• Stars
    star
    168
  • Rank 225,507 (Top 5 %)
  • Language
    Swift
  • License
    Apache License 2.0
  • Created over 7 years ago
  • Updated over 4 years ago

Reviews

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

Repository Details

TensorFlow C API Class Wrapper in Server Side Swift.

Perfect TensorFlow įŽ€äŊ“中文

Get Involved with Perfect!

Star Perfect On Github Stack Overflow Follow Perfect on Twitter Join the Perfect Slack

Swift 4.1 Platforms OS X | Linux License Apache PerfectlySoft Twitter Slack Status

This project is an experimental wrapper of TensorFlow C API which enables Machine Learning in Server Side Swift.

This package builds with Swift Package Manager and is part of the Perfect project but can also be used as an independent module.

Ensure you have installed and activated the latest Swift 4.1.1 / Xcode 9.3

Project Status

The framework conforms to TensorFlow v1.8.0 C API functionality.

Development Notes

These files are the key part of Perfect-TensorFlow:

Sources
├── PerfectTensorFlow
│   ├── APILoader.swift (1000+ lines, translated from tensorflow/c/c_api.h)
│   ├── PerfectTensorFlow.swift (2700+ lines)
└── TensorFlowAPI
    ├── TensorFlowAPI.c (72 lines)
    └── include
        └── TensorFlowAPI.h (138 lines)

All other Swift sources named as 'pb.*.swift', which is totally up to 45,000+ lines of code, are automatically generated by updateprotos.sh in the root directory. Unfortunately, if using such a script, you still need to manually edit the public typealias part listed in the PerfectTensorFlow.swift.

Up to now there is no such a plan to generate these protocol buffer files dynamically in the Swift Source since Perfect-TensorFlow is a part of Perfect, although it can run independently, all features of Perfect framework are built by Swift Package Manager for consistency consideration. However, since the project is also fast growing, all pull request, ideas, suggestions and comments are welcome!

API Guide

API programming topics can be found in Perfect TensorFlow Guide.

Also, there are many features that has already embedded in the testing script, such as TensorFlow event and summary for TensorBoard report and benchmarking. Please check the Perfect TensorFlow Testing Script for detail.

Quick Start

TensorFlow C API Library Installation

Perfect-TensorFlow is based on TensorFlow C API, i.e., libtensorflow.so and libtensorflow_framework.so on runtime. This project contains an express CPU version installation script for this module on both macOS / Ubuntu Linux, and will install both dynamic libraries into path /usr/local/lib. You can download & run install.sh. Before running this script, please make sure that curl has been installed onto your computer.

For more installation options, such as GPU/CPU and multiple versions on the same machine, please check TensorFlow website: Installing TensorFlow for C

Perfect TensorFlow Application

To use this library, add dependencies to your project's Package.swift with the LATEST TAG:

.package(url: "https://github.com/PerfectlySoft/Perfect-TensorFlow.git", from: "1.4.0")

and it also requires a dependency declaration in the same file, target section:

dependencies: ["PerfectTensorFlow"]

Then declare the library:

// TensorFlowAPI contains most API functions defined in libtensorflow.so
import TensorFlowAPI

// This is the Swift version of TensorFlow classes and objects
import PerfectTensorFlow

// To keep the naming consistency with TensorFlow in other languages such as
// Python or Java, making an alias of `TensorFlow` Class is a good idea:
public typealias TF = TensorFlow

Library Activation

⚠ī¸NOTE⚠ī¸ Prior to use ANY ACTUAL FUNCTIONS of Perfect TensorFlow framework, TF.Open() must be called first:

// this action will load all api functions defined
// in /usr/local/lib/libtensorflow.so
try TF.Open()

Please also note that you can active the library with a specific path, alternatively, especially in case of different versions or CPU/GPU library adjustment required:

// this action will load the library with the path
try TF.Open("/path/to/DLL/of/libtensorflow.so")

"Hello, Perfect TensorFlow!"

Here is the Swift version of "Hello, TensorFlow!":

// define a string tensor
let tensor = try TF.Tensor.Scalar("Hello, Perfect TensorFlow! 🇨đŸ‡ŗ🇨đŸ‡Ļ")

// declare a new graph
let g = try TF.Graph()

// turn the tensor into an operation
let op = try g.const(tensor: tensor, name: "hello")

// run a session
let o = try g.runner().fetch(op).addTarget(op).run()

// decode the result      
let decoded = try TF.Decode(strings: o[0].data, count: 1)

// check the result
let s2 = decoded[0].string
print(s2)

Matrix Operations

As you can see, Swift version of TensorFlow keeps the same principals of the original one, i.e., create tensors, save tensors into graph, define the operations and then run the session & check the result.

Here is an other simple example of matrix operations in Perfect TensorFlow:

/* Matrix Multiply:
| 1 2 |   |0 1|   |0 1|
| 3 4 | * |0 0| = |0 3|
*/
// input the matrix.
let tA = try TF.Tensor.Matrix([[1, 2], [3, 4]])
let tB = try TF.Tensor.Matrix([[0, 0], [1, 0]])

// adding tensors to graph
let g = try TF.Graph()
let A = try g.const(tensor: tA, name: "Const_0")
let B = try g.const(tensor: tB, name: "Const_1")

// define matrix multiply operation
let v = try g.matMul(l: A, r: B, name: "v", transposeB: true)

// run the session
let o = try g.runner().fetch(v).addTarget(v).run()
let m:[Float] = try o[0].asArray()
print(m)
// m shall be [0, 1, 0, 3]

Load a Saved Artificial Neural Network Model

Besides building graph & sessions in code, Perfect TensorFlow also provides a handy method to load models into runtime, i.e, generate a new session by loading a model file:

let g = try TF.Graph()

// the meta signature info defined in a saved model
let metaBuf = try TF.Buffer()

// load the session
let session = try g.load(
	exportDir: "/path/to/saved/model",
	tags: ["tag1", "tag2", ...],
	metaGraphDef: metaBuf)

Computer Vision Demo

A detailed example of Perfect TensorFlow for Computer Vision can be found in this repo: Perfect TensorFlow Demo, where you can upload any local images or draw a scribble online to test if the server can recognize the picture content:

Further Information

For more information on the Perfect project, please visit perfect.org.

Now WeChat Subscription is Available (Chinese)

More Repositories

1

Perfect

Server-side Swift. The Perfect core toolset and framework for Swift Developers. (For mobile back-end development, website and API development, and moreâ€Ļ)
Swift
13,837
star
2

PerfectDocs

Reference and documentation for Perfect (Server-side Swift). Perfect (æ”¯æŒæœåŠĄå™¨įĢ¯Swiftč¯­č¨€įš„čŊ¯äģļå‡Ŋ数åē“īŧ‰äŊŋį”¨æ–‡æĄŖå’Œå‚č€ƒæ‰‹å†Œ.
HTML
567
star
3

PerfectTemplate

Empty Perfect Starter Project.
Swift
222
star
4

Perfect-MySQL

A stand-alone Swift wrapper around the MySQL client library, enabling access to MySQL servers.
Swift
128
star
5

Perfect-Notifications

Apple Push Notifications (APNs) Server-Side library.
Swift
115
star
6

Perfect-HTTPServer

HTTP server for Perfect.
Swift
108
star
7

Perfect-CRUD

CRUD is an object-relational mapping (ORM) system for Swift 4+.
Swift
63
star
8

Perfect-Python

An expressway to import Python 2.7 modules into Server Side Swift
Swift
62
star
9

Perfect-PostgreSQL

A stand-alone Swift wrapper around the libpq client library, enabling access to PostgreSQL servers.
Swift
54
star
10

Perfect-MongoDB

A stand-alone Swift wrapper around the mongo-c client library, enabling access to MongoDB servers.
Swift
52
star
11

Perfect-SQLite

A stand-alone Swift wrapper around the SQLite 3 client library.
Swift
49
star
12

Perfect-CURL

cURL support for Perfect.
Swift
41
star
13

Perfect-Markdown

A solution to convert markdown text into html presentation in Swift, based on GerHobbelt's "upskirt" project.
Swift
41
star
14

Perfect-Heroku-Buildpack

Swift + Perfect Buildpack for Heroku
Shell
37
star
15

Perfect-Ubuntu

Install Swift and Perfect dependencies into an Ubuntu 16.04 system.
Shell
35
star
16

Perfect-FileMaker

A stand-alone Swift wrapper around the FileMaker XML Web publishing interface, enabling access to FileMaker servers.
Swift
34
star
17

Perfect-HTTP

Base HTTP Support for Perfect.
Swift
31
star
18

Perfect-Crypto

Cryptographic Operations
Swift
28
star
19

Perfect-Redis

A Swift client for Redis.
Swift
28
star
20

Perfect-LDAP

A simple Swift class wrapper of OpenLDAP.
Swift
27
star
21

Perfect-Net

Core asynchronous networking package used in Perfect. Includes support for TCP, SSL, UNIX socket files and IO event handling.
Swift
27
star
22

Perfect-Kafka

An Express Swift Client of Apache Kafka 0.8, the Stream Processing Platform
Swift
24
star
23

Perfect-Mustache

Mustache template support for Perfect.
Swift
24
star
24

Perfect-WebSockets

WebSockets support for Perfect.
Swift
23
star
25

Perfect-SysInfo

This project provides a Swift library to monitor system performance in essential metrics.
Swift
23
star
26

Perfect-Mosquitto

A Swift Class Wrapper of Perfect-libMosquitto, the MQTT client
Swift
23
star
27

Perfect-SMTP

SMTP Client for Perfect.
Swift
22
star
28

Perfect-Zip

Perfect Zip compression utility.
Swift
21
star
29

PerfectAppTemplate

Provides a structure for a larger project to grow into. It contains an HTTP Server config that loads from pre-separated Filters and Routes, a JSON config loader, and directories into which you can organize your handlers, objects and utility functions.
Swift
21
star
30

Perfect-NIO

Perfect 4 NIO
Swift
20
star
31

Perfect-Logger

File-Based Logging.
Swift
19
star
32

Perfect-Thread

Core threading library for Perfect Server Side Swift. Includes support for serial and concurrent thread queues, locks, read/write locks and events.
Swift
18
star
33

Perfect-XML

XML support for Perfect.
Swift
16
star
34

Perfect-Authentication

OAuth2 Implementations with Facebook, Google, LinkedIn, Slack, SalesForce and GitHub providers.
Swift
15
star
35

Perfect-INIParser

A lightweight INI file parser in Server Side Swift
Swift
15
star
36

Perfect-LocalMirror

Perfect Server Local Image Builder įŧ–č¯‘åŠ é€Ÿå™¨
Shell
14
star
37

Perfect-COpenSSL

C module OpenSSL import for Perfect.
C
12
star
38

Perfect-OAuth2

OAuth2 Implementations with Facebook, Google, LinkedIn, Slack, SalesForce and GitHub providers.
Swift
10
star
39

Perfect-Stripe

Server Side Swift 3 Stripe API
Swift
10
star
40

Perfect-FastCGI

FastCGI server for Perfect.
Swift
9
star
41

Perfect-MariaDB

A stand-alone Swift wrapper around the MariaDB client library, enabling access to MariaDB servers. http://www.perfect.org
Swift
9
star
42

Perfect-libxml2

libxml2 support module for Perfect.
Swift
8
star
43

Perfect-Local-Auth-PostgreSQL-Template

Template starter template for a Local Authentication - equipped server
CSS
8
star
44

PerfectAPIGenerator

Documentation generator for the Perfect API, written in Perfect.
JavaScript
8
star
45

Perfect-Hadoop

Perfect Hadoop: WebHDFS, MapReduce & Yarn.
Swift
8
star
46

PerfectDocGenerator

The Perfect Documentation build process.
Swift
7
star
47

Perfect-FastCGI-Apache2.4

mod_perfect - Apache FastCGI connector
C++
7
star
48

Perfect-ZooKeeper

A ZooKeeper Client in Swift (LINUX ONLY)
Swift
7
star
49

Perfect-LocalAuthentication-PostgreSQL

Local Authentication processes and routes
Swift
6
star
50

Perfect-COpenSSL-Linux

C module OpenSSL import for Perfect (Linux).
C++
6
star
51

Perfect-libcurl

C module libcurl import for Perfect.
C
5
star
52

Perfect-Turnstile-MongoDB

A MongoDB ORM single-package integration for Turnstile authentication.
Swift
5
star
53

Perfect-OpenLDAP

OpenLDAP C Library for Swift.
Swift
5
star
54

Perfect-LinuxBridge

C module Linux compatibility import for Perfect
C
5
star
55

Perfect-Repeater

A simple library that takes a closure and executes it at the specified interval until the closure returns false or the application is terminated.
Swift
5
star
56

Perfect-Turnstile-MySQL

A MySQL ORM single-package integration for Turnstile authentication.
Swift
5
star
57

Perfect-WebRedirects

Filter for specified routes (including trailing wildcard routes) and perform redirects as instructed if a match is found.
Swift
5
star
58

Perfect-Session-MySQL

MySQL Driver for Perfect Sessions.
Swift
4
star
59

Perfect-LocalAuthentication-MySQL

Local Authentication, MySQL module
Swift
4
star
60

Perfect-Turnstile-PostgreSQL

A PostgreSQL ORM single-package integration for Turnstile authentication.
Swift
4
star
61

Perfect-libMosquitto

C library of Mosquitto (MQTT client) for Swift
Swift
4
star
62

Perfect-Session-MongoDB

Perfect Session Drivers for MongoDB.
Swift
4
star
63

Perfect-sqlite3-support

C module import for sqlite3.
Swift
4
star
64

Perfect-Turnstile-SQLite

An SQLite ORM single-package integration for Turnstile authentication.
Swift
4
star
65

Perfect-Session

Session drivers (for use in Perfect projects).
Swift
4
star
66

Perfect-CZlib-src

C
3
star
67

PerfectTemplateFCGI

Perfect Empty Starter Project for FastCGI.
Swift
3
star
68

Perfect-libSASL

SASL C library for Swift.
C
3
star
69

Perfect-Session-Redis

Redis Driver for Perfect Sessions
Swift
3
star
70

Perfect-CouchDB

CouchDB Database Connector for Perfect.
Swift
3
star
71

Perfect-Local-Auth-MySQL-Template

CSS
3
star
72

PerfectTemplateAppEngine

Perfect Empty Starter Project for Google App Engine.
Swift
3
star
73

Perfect-SPNEGO

A general Server Side Swift library that implements SPNEGO mechanism.
C
3
star
74

Perfect-Session-PostgreSQL

PostgreSQL Driver for Perfect Sessions.
Swift
3
star
75

Perfect-mysqlclient

C module import for MySQL client.
Swift
3
star
76

Perfect-GoogleAnalytics-MeasurementProtocol

Server side Google Analytics, using Swift / Perfect
Swift
2
star
77

Perfect-ODBC

Perfect connector for ODBC databases
Swift
2
star
78

Perfect-mariadbclient

C module import for MariaDB client.
Swift
2
star
79

Perfect-NewRelic-Linux

This project provides a Swift class wrapper for New Relic Agent SDK.
Swift
2
star
80

PerfectDocsUI

User interface for Perfect Docs Dev.
JavaScript
2
star
81

Archived-Perfect-Issues

JIRA Archive of Perfect.
Swift
2
star
82

Perfect-Turnstile-CouchDB

A CouchDB ORM single-package integration for Turnstile authentication.
Swift
2
star
83

Perfect-libpq

C module import for libpq.
Swift
2
star
84

Perfect-Session-SQLite

SQLite driver for Perfect Sessions.
Swift
2
star
85

Perfect-libpq-linux

C module import for libpq.
Swift
2
star
86

Perfect-mysqlclient-Linux

C module import for MySQL client Linux.
Swift
1
star
87

Perfect-Session-CouchDB

CouchDB Driver for Perfect Sessions.
Swift
1
star
88

Perfect-CloudFormation

Support for CloudFormation server instances.
Swift
1
star
89

Perfect-mongo-c-linux

Obsolete - Perfect Mongodb c-binding for linux.
Swift
1
star
90

Perfect-NIOCompat

Perfect 3 -> 4 compatability
Swift
1
star
91

Perfect-mongo-c

Obsolete - C module import for mongo-c.
Swift
1
star
92

Perfect-Assistant-Issues

Tracking issues with Perfect Assistant
1
star
93

Perfect-mariadbclient-Linux

C module import for MariaDB client Linux.
Swift
1
star