Skip to content

Instantly share code, notes, and snippets.

@johndpope
Last active July 14, 2020 15:58
Show Gist options
  • Save johndpope/7ad704adf84f4ff6dbf48da6abde31f7 to your computer and use it in GitHub Desktop.
Save johndpope/7ad704adf84f4ff6dbf48da6abde31f7 to your computer and use it in GitHub Desktop.
Create an xcode project / mac executable for swift for tensorflow
// Save into a Sources folder
import TensorFlow
struct MLPClassifier {
var w1 = Tensor<Float>(shape: [2, 4], repeating: 0.1)
var w2 = Tensor<Float>(shape: [4, 1], scalars: [0.4, -0.5, -0.5, 0.4])
var b1 = Tensor<Float>([0.2, -0.3, -0.3, 0.2])
var b2 = Tensor<Float>([[0.4]])
func prediction(for x: Tensor<Float>) -> Tensor<Float> {
let o1 = tanh(matmul(x, w1) + b1)
return tanh(matmul(o1, w2) + b2)
}
}
let input = Tensor<Float>([[0.2, 0.8]])
let classifier = MLPClassifier()
let prediction = classifier.prediction(for: input)
print(prediction)
name: SwiftTensorflow
options:
bundleIdPrefix: com.swiftTensorflow
targets:
SwiftTensorflow:
type: tool
platform: macOS
deploymentTarget: "10.13"
sources:
- Sources
dependencies:
- framework: /Library/Developer/Toolchains/swift-latest/usr/lib/swift/macosx/libtensorflow_framework.so
- framework: /Library/Developer/Toolchains/swift-latest/usr/lib/swift/macosx/libtensorflow.so
- framework: libpython2.7.tbd
SWIFT_OPTIMIZATION_LEVEL: -O
LD_RUNPATH_SEARCH_PATHS: "/Library/Developer/Toolchains/swift-latest/usr/lib/swift/macosx"
OTHER_LDFLAGS: -lpython
@johndpope
Copy link
Author

johndpope commented Jan 3, 2019

brew install xcodegen
(move the main.swift file into a folder called Sources)
xcodegen generate
open project
File > Project Settings > Build System > Legacy Build System (otherwise you'll see TensorFlow not found error)
yonaskolb/XcodeGen#470

N.B. - if you upgrade toolchain - ensure that swift-latest symlink is correct.
You can force it to update by pointing to latest toolchain
eg. swift-tensorflow-DEVELOPMENT-2018-12-04-a.xctoolchain

sudo rm -rf /Library/Developer/Toolchains/swift-latest
sudo ln -s  /Library/Developer/Toolchains/swift-tensorflow-DEVELOPMENT-2018-12-04-a.xctoolchain/ /Library/Developer/Toolchains/swift-latest

@sudoflex
Copy link

Thanks for this quick boilerplate hack.
I'm running into a confusing error. I reported it here.
Do you have an idea about how to fix this?

@johndpope
Copy link
Author

I just saw this message - sorry @bobuntu - I'm updating my config / still hitting a problem though / @unknown attribute 'differentiable'
https://gist.github.com/johndpope/b91748d307b2a49e710d8d0580bd52a8

There's a bit of flux with migration to swift 5 / xcode 10.2 I'm forcing things to compile using swift 4.2 - but may have to resort to rolling back to xcode 10. I'm looking to test driving https://github.com/regrettable-username/style-transfer (currently only working on ubuntu that I can tell)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment