• Stars
    star
    1,373
  • Rank 32,880 (Top 0.7 %)
  • Language
    Kotlin
  • License
    Apache License 2.0
  • Created about 4 years ago
  • Updated 7 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

High-level Deep Learning Framework written in Kotlin and inspired by Keras

KotlinDL: High-level Deep Learning API in Kotlin official JetBrains project

Kotlin Slack channel

KotlinDL is a high-level Deep Learning API written in Kotlin and inspired by Keras. Under the hood, it uses TensorFlow Java API and ONNX Runtime API for Java. KotlinDL offers simple APIs for training deep learning models from scratch, importing existing Keras and ONNX models for inference, and leveraging transfer learning for tailoring existing pre-trained models to your tasks.

This project aims to make Deep Learning easier for JVM and Android developers and simplify deploying deep learning models in production environments.

Here's an example of what a classic convolutional neural network LeNet would look like in KotlinDL:

private const val EPOCHS = 3
private const val TRAINING_BATCH_SIZE = 1000
private const val NUM_CHANNELS = 1L
private const val IMAGE_SIZE = 28L
private const val SEED = 12L
private const val TEST_BATCH_SIZE = 1000

private val lenet5Classic = Sequential.of(
    Input(
        IMAGE_SIZE,
        IMAGE_SIZE,
        NUM_CHANNELS
    ),
    Conv2D(
        filters = 6,
        kernelSize = intArrayOf(5, 5),
        strides = intArrayOf(1, 1, 1, 1),
        activation = Activations.Tanh,
        kernelInitializer = GlorotNormal(SEED),
        biasInitializer = Zeros(),
        padding = ConvPadding.SAME
    ),
    AvgPool2D(
        poolSize = intArrayOf(1, 2, 2, 1),
        strides = intArrayOf(1, 2, 2, 1),
        padding = ConvPadding.VALID
    ),
    Conv2D(
        filters = 16,
        kernelSize = intArrayOf(5, 5),
        strides = intArrayOf(1, 1, 1, 1),
        activation = Activations.Tanh,
        kernelInitializer = GlorotNormal(SEED),
        biasInitializer = Zeros(),
        padding = ConvPadding.SAME
    ),
    AvgPool2D(
        poolSize = intArrayOf(1, 2, 2, 1),
        strides = intArrayOf(1, 2, 2, 1),
        padding = ConvPadding.VALID
    ),
    Flatten(), // 3136
    Dense(
        outputSize = 120,
        activation = Activations.Tanh,
        kernelInitializer = GlorotNormal(SEED),
        biasInitializer = Constant(0.1f)
    ),
    Dense(
        outputSize = 84,
        activation = Activations.Tanh,
        kernelInitializer = GlorotNormal(SEED),
        biasInitializer = Constant(0.1f)
    ),
    Dense(
        outputSize = 10,
        activation = Activations.Linear,
        kernelInitializer = GlorotNormal(SEED),
        biasInitializer = Constant(0.1f)
    )
)


fun main() {
    val (train, test) = mnist()
    
    lenet5Classic.use {
        it.compile(
            optimizer = Adam(clipGradient = ClipGradientByValue(0.1f)),
            loss = Losses.SOFT_MAX_CROSS_ENTROPY_WITH_LOGITS,
            metric = Metrics.ACCURACY
        )
    
        it.logSummary()
    
        it.fit(dataset = train, epochs = EPOCHS, batchSize = TRAINING_BATCH_SIZE)
    
        val accuracy = it.evaluate(dataset = test, batchSize = TEST_BATCH_SIZE).metrics[Metrics.ACCURACY]
    
        println("Accuracy: $accuracy")
    }
}

Table of Contents

Library Structure

KotlinDL consists of several modules:

  • kotlin-deeplearning-api api interfaces and classes
  • kotlin-deeplearning-impl implementation classes and utilities
  • kotlin-deeplearning-onnx inference with ONNX Runtime
  • kotlin-deeplearning-tensorflow learning and inference with TensorFlow
  • kotlin-deeplearning-visualization visualization utilities
  • kotlin-deeplearning-dataset dataset classes

Modules kotlin-deeplearning-tensorflow and kotlin-deeplearning-dataset are only available for desktop JVM, while other artifacts could also be used on Android.

How to configure KotlinDL in your project

To use KotlinDL in your project, ensure that mavenCentral is added to the repositories list:

repositories {
    mavenCentral()
}

Then add the necessary dependencies to your build.gradle file.

To start with creating simple neural networks or downloading pre-trained models, just add the following dependency:

// build.gradle
dependencies {
    implementation 'org.jetbrains.kotlinx:kotlin-deeplearning-tensorflow:[KOTLIN-DL-VERSION]'
}
// build.gradle.kts
dependencies {
    implementation ("org.jetbrains.kotlinx:kotlin-deeplearning-tensorflow:[KOTLIN-DL-VERSION]")
}

Use kotlin-deeplearning-onnx module for inference with ONNX Runtime:

// build.gradle
dependencies {
    implementation 'org.jetbrains.kotlinx:kotlin-deeplearning-onnx:[KOTLIN-DL-VERSION]'
}
// build.gradle.kts
dependencies {
  implementation ("org.jetbrains.kotlinx:kotlin-deeplearning-onnx:[KOTLIN-DL-VERSION]")
}

To use the full power of KotlinDL in your project for JVM, add the following dependencies to your build.gradle file:

// build.gradle
dependencies {
    implementation 'org.jetbrains.kotlinx:kotlin-deeplearning-tensorflow:[KOTLIN-DL-VERSION]'
    implementation 'org.jetbrains.kotlinx:kotlin-deeplearning-onnx:[KOTLIN-DL-VERSION]'
    implementation 'org.jetbrains.kotlinx:kotlin-deeplearning-visualization:[KOTLIN-DL-VERSION]'
}
// build.gradle.kts
dependencies {
  implementation ("org.jetbrains.kotlinx:kotlin-deeplearning-tensorflow:[KOTLIN-DL-VERSION]")
  implementation ("org.jetbrains.kotlinx:kotlin-deeplearning-onnx:[KOTLIN-DL-VERSION]")
  implementation ("org.jetbrains.kotlinx:kotlin-deeplearning-visualization:[KOTLIN-DL-VERSION]")
}

The latest stable KotlinDL version is 0.5.2, latest unstable version is 0.6.0-alpha-1.

For more details, as well as for pom.xml and build.gradle.kts examples, please refer to the Quick Start Guide.

Working with KotlinDL in Jupyter Notebook

You can work with KotlinDL interactively in Jupyter Notebook with the Kotlin kernel. To do so, add the required dependencies in your notebook:

@file:DependsOn("org.jetbrains.kotlinx:kotlin-deeplearning-tensorflow:[KOTLIN-DL-VERSION]")

For more details on installing Jupyter Notebook and adding the Kotlin kernel, check out the Quick Start Guide.

Working with KotlinDL in Android projects

KotlinDL supports an inference of ONNX models on the Android platform. To use KotlinDL in your Android project, add the following dependency to your build.gradle file:

// build.gradle
implementation 'org.jetbrains.kotlinx:kotlin-deeplearning-onnx:[KOTLIN-DL-VERSION]'
// build.gradle.kts
implementation ("org.jetbrains.kotlinx:kotlin-deeplearning-onnx:[KOTLIN-DL-VERSION]")

For more details, please refer to the Quick Start Guide.

KotlinDL, ONNX Runtime, Android, and JDK versions

This table shows the mapping between KotlinDL, TensorFlow, ONNX Runtime, Compile SDK for Android and minimum supported Java versions.

KotlinDL Version Minimum Java Version ONNX Runtime Version TensorFlow Version Android: Compile SDK Version
0.1.* 8 1.15
0.2.0 8 1.15
0.3.0 8 1.8.1 1.15
0.4.0 8 1.11.0 1.15
0.5.0-0.5.1 11 1.12.1 1.15 31
0.5.2 11 1.14.0 1.15 31
0.6.* 11 1.14.0 1.15 31

Documentation

Examples and tutorials

You do not need prior experience with Deep Learning to use KotlinDL.

We are working on including extensive documentation to help you get started. At this point, please feel free to check out the following tutorials we have prepared:

For more inspiration, take a look at the code examples in this repository and Sample Android App.

Running KotlinDL on GPU

To enable the training and inference on a GPU, please read this TensorFlow GPU Support page and install the CUDA framework to allow calculations on a GPU device.

Note that only NVIDIA devices are supported.

You will also need to add the following dependencies in your project if you wish to leverage a GPU:

// build.gradle
implementation 'org.tensorflow:libtensorflow:1.15.0'
implementation 'org.tensorflow:libtensorflow_jni_gpu:1.15.0'
// build.gradle.kts
implementation ("org.tensorflow:libtensorflow:1.15.0")
implementation ("org.tensorflow:libtensorflow_jni_gpu:1.15.0")

On Windows, the following distributions are required:

For inference of ONNX models on a CUDA device, you will also need to add the following dependencies to your project:

// build.gradle
api 'com.microsoft.onnxruntime:onnxruntime_gpu:1.14.0'
// build.gradle.kts
api("com.microsoft.onnxruntime:onnxruntime_gpu:1.14.0")

To find more info about ONNXRuntime and CUDA version compatibility, please refer to the ONNXRuntime CUDA Execution Provider page.

Logging

By default, the API module uses the kotlin-logging library to organize the logging process separately from the specific logger implementation.

You could use any widely known JVM logging library with a Simple Logging Facade for Java (SLF4J) implementation such as Logback or Log4j/Log4j2.

You will also need to add the following dependencies and configuration file log4j2.xml to the src/resource folder in your project if you wish to use log4j2:

// build.gradle
implementation 'org.apache.logging.log4j:log4j-api:2.17.2'
implementation 'org.apache.logging.log4j:log4j-core:2.17.2'
implementation 'org.apache.logging.log4j:log4j-slf4j-impl:2.17.2'
// build.gradle.kts
implementation("org.apache.logging.log4j:log4j-api:2.17.2")
implementation("org.apache.logging.log4j:log4j-core:2.17.2")
implementation("org.apache.logging.log4j:log4j-slf4j-impl:2.17.2")
<Configuration status="WARN">
    <Appenders>
        <Console name="STDOUT" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n"/>
        </Console>
    </Appenders>

    <Loggers>
        <Root level="debug">
            <AppenderRef ref="STDOUT" level="DEBUG"/>
        </Root>
        <Logger name="io.jhdf" level="off" additivity="true">
            <appender-ref ref="STDOUT" />
        </Logger>
    </Loggers>
</Configuration>

If you wish to use Logback, include the following dependency and configuration file logback.xml to src/resource folder in your project

// build.gradle
implementation 'ch.qos.logback:logback-classic:1.4.5'
// build.gradle.kts
implementation("ch.qos.logback:logback-classic:1.4.5")
<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="info">
        <appender-ref ref="STDOUT"/>
    </root>
</configuration>

These configuration files can be found in the examples module.

Fat Jar issue

There is a known Stack Overflow question and TensorFlow issue with Fat Jar creation and execution on Amazon EC2 instances.

java.lang.UnsatisfiedLinkError: /tmp/tensorflow_native_libraries-1562914806051-0/libtensorflow_jni.so: libtensorflow_framework.so.1: cannot open shared object file: No such file or directory

Despite the fact that the bug describing this problem was closed in the release of TensorFlow 1.14, it was not fully fixed and required an additional line in the build script.

One simple solution is to add a TensorFlow version specification to the Jar's Manifest. Below is an example of a Gradle build task for Fat Jar creation.

// build.gradle

task fatJar(type: Jar) {
    manifest {
        attributes 'Implementation-Version': '1.15'
    }
    classifier = 'all'
    from { configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) } }
    with jar
}
// build.gradle.kts

plugins {
    kotlin("jvm") version "1.5.31"
    id("com.github.johnrengelman.shadow") version "7.0.0"
}

tasks{
    shadowJar {
        manifest {
            attributes(Pair("Main-Class", "MainKt"))
            attributes(Pair("Implementation-Version", "1.15"))
        }
    }
}

Limitations

Currently, only a limited set of deep learning architectures are supported. Here's the list of available layers:

  • Core layers:
    • Input, Dense, Flatten, Reshape, Dropout, BatchNorm.
  • Convolutional layers:
    • Conv1D, Conv2D, Conv3D;
    • Conv1DTranspose, Conv2DTranspose, Conv3DTranspose;
    • DepthwiseConv2D;
    • SeparableConv2D.
  • Pooling layers:
    • MaxPool1D, MaxPool2D, MaxPooling3D;
    • AvgPool1D, AvgPool2D, AvgPool3D;
    • GlobalMaxPool1D, GlobalMaxPool2D, GlobalMaxPool3D;
    • GlobalAvgPool1D, GlobalAvgPool2D, GlobalAvgPool3D.
  • Merge layers:
    • Add, Subtract, Multiply;
    • Average, Maximum, Minimum;
    • Dot;
    • Concatenate.
  • Activation layers:
    • ELU, LeakyReLU, PReLU, ReLU, Softmax, ThresholdedReLU;
    • ActivationLayer.
  • Cropping layers:
    • Cropping1D, Cropping2D, Cropping3D.
  • Upsampling layers:
    • UpSampling1D, UpSampling2D, UpSampling3D.
  • Zero padding layers:
    • ZeroPadding1D, ZeroPadding2D, ZeroPadding3D.
  • Other layers:
    • Permute, RepeatVector.

TensorFlow 1.15 Java API is currently used for layer implementation, but this project will be switching to TensorFlow 2.+ in the nearest future. This, however, does not affect the high-level API. Inference with TensorFlow models is currently supported only on desktops.

Contributing

Read the Contributing Guidelines.

Reporting issues/Support

Please use GitHub issues for filing feature requests and bug reports. You are also welcome to join the #kotlindl channel in Kotlin Slack.

Code of Conduct

This project and the corresponding community are governed by the JetBrains Open Source and Community Code of Conduct. Please make sure you read it.

License

KotlinDL is licensed under the Apache 2.0 License.

More Repositories

1

anko

Pleasant Android application development
Kotlin
15,927
star
2

kotlinx.coroutines

Library support for Kotlin coroutines
Kotlin
12,203
star
3

kotlinx.serialization

Kotlin multiplatform / multi-format serialization
Kotlin
4,951
star
4

dokka

API documentation engine for Kotlin
Kotlin
3,220
star
5

kotlin-examples

Various examples for Kotlin
3,177
star
6

KEEP

Kotlin Evolution and Enhancement Process
Markdown
3,109
star
7

kotlin-koans

Kotlin workshop
Kotlin
2,602
star
8

kotlinx-datetime

KotlinX multiplatform date/time library
Kotlin
2,166
star
9

kmm-production-sample

This is an open-source, mobile, cross-platform application built with Kotlin Multiplatform Mobile. It's a simple RSS reader, and you can download it from the App Store and Google Play. It's been designed to demonstrate how KMM can be used in real production projects.
Kotlin
1,868
star
10

coroutines-examples

Examples for coroutines design in Kotlin
1,465
star
11

kotlin-fullstack-sample

Kotlin Full-stack Application Example
Kotlin
1,218
star
12

kotlinx-kover

Kotlin
1,185
star
13

kotlinx.collections.immutable

Immutable persistent collections for Kotlin
Kotlin
1,064
star
14

kotlin-jupyter

Kotlin kernel for Jupyter/IPython
Kotlin
1,037
star
15

kotlinx-cli

Pure Kotlin implementation of a generic CLI parser.
Kotlin
893
star
16

kmm-basic-sample

Example of Kotlin multiplatform project
Kotlin
887
star
17

kotlinx-io

Kotlin multiplatform I/O library
Kotlin
817
star
18

kotlinx-atomicfu

The idiomatic way to use atomic operations in Kotlin
Kotlin
716
star
19

binary-compatibility-validator

Public API management tool
Kotlin
714
star
20

dataframe

Structured data processing in Kotlin
Kotlin
700
star
21

kotlinconf-spinner

Kotlin
603
star
22

workshop

JetBrains Kotlin Workshop Material
Kotlin
594
star
23

kotlin-interactive-shell

Kotlin Language Interactive Shell
Java
574
star
24

kotlin-frontend-plugin

Gradle Kotlin (http://kotlinlang.org) plugin for frontend development
Kotlin
570
star
25

multik

Kotlin
550
star
26

dukat

Converter of <any kind of declarations> to Kotlin external declarations
Kotlin
535
star
27

kdoctor

Environment analysis tool
Kotlin
509
star
28

kotlin-wasm-examples

Examples with Kotlin/Wasm
Kotlin
449
star
29

kotlin-spark-api

This projects gives Kotlin bindings and several extensions for Apache Spark. We are looking to have this as a part of Apache Spark 3.x
Kotlin
435
star
30

kandy

Kotlin plotting library.
Kotlin
429
star
31

kotlin-by-example

The sources of Kotlin by Example.
396
star
32

kotlinx-benchmark

Kotlin multiplatform benchmarking toolkit
Kotlin
387
star
33

kotlin-spec

Kotlin Language Specification:
Kotlin
358
star
34

kotlin-in-action

Code samples from the "Kotlin in Action" book
Kotlin
343
star
35

ts2kt

ts2kt is officially deprecated, please use https://github.com/Kotlin/dukat instead. // Converter of TypeScript definition files to Kotlin external declarations
Kotlin
320
star
36

kotlin-numpy

Kotlin bindings for NumPy
Kotlin
312
star
37

kotlin-style-guide

Work-in-progress notes for the Kotlin style guide
289
star
38

kotlinx-knit

Kotlin source code documentation management tool
Kotlin
287
star
39

anko-example

A small application built with Anko DSL
Kotlin
285
star
40

full-stack-web-jetbrains-night-sample

Full-stack demo application written with Kotlin MPP
Kotlin
271
star
41

kotlin-script-examples

Examples of Kotlin Scripts and usages of the Kotlin Scripting API
Kotlin
262
star
42

kotlinx-nodejs

Kotlin external declarations for using the Node.js API from Kotlin code targeting JavaScript
Kotlin
212
star
43

kotlin-eclipse

Kotlin Plugin for Eclipse
Kotlin
185
star
44

kotlinx.reflect.lite

Lightweight library allowing to introspect basic stuff about Kotlin symbols
Kotlin
150
star
45

api-guidelines

Best practices to consider when writing an API for your library
143
star
46

kotlin-benchmarks

This is the project to verify and investigate performance issues in Kotlin and standard library.
Kotlin
136
star
47

kotlin-libs-publisher

Gradle plugin for publishing of Kotlin libs
Kotlin
114
star
48

KMP-App-Template

Kotlin Multiplatform app template with shared UI
Kotlin
100
star
49

kotlinx-browser

Kotlin browser API
Kotlin
100
star
50

kotlindl-app-sample

This repo demonstrates how to use KotlinDL for neural network inference on Android devices.
Kotlin
96
star
51

kotlin-koans-edu

Kotlin Koans for Educational Plugin and play.kotl.in
Kotlin
93
star
52

grammar-tools

Tokenization and parsing Kotlin code using the ANTLR Kotlin grammar
Kotlin
83
star
53

kmm-integration-sample

Kotlin
76
star
54

kmm-with-cocoapods-sample

This project represents the case when Cocoapods dependencies are added in Kotlin and there is no existing Xcode project
Kotlin
57
star
55

kotlin-koans-edu-obsolete

Obsolete: check https://github.com/Kotlin/kotlin-koans-edu for the latest version.
Kotlin
55
star
56

kotlin-native-calculator-sample

55
star
57

kotlinx.support

Extension and top-level functions to use JDK7/JDK8 features in Kotlin 1.0
Kotlin
54
star
58

js-externals

External declarations for Kotlin/JS
53
star
59

coroutines-workshop

Materials for a full-day workshop on Kotlin Coroutines
Kotlin
42
star
60

kotlin-playground-wp-plugin

WordPress plugin which allows to embed interactive Kotlin playground to any post via [kotlin] shortcode
PHP
35
star
61

io2019-serverside-demo

E2E Sample
Kotlin
31
star
62

kotlin-jupyter-libraries

Library descriptors for Kotlin kernel for Jupyter
23
star
63

kmm-with-cocoapods-multitarget-xcode-sample

This project is intended to demonstrate how to connect Kotlin library to Xcode project with several targets: iOS, macOS, tvOS, watchOS
Swift
23
star
64

kmp-native-wizard

A mostly-empty template to get started creating a Kotlin/Native project.
Kotlin
22
star
65

KMP-App-Template-Native

Kotlin Multiplatform app template with native UI
Kotlin
22
star
66

xcode-compat

AppCode helper for Kotlin/Native and Xcode
Kotlin
21
star
67

kotlin-in-action-2e

Code samples for the second edition of "Kotlin in Action".
Kotlin
20
star
68

kotlinx.dom

Kotlin
17
star
69

dokka-plugin-template

Dokka plugin quickstart template with pre-configured dependencies and publishing
Kotlin
13
star
70

kotlin-wasm-benchmarks

Kotlin Multiplatform Collection of Benchmarks focused on Kotlin/Wasm performance
Kotlin
12
star
71

kotlinx.team.infra

Kotlin
10
star
72

multiplatform-library-template

Kotlin
10
star
73

kotlin-js-inspection-pack-plugin

Adds useful inspections, intentions, and quick-fixes for working with Kotlin/JS projects.
Kotlin
10
star
74

kotlin-wasm-compose-template

A template repository for Compose Multiplatform with Kotlin/Wasm target
Kotlin
9
star
75

obsolete-kotlin-swing

Experimental library providing some helper functions and extensions for creating Swing user interfaces.
Kotlin
8
star
76

kotlin-in-action-2e-jkid

Sample project accompanying the second edition of "Kotlin in Action". JSON serialization/deserialization library for Kotlin data classes
Kotlin
8
star
77

obsolete-kotlin-jdbc

Experimental library providing some helper functions and extensions for working with JDBC in Kotlin.
Kotlin
7
star
78

community-project-gradle-plugin

Kotlin
6
star
79

website-grammar-generator

Kotlin ANTLR grammar converter to XML for the Kotlin website or text file
Kotlin
6
star
80

kotlin-grammar-gpl2

Kotlin grammar ANTLR sources (under GPLv2)
ANTLR
6
star
81

kotlin-spark-shell

Kotlin Language support for Apache Spark
Kotlin
5
star
82

web-site-samples

Examples repository for kotlinlang.org
4
star
83

kotlin-wasm-browser-template

A template repository for Kotlin/Wasm on browser
HTML
4
star
84

kotlin-cocoapods-spec

Ruby
3
star
85

kotlin-build-report-sample

Kotlin
3
star
86

spec-tests-relinking-recommender

Tool for relinking recommendation of the Kotlin compiler spec tests, that are inconsistent to the latest Kotlin specification
Python
1
star
87

kmm-with-cocoapods-xcode-two-kotlin-libraries-sample

This project is intended to demonstrate the connection of two Kotlin libraries to existing Xcode project through Cocoapods
Kotlin
1
star
88

kotlin-wasm-wasi-template

A template repository for Kotlin/Wasm with WASI
Kotlin
1
star