Sideloading Swift on Google Colab, post-mortem Swift for TensorFlow

Overview

Swift-Colab

How to run Swift on Google Colab

Copy this template of a Swift Colab notebook. Do not create one directly from Google Drive, as notebooks are configured for Python by default. Copy the following command into the first code cell and run it:

!curl "https://raw.githubusercontent.com/philipturner/swift-colab/pre-release/0.1/install_swift.sh" --output "install_swift.sh" && bash "install_swift.sh" "5.5.2" #// Replace 5.5.2 with newest Swift version
import Swift; Swift.precondition("" != "This statement restarts the Jupyter kernel in Python, but does nothing in Swift.")

Warning: The main branch frequently changes and may break Colab support. The above command pulls from the pre-release/0.1 branch.

In the output stream, you will see:

...
=== Downloading Swift ===
...
=== Swift successfully downloaded ===
...
=== Swift successfully installed ===
...
(a brief message about why Google Colab restarted)

The kernel will crash and automatically reconnect. That's expected, because it refreshes the runtime and lets Swift override the Python kernel.

Tip: If you factory reset the runtime or exceed the time limit, Colab will restart in Python mode. Just re-run the first code cell, and you will return to Swift mode.

Tip: Do not attempt to run any other code cells while Swift is downloading. Otherwise, Colab may indefinitely wait to reconnect after restarting in Swift mode.

Type anything into the next code cell and it echoes as output. At this time, Swift-Colab can sideload an incomplete Jupyter kernel and modify syntax coloring. Code execution and auto-completion are still in the works.

Comments
  • Not working with swift-numerics

    Not working with swift-numerics

    After some experiments I found a bug. It seems to be because I use swift-numerics in the function. https://colab.research.google.com/drive/1TL70U_I_2wEIyzSa5quB55h54A79bDtp?usp=sharing

    opened by damuellen 12
  • Automatically restart runtime

    Automatically restart runtime

    There's an easy way to restart the runtime without the arduous task of clicking the menu! Found on StackOverflow.

    import os
    os.kill(os.getpid(), 9)
    

    I also added some comments to explain the benign error messages that appear.

    I'm not sure where to PR the Colab notebook itself.

    opened by BrianHenryIE 11
  • Creating Task crashes the runtime

    Creating Task crashes the runtime

    Swift 5.6.1, Swift-Colab Install Script Latest Release (v2.0), Google-Colab.

    I tried to test concurrency, but it fails to launch anything. Creating any Task (structured or detached) on top level crashes the runtime.

    First I imported Foundation and _Concurrency. Without _Concurrency it just doesn't recognise Task.

    import Foundation
    import _Concurrency
    

    And then launching one of the following crashes:

    Task {
        for i in 1...100{
            print(i)
            try? await Task.sleep(nanoseconds: 1_000_000_000)
        }
    }
    
    Task {}
    
    Task.detached {}
    

    I don't know if it will help, but here's the log I got. It seems like it just contains bunch of restart messages.

    app.log

    bug 
    opened by jtodaone 8
  • Incorrect rendering of Pandas DataFrame + unexpected LLDB import behavior

    Incorrect rendering of Pandas DataFrame + unexpected LLDB import behavior

    I have seen this bug around for quite some time now. IIRC, the bug existed when Google sponsored S4TF. Pandas DataFrames are having their columns rearranged before rendering to the Colab GUI. This happens roughly 50% of the time that you render a DataFrame:

    Screen Shot 2022-08-11 at 8 15 36 AM Screen Shot 2022-08-11 at 8 12 47 AM

    Code to reproduce:

    %install-swiftpm-flags $clear
    %install '.package(url: "https://github.com/pvieito/PythonKit.git", .branch("master"))' PythonKit
    %install '.package(url: "https://github.com/KarthikRIyer/swiftplot", .branch("master"))' SwiftPlot AGGRenderer
    %include "EnableIPythonDisplay.swift"
    import Foundation
    import PythonKit
    import SwiftPlot
    import AGGRenderer
    
    let display = Python.import("IPython.display")
    let pd = Python.import("pandas")
    display.display(pd.DataFrame.from_records([["col 1": 3, "col 2": 5], ["col 1": 8, "col 2": 2]]))
    

    This could be a symptom of feeding the data through LLDB. If it was serialized through JSON with my new inter-process piping mechanism, perhaps it would always render correctly.

    opened by philipturner 3
  • Various problems with building Swift packages

    Various problems with building Swift packages

    When building Swift packages, there are multiple problems:

    1. The formatting from build output could leak out and make a hard-coded message about Clang modules turn green.
    2. There is an error of build.db missing when compiling a Swift package with the --verbose flag, at least with S4TF.
    3. Two module.modulemap files that declare the same Clang module can overwrite each other, even if one is part of the documentation of a Swift package and never actually involved in the build process. This happened with the modulemap currently in the Utilities directory of s4tf/s4tf.
    4. The headers referenced by a modulemap file are absent when you re-load the package. The -Xcc -I/... flags from when you built the package helped SwiftPM locate headers. Now that LLDB is loading the module with no knowledge of those manual includes, it doesn't know where the headers are.
    5. https://github.com/apple/swift/issues/58916 is still an issue and I don't have a workaround for it.

    For some of these problems, a workaround may not be possible or feasible. Thus, I might have to make documentation warning the user to copy certain header files to the system include path. Or, I might have to warn against adding duplicate modulemap files to a GitHub repo and anything it recursively depends on.

    bug 
    opened by philipturner 3
  • Extra slash in error stack trace

    Extra slash in error stack trace

    I was working on reproducing a crash in swift-reflection-mirror, and successfully reproduced it on a non-Apple platform. The stack trace for the runtime error has slightly incorrect formatting. I never accounted for this type of error message while making Swift-Colab, which is probably why it's improperly formatted. However, I can at least use the stack trace to investigate the crash in ReflectionMirror.

    // Cell 1 - pulls from the "colab-crash-1" branch
    %install '.package(url: "https://github.com/philipturner/swift-reflection-mirror", .branch("colab-crash-1"))' ReflectionMirror
    @_spi(Reflection) import ReflectionMirror
    print(_forEachField)
    
    // Cell 2
    struct ASimpleKPI {
      var w = 1
    }
    
    struct AMixedKPI {
      var string = "foo"
    }
    
    struct ANestedKPI {
      var simple = ASimpleKPI()
      var mixed = AMixedKPI()
    }
    
    // Cell 3
    var x = ANestedKPI()
        
    do {
      var result: [PartialKeyPath<ANestedKPI>] = []
      
      var out = [PartialKeyPath<ANestedKPI>]()
      _forEachFieldWithKeyPath(of: ANestedKPI.self, options: .ignoreUnknown) { _, kp in
        out.append(kp)
        return true
      }
      
      for kp in out {
        result.append(kp)
        if x[keyPath: kp] is ASimpleKPI {
          _forEachFieldWithKeyPath(of: ASimpleKPI.self, options: .ignoreUnknown) { _, nkp in
            result.append(kp.appending(path: nkp as AnyKeyPath)!)
            return true
          }
        } else if x[keyPath: kp] is AMixedKPI {
          var out2 = [AnyKeyPath]()
          _forEachFieldWithKeyPath(of: AMixedKPI.self, options: .ignoreUnknown) { _, nkp in
            out2.append(nkp as AnyKeyPath)
            return true
          }
          
          for nkp in out2 {
            result.append(kp.appending(path: nkp)!)
          }
        }
      }
    }
    
    // Cell 4
    do {
      var result: [PartialKeyPath<ANestedKPI>] = []
      
      var out = [PartialKeyPath<ANestedKPI>]()
      _forEachFieldWithKeyPath(of: ANestedKPI.self, options: .ignoreUnknown) { _, kp in
        out.append(kp)
        return true
      }
      
      for kp in out {
        result.append(kp)
        if x[keyPath: kp] is ASimpleKPI {
          _forEachFieldWithKeyPath(of: ASimpleKPI.self, options: .ignoreUnknown) { _, nkp in
            result.append(kp.appending(path: nkp as AnyKeyPath)!)
            return true
          }
        } else if x[keyPath: kp] is AMixedKPI {
          _forEachFieldWithKeyPath(of: AMixedKPI.self, options: .ignoreUnknown) { _, nkp in
            result.append(kp.appending(path: nkp as AnyKeyPath)!)
            return true
          }
        }
      }
    }
    

    Run the cells in this order:

    • Cell 1
    • Cell 2
    • Cell 3
    • Cell 4
    • Cell 3
    • Cell 4

    In the second run of Cell 4, there should be a runtime crash. The error message's second stack frame says ReflectionMirror.swift/, with an extraneous slash after swift. The bug occurs in the function prettyPrintStackTrace, inside the file FormatErrors.swift. Permalink here.

    Screen Shot 2022-07-06 at 10 20 22 AM

    On second examination, the first frame is also incorrect at closure #3 in. There are two spaces between in and -, when I would like only one present.

    bug 
    opened by philipturner 1
  • Allow stdin like with Bash in Python mode

    Allow stdin like with Bash in Python mode

    Swift-Colab uses the Python pexpect library to interact with running processes. This lets it extract colorized, interactive output - a feature not present in google/swift-jupyter. However, this means it will freeze when the process requests input.

    Screen Shot 2022-06-17 at 6 02 14 PM

    In the image above, the third %system command requests permission to overwrite a file.

    There is currently no mechanism to pass input into a running process. The Python Jupyter kernel passes input in, so it is theoretically possible. But this feature will take a non-negligible amount of time to implement. I am deferring its addition to a future release.

    enhancement good first issue 
    opened by philipturner 1
  • Swift `readLine()` scripting function not usable

    Swift `readLine()` scripting function not usable

    Although %system commands now support user input, this wasn't extended to the LLDB process. Swift code can write to output with print(), but can't read through readLine(). Any libraries that call this function will be affected.

    As an alternative to this kind of interaction, ask the user to paste a string into an empty cell. Design the notebook with a drop-down feature that closes the cell, or ask the user to delete it after running. For larger input, the user can connect to their Google Drive to import .txt or .csv files.

    wontfix 
    opened by philipturner 0
  • Provides a JupyterDisplay protocol package?

    Provides a JupyterDisplay protocol package?

    Seems we are the only two people use Swift with notebooks. Anyway, I think we need to collaborate on a new header-like library called JupyterDisplay. I have a prototype: https://github.com/liuliu/swift-jupyter/blob/main/display/JupyterDisplay.swift

    It is really simple. The idea is that any other libraries can depend on this library and provide notebook rich display support. If you looked at Python packages, many of them "battery-included" for notebook displays either inside the main package or in the support package.

    So far, the EnableJupyterDisplay.swift implementation took hands into itself and provides backends for matplotlib or Python or SwiftPlot. That is really limited.

    On the technical side, this package simply exposes a JupyterDisplay instance that EnableJupyterDisplay.swift can switch to a different implementation, thus, enabling the said behavior.

    Let me know what do you think. I mainly want to propose moving this into a "neutral" org and package it lightly (like package to SwiftPM and Bazel) and everyone can use.

    enhancement 
    opened by liuliu 33
  • « Dockerizing » Swift-Colab

    « Dockerizing » Swift-Colab

    In the recent Swift Numeric call, the idea of lowering the bar for scripting in Swift in the context of Data Science was surfaced, which lead to a suggestion to see if we could dockerize swift-colab.

    From reading through the swift-colab repo, I see the following possible directions:

    • package the install process as a set of binaries which can be directly downloaded in colab instead of compiling it from scratch
    • the above should also be usable in a standard Jupyter(Lab) environment
    • dockerize versions of the above as an image that can be used in a JupyterHub environment

    Each of the above would lower the bar of using swift-colab, as well as allow use in stand alone Jupyter environments.

    Were you thinking about something else?

    enhancement 
    opened by ratranqu 16
  • Can't compile Swift for TensorFlow quickly

    Can't compile Swift for TensorFlow quickly

    The main reason I made the overhauls present in Swift-Colab 2.0 was so that in the future, I could run S4TF code without facing bottlenecks that make it virtually unusable. However, I am unable to compile S4TF for use in the interactive experience. This is after avoiding the problems described in #14.

    The test notebook S4TF with TF 2.4 shows my effort to compile S4TF for use in the Swift interpreter. Even though that failed, I can technically compile it using %system flags like in s4tf-on-colab-example-1.ipynb and add custom code to the test suite. But that isn't ergonomic or reproducible in any way.

    Specifically, the debugger shows an error when I run the following code. Back in the swift-jupyter era, the TensorFlow module was embedded in the toolchain. So the error below was likely never encountered.

    import TensorFlow
    print(Tensor<Float>.self)
    
    <Cell 1>:2:7: error: cannot find 'Tensor' in scope
    print(Tensor<Float>.self)
          ^~~~~~
    
    bug help wanted 
    opened by philipturner 14
Releases(v2.3)
  • v2.3(Oct 11, 2022)

    From now on, Swift-Colab will focus on more general usage of Swift, diverging from the S4TF project. It may not receive many new features anymore, but should stay actively maintained. The kernel was designed to work with future versions of Swift, making it usable even if it does go unmaintained. As a final safeguard, the extensive comments and documentation make patching future problems much easier for people besides myself.

    I still find Swift-Colab quite useful for personal use cases, enabling persistently stored cloud notebooks geared toward interactive scripting. Plans to support local Jupyter notebooks are postponed indefinitely, as well as a "v3.0" version of Swift-Colab. However, liuliu/swift-jupyter provides a great experience for people seeking local Swift notebooks.

    Changes:

    • Numerous bug fixes.
    • Shortened first cell of the template notebook from 3 to 2 lines.
    • Added color to terminal output and refined stack traces for runtime errors.
    • IPython and SwiftPlot images now render inline with text, making them appear before (instead of after) a cell finishes executing.
    • You can now use Google Drive directly through PythonKit, without switching to Python mode.
    • You can now enter command-line input to %system commands, making this feature on par with Python ! bash commands.

    Not implemented:

    • %install-swiftpm-import and %install-swiftpm-environment magic commands, which would have sped up Swift for TensorFlow compilation considerably.
    • Conformance to the JupyterDisplay protocol from liuliu/swift-jupyter.
    • %install-test command for testing Swift packages inside a Colab notebook.
    • Support for specifying Swift v5.0-style package specifications.
    Source code(tar.gz)
    Source code(zip)
  • v2.2(Jun 20, 2022)

    Swift for TensorFlow now runs in the interactive Colab environment.

    • Fixed #11, allowing use of Swift concurrency inside a Task.
    • Addressed every Swift package installation bug reported in #14.
    • You can now download Swift toolchains from a custom URL.
    • Added test notebooks for S4TF and concurrency.
    Source code(tar.gz)
    Source code(zip)
  • v2.1(May 14, 2022)

  • v2.0(May 4, 2022)

  • v1.0(Dec 31, 2021)

  • v0.3(Dec 30, 2021)

  • v0.2(Dec 29, 2021)

  • v0.1(Dec 26, 2021)

Owner
Philip Turner
Spreading news that anyone can use $5 Google Cardboard to replicate $3,500 Microsoft Hololens
Philip Turner
TensorFlow C API Class Wrapper in Server Side Swift.

Perfect TensorFlow 简体中文 This project is an experimental wrapper of TensorFlow C API which enables Machine Learning in Server Side Swift. This package

PerfectlySoft Inc. 169 Dec 11, 2022
Swift for TensorFlow

Swift for TensorFlow (Archived) Swift for TensorFlow was an experiment in the next-generation platform for machine learning, incorporating the latest

null 6.1k Dec 31, 2022
BetterMood is an iOS app that uses Tensorflow to recognize user’s emotions

BetterMood is an iOS app that uses Tensorflow to recognize user’s emotions, convert it into categories then send via our api along with the user’s date of birth and name, to end up with a emotion analyse and horoscope prediction.

Yosri 2 Sep 30, 2021
Easily craft fast Neural Networks on iOS! Use TensorFlow models. Metal under the hood.

Bender Bender is an abstraction layer over MetalPerformanceShaders useful for working with neural networks. Contents Introduction Why did we need Bend

xmartlabs 1.7k Dec 24, 2022
[yolov5] + [ios] + [tensorflow lite]

YOLOv5 - TensorFlow Lite Object Detection iOS Example Application iOS Versions Supported: iOS 12.0 and above. Xcode Version Required: 10.0 and above O

Inpyo Hong 14 Dec 12, 2022
Models and examples built with TensorFlow

Welcome to the Model Garden for TensorFlow The TensorFlow Model Garden is a repository with a number of different implementations of state-of-the-art

null 74.9k Dec 29, 2022
🤗 Transformers: State-of-the-art Machine Learning for Pytorch, TensorFlow, and JAX.

English | 简体中文 | 繁體中文 | 한국어 State-of-the-art Machine Learning for JAX, PyTorch and TensorFlow ?? Transformers provides thousands of pretrained models

Hugging Face 77.1k Dec 31, 2022
Pose Estimation on iOS with TensorFlow Lite

This project is Pose Estimation on iOS with TensorFlow Lite. If you are interested in iOS + Machine Learning, visit here you can see various DEMOs. 2D

tucan9389 125 Nov 28, 2022
A Swift library for creating and exporting CoreML Models in Swift

SwiftCoreMLTools A Swift Library for creating CoreML models in Swift. Work in progress This library expose a (function builder based) DSL as well as a

Jacopo Mangiavacchi 140 Dec 5, 2022
Accelerated tensor operations and dynamic neural networks based on reverse mode automatic differentiation for every device that can run Swift - from watchOS to Linux

DL4S provides a high-level API for many accelerated operations common in neural networks and deep learning. It furthermore has automatic differentiati

Palle 87 Dec 29, 2022
The Swift machine learning library.

Swift AI is a high-performance deep learning library written entirely in Swift. We currently offer support for all Apple platforms, with Linux support

Swift AI 5.9k Jan 2, 2023
BrainCore is a simple but fast neural network framework written in Swift.

BrainCore is a simple but fast neural network framework written in Swift. It uses Metal which makes it screamin' fast. If you want to see it

Alejandro Isaza 377 Jun 29, 2022
MLKit is a simple machine learning framework written in Swift.

MLKit (a.k.a Machine Learning Kit) ?? MLKit is a simple machine learning framework written in Swift. Currently MLKit features machine learning algorit

Guled 152 Nov 17, 2022
Matft is Numpy-like library in Swift. Function name and usage is similar to Numpy.

Numpy-like library in swift. (Multi-dimensional Array, ndarray, matrix and vector library)

null 80 Dec 21, 2022
A simple Swift package which acts as an OpenAI client for the GPT-3 API.

SwiftyGPT3 A simple Swift package which acts as an OpenAI client for GPT-3 brought to you by the Airgift Crew. Supports GPT-3 Codex! Requirements iOS

Airgift 23 Dec 25, 2022
Artificial intelligence/machine learning data structures and Swift algorithms for future iOS development. bayes theorem, neural networks, and more AI.

Swift Brain The first neural network / machine learning library written in Swift. This is a project for AI algorithms in Swift for iOS and OS X develo

Vishal 331 Oct 14, 2022
A toolbox of AI modules written in Swift: Graphs/Trees, Support Vector Machines, Neural Networks, PCA, K-Means, Genetic Algorithms

AIToolbox A toolbox of AI modules written in Swift: Graphs/Trees, Linear Regression, Support Vector Machines, Neural Networks, PCA, KMeans, Genetic Al

Kevin Coble 776 Dec 18, 2022
A framework for building fast genetic algorithms in Swift.

Revolver is a framework for building fast genetic algorithms in Swift 3.0. Features Chromosomes: strings, trees Genetic operators: reproduction, mutat

Petr Mánek 27 Nov 17, 2022
A Swift deep learning library with Accelerate and Metal support.

Serrano Aiming to offering popular and cutting edge techs in deep learning area on iOS devices, Serrano is developed as a tool for developers & resear

pcpLiu 51 Nov 17, 2022