-
Notifications
You must be signed in to change notification settings - Fork 16
/
ViewController.swift
254 lines (176 loc) · 9.9 KB
/
ViewController.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
//
// ViewController.Swift
// SwiftMetalProcessing
//
// Created by Amund Tveit on 15/12/14.
// Copyright (c) 2014 Amund Tveit. All rights reserved.
//
import UIKit
import Metal
import QuartzCore
import Darwin
import Accelerate
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
for(var i = 25; i<26; ++i) {
let start0 = CACurrentMediaTime()
let maxcount = Int(pow(2.0,Float(i)))
println("#############################################")
println("==> count = \(maxcount) - 2^\(i)")
// NEW APPROACH FOR ALLOCATION
// new way of prepping data
var memory:UnsafeMutablePointer<Void> = nil
//var memory:AutoreleasingUnsafeMutablePointer<Void> = nil
var alignment:UInt = 0x4000 // 16K aligned
var size:UInt = UInt(maxcount)*UInt(sizeof(Float))
posix_memalign(&memory, alignment, size)
var outmemory:UnsafeMutablePointer<Void> = nil
posix_memalign(&outmemory, alignment, size)
// var myvectorPtr = unsafeBitCast(memory, UnsafePointer<Float>.self)
var pptr = COpaquePointer(memory)
var nps = UnsafeMutablePointer<Float>(pptr)
nps.memory = 1234.47
var yoda = UnsafeMutableBufferPointer<Float>(start: nps, count: maxcount)
for index in yoda.startIndex..<yoda.endIndex {
yoda[index] = Float(index)
}
/*
// PREVIOUS APPROACH
var myvector = Array(yoda)
println(myvector)
println("after")
// prepare original input data – a Swift array
//var myvector = [Float](count: maxcount, repeatedValue: 0)
for (index, value) in enumerate(myvector) {
myvector[index] = Float(index)
}
let stop0 = CACurrentMediaTime()
let delta0 = (stop0-start0)*1000000.0
println("filling array took \(delta0) microseconds")
var mynegativeVector = [Float](count: maxcount, repeatedValue: 0)
for(index, value) in enumerate(mynegativeVector) {
mynegativeVector[index] = Float(-index)
}
// calculate exp(-x)
var expMinusX = [Float](count: maxcount, repeatedValue:0)
var oneVec = [Float](count:maxcount, repeatedValue:1.0)
var negOneVec = [Float](count:maxcount, repeatedValue:-1.0)
//println(oneVec)
//println(negOneVec)
// oneVec contains 1+exp(-x)
var finalResultVector = [Float](count:maxcount, repeatedValue:0)
var localcount:Int32 = Int32(mynegativeVector.count)
let start5 = CACurrentMediaTime()
// calculation
vvexpf(&expMinusX, &mynegativeVector, &localcount)
cblas_saxpy(Int32(oneVec.count), 1.0, &expMinusX, 1, &oneVec, 1)
vvpowf(&finalResultVector, &negOneVec, &oneVec, &localcount)
assert(finalResultVector[0] == 0.5)
let stop5 = CACurrentMediaTime()
let delta5 = (stop0-start0)*1000000.0
println("Accelerate approach took \(delta5) microseconds")
*/
// initialize Metal
// START BENCHMARK
// let start = CACurrentMediaTime()
var (device, commandQueue, defaultLibrary, commandBuffer, computeCommandEncoder) = initMetal()
// set up a compute pipeline with Sigmoid function and add it to encoder
let sigmoidProgram = defaultLibrary.newFunctionWithName("sigmoid")
var pipelineErrors = NSErrorPointer()
var computePipelineFilter = device.newComputePipelineStateWithFunction(sigmoidProgram!, error: pipelineErrors)
computeCommandEncoder.setComputePipelineState(computePipelineFilter!)
computeCommandEncoder.setComputePipelineState(computePipelineFilter!)
// calculate byte length of input data - myvector
// var myvectorByteLength = myvector.count*sizeofValue(myvector[0])
// create a MTLBuffer - input data that the GPU and Metal and produce
//var inVectorBuffer = device.newBufferWithBytes(&myvector, length: myvectorByteLength, options: nil)
var inVectorBufferNoCopy = device.newBufferWithBytesNoCopy(memory, length: Int(size), options: nil, deallocator: nil)
// set the input vector for the Sigmoid() function, e.g. inVector
// atIndex: 0 here corresponds to buffer(0) in the Sigmoid function
computeCommandEncoder.setBuffer(inVectorBufferNoCopy, offset: 0, atIndex: 0)
// d. create the output vector for the Sigmoid() function, e.g. outVector
// atIndex: 1 here corresponds to buffer(1) in the Sigmoid function
// var resultdata = [Float](count:myvector.count, repeatedValue: 0)
// var outVectorBuffer = device.newBufferWithBytes(&resultdata, length: myvectorByteLength, options: nil)
var outVectorBufferNoCopy = device.newBufferWithBytesNoCopy(outmemory, length: Int(size), options: nil, deallocator: nil)
computeCommandEncoder.setBuffer(outVectorBufferNoCopy, offset: 0, atIndex: 1)
// hardcoded to 32 for now (recommendation: read about threadExecutionWidth)
var threadsPerGroup = MTLSize(width:32,height:1,depth:1)
var numThreadgroups = MTLSize(width:(Int(maxcount)+31)/32, height:1, depth:1)
computeCommandEncoder.dispatchThreadgroups(numThreadgroups, threadsPerThreadgroup: threadsPerGroup)
computeCommandEncoder.endEncoding()
// let start = CACurrentMediaTime()
let start = CACurrentMediaTime()
commandBuffer.commit()
commandBuffer.waitUntilCompleted()
let stop = CACurrentMediaTime()
var memptr = COpaquePointer(outmemory)
var memptrfloat = UnsafeMutablePointer<Float>(memptr)
var yoda2 = UnsafeMutableBufferPointer<Float>(start: memptrfloat, count: maxcount)
println(memptrfloat.memory)
// var r = Array(yoda2)
//
// println("r = ")
// println(r)
// let stop = CACurrentMediaTime()
// let deltaMicroseconds = (stop-start) * (1.0*10e6)
// println("cold GPU: runtime in microsecs : \(deltaMicroseconds)")
/*
// a. Get GPU data
// outVectorBuffer.contents() returns UnsafeMutablePointer roughly equivalent to char* in C
var data = NSData(bytesNoCopy: outVectorBuffer.contents(),
length: myvector.count*sizeof(Float), freeWhenDone: false)
// b. prepare Swift array large enough to receive data from GPU
var finalResultArray = [Float](count: myvector.count, repeatedValue: 0)
// c. get data from GPU into Swift array
data.getBytes(&finalResultArray, length:myvector.count * sizeof(Float))
assert(finalResultVector[0] == 0.5)
*/
// STOP BENCHMARK
let deltaMicroseconds = (stop-start) * (1.0*10e6)
println("cold GPU: runtime in microsecs : \(deltaMicroseconds)")
let start3 = CACurrentMediaTime()
// timing without
/*
for (index, value) in enumerate(myvector) {
finalResultArray[index] = 1.0 / (1.0 + exp(-myvector[index]))
}
var fra = NSMutableArray(capacity: myvector.count)
let ccount = myvector.count
for j in 0..<ccount {
fra[j] = 1.0/(1.0 + exp(-myvector[j]))
}
let stop3 = CACurrentMediaTime()
let deltaMicroseconds3 = (stop3-start3) * (1.0*10e6)
println("CPU: runtime in microsecs : \(deltaMicroseconds3)")
let relativeSpeed = deltaMicroseconds3/deltaMicroseconds
println("Metal was \(relativeSpeed) times faster than CPU")
let relativeToAccelerate = delta5/deltaMicroseconds
println("Metal was \(relativeToAccelerate) times faster than Accelerate Framework")
*/
}
exit(0)
}
func initMetal() -> (MTLDevice, MTLCommandQueue, MTLLibrary, MTLCommandBuffer,
MTLComputeCommandEncoder){
// Get access to iPhone or iPad GPU
var device = MTLCreateSystemDefaultDevice()
// Queue to handle an ordered list of command buffers
var commandQueue = device.newCommandQueue()
// Access to Metal functions that are stored in Shaders.metal file, e.g. sigmoid()
var defaultLibrary = device.newDefaultLibrary()
// Buffer for storing encoded commands that are sent to GPU
var commandBuffer = commandQueue.commandBuffer()
// Encoder for GPU commands
var computeCommandEncoder = commandBuffer.computeCommandEncoder()
return (device, commandQueue, defaultLibrary!, commandBuffer, computeCommandEncoder)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
if(self.isViewLoaded() && self.view.window == nil) {
self.view = nil
}
}
}