The document discusses exporting models trained with S4TF to CoreML format in Swift.
It provides code to:
1. Generate Swift data structures from CoreML protobuf definitions to represent models
2. Export an S4TF model defined with layers, weights, and hyperparameters to the CoreML format
3. Compile, make predictions, and perform personalization/training using the exported CoreML model
The personalization process involves:
1. Generating training data
2. Preparing batch providers for input/output
3. Configuring and running a training task on the CoreML model
4. Saving the retrained model
The document suggests automating the export process by extending S
Slides from Advaned Python lectures I gave recently in Haifa Linux club
Advanced python, Part 1:
- Decorators
- Descriptors
- Metaclasses
- Multiple inheritance
In this talk, Adrian Kashivskyy, Netguru iOS Developer, digs into rarely discussed Swift features, such as literal convertibles, interpolation convertibles, pattern matching, reflection and advanced Objective-C bridging.
Slides from Advaned Python lectures I gave recently in Haifa Linux club
Advanced python, Part 1:
- Decorators
- Descriptors
- Metaclasses
- Multiple inheritance
In this talk, Adrian Kashivskyy, Netguru iOS Developer, digs into rarely discussed Swift features, such as literal convertibles, interpolation convertibles, pattern matching, reflection and advanced Objective-C bridging.
Clojure is a new language that combines the power of Lisp with an existing hosted VM ecosystem (the Java VM). Clojure is a dynamically typed, functional, compiled language with performance on par with Java.
At the heart of all programming lies the need for abstraction, be it abstraction over our data or abstraction over the processes that operate upon it. Clojure provides a core set of powerful abstractions and ways to compose them. These abstractions are based in a heritage of Lisp but also cover many aspects of object-oriented programming as well.
This talk will examine these abstractions and introduce you to both Clojure and functional programming. Attendees are not expected to be familiar with either Clojure or FP.
Slides from Advaned Python lectures I gave recently in Haifa Linux club
Advanced python, Part 2:
- Slots vs Dictionaries
- Basic and Advanced Generators
- Async programming
From Java to Scala - advantages and possible risksSeniorDevOnly
Oleksii Petinov during his presentation gave the audience the overview of his vision of Scala pros and contras. In his vision Scala smoothly integrates features of object-oriented and functional languages, enabling Java and other programmers to be more productive.
There is admittedly some truth to the statement that “Scala is complex”, but the learning curve is well worth the investment.
Following a game show format made popular by Joshua Bloch and Neal Gafter's Java Puzzlers this presentation intends to both entertain and inform. Snippets of Python code the whose behaviour is not entirely obvious are shown, the audience will then be asked to pick from a number of options what the behaviour of the program is. The correct and sometimes non-intuitive answer will then be given along with a brief explanation of the idea the puzzle exposes. Only a modest working knowledge of the Python language is required to understand the puzzles, but the puzzles may also entertain the more experienced Python programmer.
A class is a code template for creating objects. Objects have member variables and have behaviour associated with them. In python a class is created by the keyword class.
An object is created using the constructor of the class. This object will then be called the instance of the class.
From java to kotlin beyond alt+shift+cmd+k - Droidcon italyFabio Collini
Kotlin is a first-class language for Android development since Google I/O 2017. And it’s here to stay!
Thanks to Android Studio it’s really easy to introduce Kotlin in an existing project, the configuration is trivial and then we can convert Java classes to Kotlin using a Alt+Shift+Cmd+K. But the new syntax is the just beginning, using Kotlin we can improve our code making it more readable and simpler to write.
In this talk we’ll see how to use some Kotlin features (for example data classes, collections, coroutines and delegates) to simplify Android development comparing the code with the equivalent “modern” Java code. It’s not fair to compare Kotlin code with plain Java 6 code so the Java examples will use lambdas and some external libraries like RxJava and AutoValue.
Clojure is a new language that combines the power of Lisp with an existing hosted VM ecosystem (the Java VM). Clojure is a dynamically typed, functional, compiled language with performance on par with Java.
At the heart of all programming lies the need for abstraction, be it abstraction over our data or abstraction over the processes that operate upon it. Clojure provides a core set of powerful abstractions and ways to compose them. These abstractions are based in a heritage of Lisp but also cover many aspects of object-oriented programming as well.
This talk will examine these abstractions and introduce you to both Clojure and functional programming. Attendees are not expected to be familiar with either Clojure or FP.
Slides from Advaned Python lectures I gave recently in Haifa Linux club
Advanced python, Part 2:
- Slots vs Dictionaries
- Basic and Advanced Generators
- Async programming
From Java to Scala - advantages and possible risksSeniorDevOnly
Oleksii Petinov during his presentation gave the audience the overview of his vision of Scala pros and contras. In his vision Scala smoothly integrates features of object-oriented and functional languages, enabling Java and other programmers to be more productive.
There is admittedly some truth to the statement that “Scala is complex”, but the learning curve is well worth the investment.
Following a game show format made popular by Joshua Bloch and Neal Gafter's Java Puzzlers this presentation intends to both entertain and inform. Snippets of Python code the whose behaviour is not entirely obvious are shown, the audience will then be asked to pick from a number of options what the behaviour of the program is. The correct and sometimes non-intuitive answer will then be given along with a brief explanation of the idea the puzzle exposes. Only a modest working knowledge of the Python language is required to understand the puzzles, but the puzzles may also entertain the more experienced Python programmer.
A class is a code template for creating objects. Objects have member variables and have behaviour associated with them. In python a class is created by the keyword class.
An object is created using the constructor of the class. This object will then be called the instance of the class.
From java to kotlin beyond alt+shift+cmd+k - Droidcon italyFabio Collini
Kotlin is a first-class language for Android development since Google I/O 2017. And it’s here to stay!
Thanks to Android Studio it’s really easy to introduce Kotlin in an existing project, the configuration is trivial and then we can convert Java classes to Kotlin using a Alt+Shift+Cmd+K. But the new syntax is the just beginning, using Kotlin we can improve our code making it more readable and simpler to write.
In this talk we’ll see how to use some Kotlin features (for example data classes, collections, coroutines and delegates) to simplify Android development comparing the code with the equivalent “modern” Java code. It’s not fair to compare Kotlin code with plain Java 6 code so the Java examples will use lambdas and some external libraries like RxJava and AutoValue.
Deep learning continues to push the state of the art in domains such as computer vision, natural language understanding and recommendation engines. One of the key reasons for this progress is the availability of highly flexible and developer friendly deep learning frameworks. During this workshop, members of the Amazon Machine Learning team will provide a short background on Deep Learning focusing on relevant application domains and an introduction to using the powerful and scalable Deep Learning framework, MXNet. At the end of this tutorial you’ll gain hands on experience targeting a variety of applications including computer vision and recommendation engines as well as exposure to how to use preconfigured Deep Learning AMIs and CloudFormation Templates to help speed your development.
A bird's eye view on some programming languages, focusing on concepts like typing, execution model or style. Presented on T3chFest 2016 in Leganés, Madrid, Spain.
The Rule of 10,000 Spark Jobs - Learning from Exceptions and Serializing Your...Matthew Tovbin
Spark + AI Summit, 2019 - Mastering complex software stacks, such as Spark or Hadoop, is a challenging process. Incompatible dependencies, new programming paradigms, runtime errors, outdated documentation, scaling, tuning - this is just a short list of skills we must acquire. How do we make sure that we are not wasting time and making progress learning? How do we share our knowledge efficiently? This talk walks you through a journey of scaling Salesforce Einstein AI platform to serve 6B+ predictions per day and provides you with a scale to measure learning progress.
The Rule of 10,000 Spark Jobs: Learning From Exceptions and Serializing Your ...Databricks
Mastering complex software stacks, such as Spark or Hadoop, is a challenging process. Incompatible dependencies, new programming paradigms, runtime errors, outdated documentation, scaling, tuning - this is just a short list of skills we must acquire. How do we make sure that we are not wasting time and making progress learning? How do we share our knowledge efficiently? This talk walks you through a journey of scaling Salesforce Einstein AI platform to serve 3B+ predictions per day and provides you with a scale to measure learning progress.
Speaker: Matthew Tovbin
JavaScript Advanced - Useful methods to power up your codeLaurence Svekis ✔
Get this Course
https://www.udemy.com/javascript-course-plus/?couponCode=SLIDESHARE
Useful methods and JavaScript code snippets power up your code and make even more happen with it.
This course is perfect for anyone who has fundamental JavaScript experience and wants to move to the next level. Use and apply more advanced code, and do more with JavaScript.
Everything you need to learn more about JavaScript
Source code is included
60+ page Downloadable PDF guide with resources and code snippets
3 Challenges to get you coding try the code
demonstrating useful JavaScript methods that can power up your code and make even more happen with it.
Course lessons will cover
JavaScript Number Methods
JavaScript String Methods
JavaScript Math - including math random
DOMContentLoaded - DOM ready when the document has loaded.
JavaScript Date - Date methods and how to get set and use date.
JavaScript parse and stringify - strings to objects back to strings
JavaScript LocalStorage - store variables in the user browser
JavaScript getBoundingClientRect() - get the dimensions of an element
JavaScript Timers setTimeout() setInterval() requestAnimationFrame() - Run code when you want too
encodeURIComponent - encoding made easy
Regex - so powerful use it to get values from your string
prototype - extend JavaScript objects with customized powers
Try and catch - perfect for error and testing
Fetch xHR requests - bring content in from servers
and more
No libraries, no shortcuts just learning JavaScript making it DYNAMIC and INTERACTIVE web application.
Step by step learning with all steps included.
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionAggregage
Join Maher Hanafi, VP of Engineering at Betterworks, in this new session where he'll share a practical framework to transform Gen AI prototypes into impactful products! He'll delve into the complexities of data collection and management, model selection and optimization, and ensuring security, scalability, and responsible use.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™UiPathCommunity
In questo evento online gratuito, organizzato dalla Community Italiana di UiPath, potrai esplorare le nuove funzionalità di Autopilot, il tool che integra l'Intelligenza Artificiale nei processi di sviluppo e utilizzo delle Automazioni.
📕 Vedremo insieme alcuni esempi dell'utilizzo di Autopilot in diversi tool della Suite UiPath:
Autopilot per Studio Web
Autopilot per Studio
Autopilot per Apps
Clipboard AI
GenAI applicata alla Document Understanding
👨🏫👨💻 Speakers:
Stefano Negro, UiPath MVPx3, RPA Tech Lead @ BSP Consultant
Flavio Martinelli, UiPath MVP 2023, Technical Account Manager @UiPath
Andrei Tasca, RPA Solutions Team Lead @NTT Data
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
Enhancing Performance with Globus and the Science DMZGlobus
ESnet has led the way in helping national facilities—and many other institutions in the research community—configure Science DMZs and troubleshoot network issues to maximize data transfer performance. In this talk we will present a summary of approaches and tips for getting the most out of your network infrastructure using Globus Connect Server.
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
Elevating Tactical DDD Patterns Through Object CalisthenicsDorra BARTAGUIZ
After immersing yourself in the blue book and its red counterpart, attending DDD-focused conferences, and applying tactical patterns, you're left with a crucial question: How do I ensure my design is effective? Tactical patterns within Domain-Driven Design (DDD) serve as guiding principles for creating clear and manageable domain models. However, achieving success with these patterns requires additional guidance. Interestingly, we've observed that a set of constraints initially designed for training purposes remarkably aligns with effective pattern implementation, offering a more ‘mechanical’ approach. Let's explore together how Object Calisthenics can elevate the design of your tactical DDD patterns, offering concrete help for those venturing into DDD for the first time!
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfPeter Spielvogel
Building better applications for business users with SAP Fiori.
• What is SAP Fiori and why it matters to you
• How a better user experience drives measurable business benefits
• How to get started with SAP Fiori today
• How SAP Fiori elements accelerates application development
• How SAP Build Code includes SAP Fiori tools and other generative artificial intelligence capabilities
• How SAP Fiori paves the way for using AI in SAP apps
The Metaverse and AI: how can decision-makers harness the Metaverse for their...Jen Stirrup
The Metaverse is popularized in science fiction, and now it is becoming closer to being a part of our daily lives through the use of social media and shopping companies. How can businesses survive in a world where Artificial Intelligence is becoming the present as well as the future of technology, and how does the Metaverse fit into business strategy when futurist ideas are developing into reality at accelerated rates? How do we do this when our data isn't up to scratch? How can we move towards success with our data so we are set up for the Metaverse when it arrives?
How can you help your company evolve, adapt, and succeed using Artificial Intelligence and the Metaverse to stay ahead of the competition? What are the potential issues, complications, and benefits that these technologies could bring to us and our organizations? In this session, Jen Stirrup will explain how to start thinking about these technologies as an organisation.
Quantum Computing: Current Landscape and the Future Role of APIs
Swift for TensorFlow - CoreML Personalization
1. S4TF save/export
Not a priority but a nice feature for the edge
ProtoBuf / FlatBuf file format
Inferencing
Personalization
Federated Learning
Runtime
2. S4TF Trivial data, model, hack
let SAMPLE_SIZE = 100
let a: Float = 2.0
let b: Float = 1.5
let x = Tensor<Float>(rangeFrom: 0, to: 1, stride: 1.0 / Float(SAMPLE_SIZE))
let noise = (Tensor<Float>(randomNormal: [SAMPLE_SIZE]) - 0.5) * 0.1
let y = (a * x + b) + noise
struct LinearRegression: Layer {
var layer1 = Dense<Float>(inputSize: 1, outputSize: 1, activation: identity)
@differentiable
func callAsFunction(_ input: Tensor<Float>) -> Tensor<Float> {
return layer1(input)
}
}
var regression = LinearRegression()
let optimizer = SGD(for: regression, learningRate: 0.03)
Context.local.learningPhase = .training
for _ in 0..<100 { //1000
let 𝛁model = regression.gradient { r -> Tensor<Float> in
let ŷ = r(X)
let loss = meanSquaredError(predicted: ŷ, expected: Y)
print("Loss: (loss)")
return loss
}
optimizer.update(®ression, along: 𝛁model)
}
3. Hack Swift CoreML ProtoBuf format
Apple provide Python CoreMLTools package and Swift API for iOS/macOS/.. for
model usage but no Swift API for CoreML model creation
1. Install ProtoBuf Compiler - https://github.com/protocolbuffers/protobuf
2. Install Swift ProtoBuf Plugin - https://github.com/apple/swift-protobuf
3. Download CoreML ProtoBuf source file - https://github.com/apple/
coremltools/tree/master/mlmodel/format
4. Compile and generate Swift CoreML data structures - protoc --
swift_out=[PATH TO FOLDER FOR GENERATED SWIFT FILES] [PATH TO
COREMLTOOS FOLDER]/mlmodel/format/*.proto
4. Swift CoreML ProtoBuf data
1: 4
2 {
1 {
1: "dense_input"
3 {
5 {
1: "001"
2: 65600
}
}
}
10 {
1: "output"
3 {
5 {
1: "001"
2: 65600
}
}
}
50 {
1: "dense_input"
3 {
5 {
1: "001"
2: 65600
protoc --decode_raw < model.mlmodel
syntax = “proto3”;
message Model {
int32 specificationVersion = 1;
ModelDescription description = 2;
bool isUpdatable = 10;
oneof Type {
...
NeuralNetwork neuralNetwork = 500;
...
}
...
}
message ModelDescription {
repeated FeatureDescription input = 1;
repeated FeatureDescription output = 10;
string predictedFeatureName = 11;
string predictedProbabilitiesName = 12;
repeated FeatureDescription trainingInput = 50;
Metadata metadata = 100;
}
message FeatureDescription {
string name = 1;
string shortDescription = 2;
FeatureType type = 3;
}
message NeuralNetwork {
repeated NeuralNetworkLayer layers = 1;
repeated NeuralNetworkPreprocessing preprocessing =
2;
NeuralNetworkMultiArrayShapeMapping
arrayInputShapeMapping = 5;
NeuralNetworkImageShapeMapping
imageInputShapeMapping = 6;
NetworkUpdateParameters updateParams = 10;
}
…
Model.proto Model.pb.swift
import Foundation
import SwiftProtobuf
struct CoreML_Specification_Model {
var specificationVersion: Int32 {
get {return _storage._specificationVersion}
set {_uniqueStorage()._specificationVersion = newValue}
}
var description_p: CoreML_Specification_ModelDescription
{
get {return _storage._description_p ??
CoreML_Specification_ModelDescription()}
set {_uniqueStorage()._description_p = newValue}
}
var hasDescription_p: Bool {return
_storage._description_p != nil}
var isUpdatable: Bool {
get {return _storage._isUpdatable}
set {_uniqueStorage()._isUpdatable = newValue}
}
var type: OneOf_Type? {
get {return _storage._type}
set {_uniqueStorage()._type = newValue}
}
...
/// generic models start at 500
var neuralNetwork: CoreML_Specification_NeuralNetwork {
get {
if case .neuralNetwork(let v)? = _storage._type
{return v}
return CoreML_Specification_NeuralNetwork()
}
set {_uniqueStorage()._type = .neuralNetwork(newValue)}
}
...
}
...
6. CoreML Compile and Inference
func compileCoreML(path: String) -> (MLModel, URL) {
let modelUrl = URL(fileURLWithPath: path)
let compiledUrl = try! MLModel.compileModel(at: modelUrl)
return try! (MLModel(contentsOf: compiledUrl), compiledUrl)
}
func inferenceCoreML(model: MLModel, x: Float) -> Float {
let multiArr = try! MLMultiArray(shape: [1], dataType: .double)
multiArr[0] = NSNumber(value: x)
let inputValue = MLFeatureValue(multiArray: multiArr)
let dataPointFeatures: [String: MLFeatureValue] = [inputName: "dense_input"]
let provider = try! MLDictionaryFeatureProvider(dictionary: dataPointFeatures)
let prediction = try! model.prediction(from: provider)
return Float(prediction.featureValue(for: "output")!.multiArrayValue![0].doubleValue)
}
let (coreModel, compiledModelUrl) = compileCoreML(path: coreMLFilePath)
let prediction = inferenceCoreML(model: coreModel, x: 1.0)
Xcode has fantastic drag&drop integration of CoreML model into project with Swift wrapper
code generation but models can also be loaded, compiled and used dynamically
7. CoreML Personalization / Training
func generateData(sampleSize: Int = 100) -> ([Float], [Float]) {
let a: Float = 2.0
let b: Float = 1.5
var X = [Float]()
var Y = [Float]()
for i in 0..<sampleSize {
let x: Float = Float(i) / Float(sampleSize)
let noise: Float = (Float.random(in: 0..<1) - 0.5) * 0.1
let y: Float = (a * x + b) + noise
X.append(x)
Y.append(y)
}
return (X, Y)
}
func prepareTrainingBatch() -> MLBatchProvider {
var featureProviders = [MLFeatureProvider]()
let inputName = "dense_input"
let outputName = "output_true"
let (X, Y) = generateData()
for (x,y) in zip(X, Y) {
let multiArr = try! MLMultiArray(shape: [1], dataType: .double)
multiArr[0] = NSNumber(value: x)
let inputValue = MLFeatureValue(multiArray: multiArr)
multiArr[0] = NSNumber(value: y)
let outputValue = MLFeatureValue(multiArray: multiArr)
let dataPointFeatures: [String: MLFeatureValue] = [inputName: inputValue,
outputName: outputValue]
if let provider = try? MLDictionaryFeatureProvider(dictionary: dataPointFeatures) {
featureProviders.append(provider)
}
}
return MLArrayBatchProvider(array: featureProviders)
}
func train(url: URL) {
let configuration = MLModelConfiguration()
configuration.computeUnits = .all
configuration.parameters = [.epochs : 100]
let progressHandler = { (context: MLUpdateContext) in
switch context.event {
case .trainingBegin: ...
case .miniBatchEnd: ...
case .epochEnd: ...
}
}
let completionHandler = { (context: MLUpdateContext) in
guard context.task.state == .completed else { return }
let trainLoss = context.metrics[.lossValue] as! Double
let updatedModel = context.model
let updatedModelURL = URL(fileURLWithPath: retrainedCoreMLFilePath)
try! updatedModel.write(to: updatedModelURL)
}
let handlers = MLUpdateProgressHandlers(
forEvents: [.trainingBegin, .miniBatchEnd, .epochEnd],
progressHandler: progressHandler,
completionHandler: completionHandler)
let updateTask = try! MLUpdateTask(forModelAt: url,
trainingData: prepareTrainingBatch(),
configuration: configuration,
progressHandlers: handlers)
updateTask.resume()
}
Prepare Batch Data Training
train(url: compiledModelUrl)
// Wait for completition of the asyncronous training task
let retrainedModel = try! MLModel(contentsOf: URL(fileURLWithPath: retrainedCoreMLFilePath))
let prediction = inferenceCoreML(model: retrainedModel, x: 1.0)
8. S4TF How Automate Model Export
?
• Extend Layer, Sequencial/sequenced(), DSL function builder ???
• What about Training parameters (Cost Functions, Optimizations, …) ??
+ Model Optimizations:
• Other then Quantization and Pruning
• i.e. Microsoft ONNX BERT condensed layers (17x inference acceleration)
• i.e. CoreML Custom Layers and/or Custom Activation Functions
• https://github.com/JacopoMangiavacchi/S4TF_CoreML_Test
• https://medium.com/@JMangia/swift-loves-tensorflow-and-coreml-2a11da25d44