• Stars
    star
    1,270
  • Rank 37,046 (Top 0.8 %)
  • Language
    Swift
  • License
    MIT License
  • Created over 7 years ago
  • Updated over 6 years ago

Reviews

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

Repository Details

A neural network toolkit for Metal

Forge: a neural network toolkit for Metal

⚠️ ⚠️ ⚠️ IMPORTANT: I'm no longer maintaining Forge. It uses an older version of the MPSCNN API that is no longer supported by Apple. I also feel that Core ML has largely taken away the need for a library like this. However, neural networks implemented in Metal are still faster than Core ML. If you're looking for very fast implementations of MobileNet V1, MobileNet V2, and SSD for iOS and macOS, check out my new source code library.


Forge is a collection of helper code that makes it a little easier to construct deep neural networks using Apple's MPSCNN framework.

Read the blog post

Geordi likes it!

What does this do?

Features of Forge:

Conversion functions. MPSCNN uses MPSImages and MTLTextures for everything, often using 16-bit floats. But you probably want to work with Swift [Float] arrays. Forge's conversion functions make it easy to work with Metal images and textures.

Easy layer creation. Reduce the boilerplate when building the layers for your neural network. Forge's domain-specific language makes defining a neural net as simple as:

let input = Input()

let output = input
        --> Resize(width: 28, height: 28)
        --> Convolution(kernel: (5, 5), channels: 20, activation: relu, name: "conv1")
        --> MaxPooling(kernel: (2, 2), stride: (2, 2))
        --> Convolution(kernel: (5, 5), channels: 50, activation: relu, name: "conv2")
        --> MaxPooling(kernel: (2, 2), stride: (2, 2))
        --> Dense(neurons: 320, activation: relu, name: "fc1")
        --> Dense(neurons: 10, name: "fc2")
        --> Softmax()

let model = Model(input: input, output: output)

Custom layers. MPSCNN only supports a limited number of layers, so we've added a few of our own:

  • Depth-wise convolution
  • Transpose channels
  • Deconvolution (coming soon!)

Preprocessing kernels. Often you need to preprocess data before it goes into the neural network. Forge comes with a few handy kernels for this:

  • SubtractMeanColor
  • RGB2Gray
  • RGB2BGR

Custom compute kernels. Many neural networks require custom compute kernels, so Forge provides helpers that make it easy to write and launch your own kernels.

Debugging tools. When you implement a neural network in Metal you want to make sure it actually computes the correct thing. Due to the way Metal encodes the data, inspecting the contents of the MTLTexture objects is not always straightforward. Forge can help with this.

Example projects. Forge comes with a number of pretrained neural networks, such as LeNet-5 on MNIST, Inception3 on ImageNet, and MobileNets.

Note: A lot of the code in this library is still experimental and subject to change. Use at your own risk!

iOS 10 and iOS 11 compatibility

Forge supports both iOS 10 and iOS 11.

Forge must be compiled with Xcode 9 and the iOS 11 SDK. (An older version is available under the tag xcode8, but is no longer supported.)

Important changes:

The order of the weights for DepthwiseConvolution layers has changed. It used to be:

[kernelHeight][kernelWidth][channels]

now it is:

[channels][kernelHeight][kernelWidth]

This was done to make this layer compatible with MPS's new depthwise convolution. On iOS 10, Forge will use its own DepthwiseConvolutionKernel, on iOS 11 and later is uses the MPS version (MPSCNNDepthWiseConvolutionDescriptor).

Note: Forge does not yet take advantage of all the MPS improvements in iOS 11, such as the ability to load batch normalization parameters or loading weights via data sources. This functionality will be added in a future version.

Run the examples!

To see a demo of Forge in action, open Forge.xcworkspace in Xcode and run one of the example apps on your device.

You need at least Xcode 9 and a device with an A8 processor (iPhone 6 or better) running iOS 10 or later. You cannot build for the simulator as it does not support Metal.

The included examples are:

MNIST

This example implements a very basic LeNet5-type neural network, trained on the MNIST dataset for handwritten digit recognition.

Run the app and point the camera at a handwritten digit (there are some images in the Test Images folder you can use for this) and the app will tell you what digit it is, and how sure it is of this prediction.

MNIST example

The small image in the top-left corner shows what the network sees (this is the output of the preprocessing shader that attempts to increase the contrast between black and white).

There are two targets in this project:

  • MNIST
  • MNIST-DSL

They do the exact same thing, except the first one is written with straight MPSCNN code and the second one uses the Forge DSL and is therefore much easier to read.

Inception-v3

Google's famous Inception network for image classification. Point your phone at some object and the app will give you its top-5 predictions:

Inception example

The Inception example app is based on Apple's sample code but completely rewritten using the DSL. We use their learned parameters. Thanks, Apple!

YOLO

YOLO is an object detection network. It can detect multiple objects in an image and will even tell you where they are!

YOLO example

The example app implements the Tiny YOLO network, which is not as accurate as the full version of YOLO9000 and can detect only 20 different kinds of objects.

YOLO9000: Better, Faster, Stronger by Joseph Redmon and Ali Farhadi (2016).

MobileNets

The MobileNets example app is an implementation of the network architecture from the paper MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications.

It works like Inception-v3 but is much faster. On the iPhone 6s it runs at 20 FPS with only moderate-to-high energy usage.

Forge uses the pretrained weights from shicai/MobileNet-Caffe.

How to add Forge to your own project

Use Xcode 9 or better.

  1. Copy the Forge folder into your project.
  2. Use File > Add Files to "YourProject" > Forge.xcodeproj to add the Forge project inside your own project.
  3. Drag Products/Forge.framework into the Embedded Binaries section of your project settings.
  4. import Forge in your code.

NOTE: You cannot build for the simulator, only for "Generic iOS Device" or an actual device with arm64 architecture.

How to use Forge

Where are the unit tests?

Run the ForgeTests app on a device.

The reason the tests are in a separate app is that Metal does not work on the simulator and Xcode can't run logic tests on the device. Catch-22.

TODO

Forge is under active development. Here is the list of bugs and upcoming features.

License and credits

Forge is copyright 2016-2017 Matthijs Hollemans and is licensed under the terms of the MIT license.

More Repositories

1

neural-engine

Everything we actually know about the Apple Neural Engine (ANE)
2,049
star
2

CoreMLHelpers

Types and functions that make it a little easier to work with Core ML in Swift.
Swift
1,373
star
3

YOLO-CoreML-MPSNNGraph

Tiny YOLO for iOS implemented using CoreML but also using the new MPS graph API.
Swift
936
star
4

MobileNet-CoreML

The MobileNet neural network using Apple's new CoreML framework
Swift
705
star
5

MHTabBarController

A custom tab bar controller for iOS 5
Objective-C
488
star
6

TensorFlow-iOS-Example

Source code for my blog post "Getting started with TensorFlow on iOS"
Swift
441
star
7

BlazeFace-PyTorch

The BlazeFace face detector model implemented in PyTorch
Jupyter Notebook
427
star
8

coreml-survival-guide

Source code for the book Core ML Survival Guide
Python
246
star
9

MHRotaryKnob

UIControl for iOS that acts like a rotary knob
Objective-C
196
star
10

VGGNet-Metal

iPhone version of the VGGNet convolutional neural network for image recognition
Swift
182
star
11

Swift-3D-Demo

Shows how to draw a 3D object without using shaders
Swift
180
star
12

synth-plugin-book

Source code for the book Code Your Own Synth Plug-Ins With C++ and JUCE
C++
172
star
13

MHLazyTableImages

This project is now deprecated.
Objective-C
157
star
14

SoundBankPlayer

Sample-based audio player for iOS that uses OpenAL.
Objective-C
156
star
15

reliability-diagrams

Reliability diagrams visualize whether a classifier model needs calibration
Jupyter Notebook
136
star
16

MHPagingScrollView

A UIScrollView subclass that shows previews of the pages on the left and right.
Objective-C
132
star
17

mda-plugins-juce

JUCE implementations of the classic MDA audio plug-ins
C
124
star
18

TheKissOfShame

DSP Magnetic Tape Emulation
C++
103
star
19

metal-gpgpu

Collection of notes on how to use Apple’s Metal API for compute tasks
101
star
20

coreml-training

Source code for my blog post series "On-device training with Core ML"
Jupyter Notebook
99
star
21

Inception-CoreML

Running Inception-v3 on Core ML
Swift
97
star
22

Matrix

A fast matrix type for Swift
Swift
94
star
23

AudioBufferPlayer

Class for doing simple iOS sound synthesis using Audio Queues.
Objective-C
85
star
24

MHNibTableViewCell

This code is now deprecated.
Objective-C
79
star
25

CoreML-Custom-Layers

Source code for the blog post "Custom Layers in Core ML"
Swift
72
star
26

InsideCoreML

Python script to examine Core ML's mlmodel files
Python
64
star
27

BNNS-vs-MPSCNN

Compares the speed of Apple's two deep learning frameworks: BNNS and Metal Performance Shaders
Swift
61
star
28

TransparentJPEG

Allows you to combine a JPEG with a second image to give it transparency.
Objective-C
59
star
29

TinyML-HelloWorld-ArduinoUno

The TinyML "Hello World" sine wave model on Arduino Uno v3
Jupyter Notebook
48
star
30

synth-recipes

Code snippets of sound synthesis algorithms in C++
C++
47
star
31

WashedOut

Color theme for Xcode 8 based on the colors from the WWDC 2016 slides
42
star
32

RNN-Drummer-Swift

Using a recurrent neural network to teach the iPhone to play drums
Python
42
star
33

BuildYourOwnLispInSwift

A simple LISP interpreter written in Swift
Swift
36
star
34

SemanticSegmentationMetalDemo

Drawing semantic segmentation masks with Metal
Swift
33
star
35

krunch

Lowpass filter + saturation audio effect plug-in
C++
32
star
36

MHSemiModal

Category on UIViewController that makes it easy to present modal view controllers that only partially cover the screen.
Objective-C
31
star
37

Deepfish

Live visualization of convolutional neural network using the iPhone's camera
Swift
24
star
38

MPS-Matrix-Multiplication

Playing with the Metal Performance Shaders matrix multiplication kernel
Swift
24
star
39

fft-juce

Example code for my blog post FFT Processing in JUCE
C++
23
star
40

MHPopoverManager

A simple class for managing the lifecycle of your UIPopoverControllers
Objective-C
23
star
41

sefr-swift

The SEFR classifier implemented in Swift
Swift
21
star
42

Railroad-Diagrams-Swift

Library for making railroad diagrams in Swift
Swift
19
star
43

AVBufferPlayer

Shows how to use AVAudioPlayer to play a buffer of waveform data that you give it.
Objective-C
17
star
44

GalaxyApocalypse

My January 2013 game for #OneGameADay (iPhone). The galaxy is falling apart and it's your job to move all the planets back to where they belong. Lots of swiping involved.
Objective-C++
15
star
45

airwindows-juce

JUCE versions of selected Airwindows plug-ins
C++
12
star
46

MHTintHelper

Tool that quickly lets you pick tint colors for navigation bars etc.
Objective-C
12
star
47

levels

Basic digital level meter plug-in.
C++
11
star
48

MHDatabase

A simple Objective-C wrapper around the sqlite3 functions.
Objective-C
11
star
49

Ignition

PyTorch helper code
Python
10
star
50

Logistic-Regression-Swift

A basic example of how to implement logistic regression in Swift
Swift
9
star
51

ShrinkPng

Simple tool for shrinking images 50% by averaging the color (and alpha) of each 2x2 pixel block.
Objective-C
9
star
52

MHOverlayWindow

A simple example of how to make a UIWindow that appears on top of everything else, including the status bar.
Objective-C
7
star
53

pumpkin

Everything must bounce!
Swift
7
star
54

MHOverride

Category on NSObject that lets you override methods on existing objects using blocks, without having to make a subclass.
Objective-C
7
star
55

ThreeBandEQ

Simple bass/mids/treble equalizer plugin written in JUCE
C++
5
star
56

bombaz

Simple bass synth VSTi based on window function synthesis
C++
5
star
57

RWDevCon-App-Architecture

Source code for my RWDevCon talk on app architecture.
Swift
3
star
58

MHMetaColors

Category that allows you to write, for example, [UIColor xFF3399] to make a new UIColor object with values #FF3399.
Objective-C
3
star
59

rubberneck

handy utility for monitoring levels and protecting ears while developing plug-ins
C++
3
star
60

RWDevCon-Swift-Closures-Generics

Source code for my RWDevCon talk on Swift closures and generics.
Swift
2
star
61

hollance

1
star
62

hollance.github.io

CSS
1
star