Swiftpack.co - kisonho/SwTorch as Swift Package

Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.
See all packages published by kisonho.
kisonho/SwTorch v1.0.0rc1
PyTorch framework integration for Swift
⭐️ 0
🕓 19 hours ago
.package(url: "https://github.com/kisonho/SwTorch.git", from: "v1.0.0rc1")


PyTorch training/evaluation wrap for Swift.


*The latest LTS version of PyTorch with python environment set up to PYTHON_LIBRARY

  • Add packages:
.package(url: "https://github.com/kisonho/SwTorch.git", branch: "main"),

Creating a Module

Create a model that implements the Module protocol, or load a python module directly with struct PyModule.

PyTorch Tensor representation

A PyTorch Tensor (torch.nn.Tensor) is represented as Tensor, which actual variable was stored in its pythonObject.


  • Creating a class to implement the Evaluating protocol
import SwTorch

class ModelEvaluator: Evaluating {
  • Call validate(<DataLoader>) to evaluate the model. The method will returns a Dictionary of metrics that averaged by returned metrics of calculatedMetrics(yTrue, yPred).
  • onBatchEnd(batch, result) is the call back method for each batch validation.


  • Creating a class to implement the Training protocol
import SwTorch

class ModelEvaluator: Training {
  • Call train(trainingDataset: <DataLoader>, epochs: <Int>, initialEpoch: <Int=0>, validationDataset: <DataLoader?=nil>) to train the model. The method will return a Dictionary of best validation result among the training epochs, or a nil if validationDataset is not given.

Device Management

Use .to(<Device>) to move a DeviceMovable object to target device.

Unmapped PyTorch operations or types

Directly use torch.* as PythonObject

MNIST Example


Stars: 0
Last commit: 5 hours ago
jonrohan Something's broken? Yell at me @ptrpavlik. Praise and feedback (and money) is also welcome.


Release Notes

First candidate release (v1.0.0 rc1)

This is a candidate release for the first final version.

Contents same as v0.2.3

Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics