This repository was archived by the owner on Apr 23, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 150
Initial training and inference benchmarks #222
Merged
Merged
Changes from 4 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
dedd46e
Initial implementation of training and inference benchmarks.
BradLarson f84778c
Resolved a typechecker issue.
BradLarson e3ccb23
Added a Readme.
BradLarson 4427385
Added copyright headers.
BradLarson 7d5be58
Merge branch 'master' into benchmarks
BradLarson 002bb3c
Merge branch 'master' into benchmarks
BradLarson f12060c
Reworked the benchmarking functions to use a single function that is …
BradLarson 9bbe853
Reworked the model-specific benchmark into general inference and trai…
BradLarson 7e81056
Restructured BenchmarkResults to be a plain collection of timings, wi…
BradLarson 7f86bf5
Rename interpretTimings to interpretedTimings.
BradLarson 686ee22
Change reference to interpretedTimings later.
BradLarson File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,114 @@ | ||
| // Copyright 2019 The TensorFlow Authors. All Rights Reserved. | ||
| // | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| import Foundation | ||
|
|
||
| protocol BenchmarkResults: CustomStringConvertible { | ||
| var description: String { get } | ||
BradLarson marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| struct TrainingBenchmarkResults: BenchmarkResults { | ||
BradLarson marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| let iterations: Int | ||
| let averageTime: Double | ||
|
||
| let standardDeviation: Double | ||
|
|
||
| var description: String { | ||
| get { | ||
BradLarson marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| return """ | ||
| \tAfter \(iterations) iterations: | ||
| \tAverage: \(averageTime) ms, standard deviation: \(standardDeviation) ms | ||
| """ | ||
| } | ||
| } | ||
| } | ||
|
|
||
| struct InferenceBenchmarkResults: BenchmarkResults { | ||
| let iterations: Int | ||
| let samplesPerSecond: Double | ||
| let standardDeviation: Double | ||
|
|
||
| var description: String { | ||
| get { | ||
| return """ | ||
| \tAfter \(iterations) iterations: | ||
| \tSamples per second: \(samplesPerSecond), standard deviation: \(standardDeviation) | ||
| """ | ||
| } | ||
| } | ||
| } | ||
|
|
||
| func timeExecution(_ operation: () -> Void) -> Double { | ||
BradLarson marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| var startTime = timeval() | ||
| gettimeofday(&startTime, nil) | ||
|
|
||
| operation() | ||
|
|
||
| var endTime = timeval() | ||
| gettimeofday(&endTime, nil) | ||
| let secondsPortion = (endTime.tv_sec - startTime.tv_sec) * 1000 | ||
| let microsecondsPortion = Int((endTime.tv_usec - startTime.tv_usec) / 1000) | ||
| return Double(secondsPortion + microsecondsPortion) | ||
| } | ||
|
|
||
| func statistics(for values: [Double]) -> (average: Double, standardDeviation: Double) { | ||
| guard values.count > 0 else { return (average: 0.0, standardDeviation: 0.0) } | ||
| guard values.count > 1 else { return (average: values.first!, standardDeviation: 0.0) } | ||
|
|
||
| let average = (values.reduce(0.0) { $0 + $1 }) / Double(values.count) | ||
|
|
||
| let standardDeviation = sqrt( | ||
| values.reduce(0.0) { $0 + ($1 - average) * ($1 - average) } | ||
| / Double(values.count - 1)) | ||
|
|
||
| return (average: average, standardDeviation: standardDeviation) | ||
| } | ||
|
|
||
| func benchmarkTraining(iterations: Int, operation: () -> Void, callback: (BenchmarkResults) -> Void) | ||
| { | ||
| var timings: [Double] = [] | ||
| for _ in 0..<iterations { | ||
| timings.append(timeExecution(operation)) | ||
| } | ||
|
|
||
| let (averageTime, standardDeviation) = statistics(for: timings) | ||
|
|
||
| let results = TrainingBenchmarkResults( | ||
| iterations: iterations, averageTime: averageTime, standardDeviation: standardDeviation) | ||
| callback(results) | ||
| } | ||
|
|
||
| func benchmarkInference( | ||
| iterations: Int, batches: Int, batchSize: Int, setup: (Int, Int) -> Void, operation: () -> Void, | ||
| callback: (BenchmarkResults) -> Void | ||
| ) { | ||
| setup(batches, batchSize) | ||
|
|
||
| var timings: [Double] = [] | ||
| for _ in 0..<iterations { | ||
| timings.append(Double(batches * batchSize) / (timeExecution(operation) / 1000.0)) | ||
| } | ||
|
|
||
| let (samplesPerSecond, standardDeviation) = statistics(for: timings) | ||
| let results = InferenceBenchmarkResults( | ||
| iterations: iterations, samplesPerSecond: samplesPerSecond, | ||
| standardDeviation: standardDeviation) | ||
| callback(results) | ||
| } | ||
|
|
||
| func logResults(name: String) -> (BenchmarkResults) -> Void { | ||
BradLarson marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| return { results in | ||
| print("Benchmark: \(name):") | ||
| print("\(results)") | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| // Copyright 2019 The TensorFlow Authors. All Rights Reserved. | ||
| // | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| import TensorFlow | ||
| import Datasets | ||
| import ImageClassificationModels | ||
|
|
||
| final class LeNetBenchmark { | ||
| let epochs: Int | ||
| let batchSize: Int | ||
| let dataset: MNIST | ||
| var inferenceModel: LeNet! | ||
| var inferenceImages: Tensor<Float>! | ||
| var batches: Int! | ||
| var inferenceBatches: Int! | ||
|
|
||
| init(epochs: Int, batchSize: Int) { | ||
| self.epochs = epochs | ||
| self.batchSize = batchSize | ||
| self.dataset = MNIST(batchSize: batchSize) | ||
| } | ||
|
|
||
| func performTraining() { | ||
| var model = LeNet() | ||
| let optimizer = SGD(for: model, learningRate: 0.1) | ||
|
|
||
| Context.local.learningPhase = .training | ||
| for _ in 1...epochs { | ||
| for i in 0..<dataset.trainingSize / batchSize { | ||
| let x = dataset.trainingImages.minibatch(at: i, batchSize: batchSize) | ||
| let y = dataset.trainingLabels.minibatch(at: i, batchSize: batchSize) | ||
| let 𝛁model = model.gradient { model -> Tensor<Float> in | ||
| let ŷ = model(x) | ||
| return softmaxCrossEntropy(logits: ŷ, labels: y) | ||
| } | ||
| optimizer.update(&model, along: 𝛁model) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| func setupInference(batches: Int, batchSize: Int) { | ||
| inferenceBatches = batches | ||
| inferenceModel = LeNet() | ||
| inferenceImages = Tensor<Float>( | ||
| randomNormal: [batchSize, 28, 28, 1], mean: Tensor<Float>(0.5), | ||
| standardDeviation: Tensor<Float>(0.1), seed: (0xffeffe, 0xfffe)) | ||
| } | ||
|
|
||
| func performInference() { | ||
| for _ in 0..<inferenceBatches { | ||
| let _ = inferenceModel(inferenceImages) | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| # Model benchmarks | ||
|
|
||
| Eventually, these will contain a series of benchmarks against a variety of models in the | ||
| swift-models repository. The following benchmarks have been implemented: | ||
|
|
||
| - Training LeNet against the MNIST dataset | ||
| - Performing inference with LeNet using MNIST-sized random images | ||
|
|
||
| These benchmarks should provide a baseline to judge performance improvements and regressions in | ||
| Swift for TensorFlow. | ||
|
|
||
| ## Running benchmarks | ||
|
|
||
| To begin, you'll need the [latest version of Swift for | ||
| TensorFlow](https://github.com/tensorflow/swift/blob/master/Installation.md) | ||
| installed. Make sure you've added the correct version of `swift` to your path. | ||
|
|
||
| To run all benchmarks, type the following while in the swift-models directory: | ||
|
|
||
| ```sh | ||
| swift run -c release Benchmarks | ||
| ``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| // Copyright 2019 The TensorFlow Authors. All Rights Reserved. | ||
| // | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| // LeNet-MNIST | ||
| let leNetBenchmark = LeNetBenchmark(epochs: 1, batchSize: 128) | ||
| benchmarkTraining( | ||
| iterations: 10, operation: leNetBenchmark.performTraining, | ||
| callback: logResults(name: "LeNet-MNIST (training)")) | ||
| benchmarkInference( | ||
| iterations: 10, batches: 1000, batchSize: 1, setup: leNetBenchmark.setupInference, | ||
| operation: leNetBenchmark.performInference, | ||
| callback: logResults(name: "LeNet-MNIST (inference)")) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.