Skip to content

Commit e38e8db

Browse files
Trim whitespace always (huggingface#200)
1 parent ce553eb commit e38e8db

36 files changed

+557
-557
lines changed

.swiftformat

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,5 +83,5 @@
8383
--disable blankLineAfterImports,unusedArguments
8484
--enable docComments
8585
--disable enumnamespaces
86-
--trimwhitespace nonblank-lines
86+
--trimwhitespace always
8787
--disable preferKeyPath

Sources/Generation/Generation.swift

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ public typealias PredictionStringCallback = (String) -> Void
3030
// TODO: callbacks (for streaming)
3131
public protocol Generation {
3232
func greedySearch(config: GenerationConfig, tokens: InputTokens, model: NextTokenModel, callback: PredictionTokensCallback?) async -> GenerationOutput
33-
33+
3434
func generate(config: GenerationConfig, prompt: String, model: NextTokenModel, tokenizer: Tokenizer, callback: PredictionStringCallback?) async -> String
3535
}
3636

@@ -48,7 +48,7 @@ public extension Generation {
4848
}
4949
return outputTokens
5050
}
51-
51+
5252
/// https://github.com/huggingface/transformers/blob/42017d82baa083da2bee3055fdac80c81ee97b8a/src/transformers/generation/utils.py#L1552
5353
func sample(config: GenerationConfig, tokens: InputTokens, model: NextTokenModel, callback: PredictionTokensCallback? = nil) async -> GenerationOutput {
5454
// Iterate until we find the eos token or reach the max length
@@ -86,7 +86,7 @@ public extension Generation {
8686
default:
8787
fatalError("Generation mode \(generationConfig.generationMode) not implemented yet")
8888
}
89-
89+
9090
return tokenizer.decode(tokens: output)
9191
}
9292

Sources/Generation/GenerationConfig.swift

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,11 @@ public struct GenerationConfig {
1919
public var topK = 50
2020
public var topP = 1.0
2121
public var repetitionPenalty = 1.0
22-
22+
2323
public var padTokenId: Int?
2424
public var bosTokenId: Int?
2525
public var eosTokenId: Int?
26-
26+
2727
public init(maxLength: Int = 20, maxNewTokens: Int, doSample: Bool = false, numBeams: Int = 1, numBeamGroups: Int = 1, penaltyAlpha: Double? = nil, temperature: Double = 1.0, topK: Int = 50, topP: Double = 1.0, repetitionPenalty: Double = 1.0) {
2828
self.maxLength = maxLength
2929
self.maxNewTokens = maxNewTokens
@@ -44,7 +44,7 @@ public extension GenerationConfig {
4444
if topK > 1, !doSample, penaltyAlpha != nil, penaltyAlpha! > 0 {
4545
return .contrastiveSearch
4646
}
47-
47+
4848
switch (numBeams, numBeamGroups, doSample) {
4949
case (1, 1, false): return .greedy
5050
case (1, 1, true): return .sample

Sources/Hub/Downloader.swift

Lines changed: 27 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -29,14 +29,14 @@ class Downloader: NSObject, ObservableObject {
2929

3030
private(set) lazy var downloadState: CurrentValueSubject<DownloadState, Never> = CurrentValueSubject(.notStarted)
3131
private var stateSubscriber: Cancellable?
32-
32+
3333
private(set) var tempFilePath: URL
3434
private(set) var expectedSize: Int?
3535
private(set) var downloadedSize: Int = 0
3636

3737
var session: URLSession? = nil
3838
var downloadTask: Task<Void, Error>? = nil
39-
39+
4040
init(
4141
from url: URL,
4242
to destination: URL,
@@ -50,13 +50,13 @@ class Downloader: NSObject, ObservableObject {
5050
) {
5151
self.destination = destination
5252
self.expectedSize = expectedSize
53-
53+
5454
// Create incomplete file path based on destination
5555
tempFilePath = incompleteDestination
56-
56+
5757
// If resume size wasn't specified, check for an existing incomplete file
5858
let resumeSize = Self.incompleteFileSize(at: incompleteDestination)
59-
59+
6060
super.init()
6161
let sessionIdentifier = "swift-transformers.hub.downloader"
6262

@@ -81,7 +81,7 @@ class Downloader: NSObject, ObservableObject {
8181
return fileSize
8282
}
8383
}
84-
84+
8585
return 0
8686
}
8787

@@ -119,23 +119,23 @@ class Downloader: NSObject, ObservableObject {
119119
existing.cancel()
120120
}
121121
}
122-
122+
123123
self.downloadTask = Task {
124124
do {
125125
// Set up the request with appropriate headers
126126
var request = URLRequest(url: url)
127127
var requestHeaders = headers ?? [:]
128-
128+
129129
if let authToken {
130130
requestHeaders["Authorization"] = "Bearer \(authToken)"
131131
}
132-
132+
133133
self.downloadedSize = resumeSize
134-
134+
135135
// Set Range header if we're resuming
136136
if resumeSize > 0 {
137137
requestHeaders["Range"] = "bytes=\(resumeSize)-"
138-
138+
139139
// Calculate and show initial progress
140140
if let expectedSize, expectedSize > 0 {
141141
let initialProgress = Double(resumeSize) / Double(expectedSize)
@@ -146,23 +146,23 @@ class Downloader: NSObject, ObservableObject {
146146
} else {
147147
self.downloadState.value = .downloading(0)
148148
}
149-
149+
150150
request.timeoutInterval = timeout
151151
request.allHTTPHeaderFields = requestHeaders
152-
152+
153153
// Open the incomplete file for writing
154154
let tempFile = try FileHandle(forWritingTo: self.tempFilePath)
155-
155+
156156
// If resuming, seek to end of file
157157
if resumeSize > 0 {
158158
try tempFile.seekToEnd()
159159
}
160-
160+
161161
try await self.httpGet(request: request, tempFile: tempFile, resumeSize: self.downloadedSize, numRetries: numRetries, expectedSize: expectedSize)
162-
162+
163163
// Clean up and move the completed download to its final destination
164164
tempFile.closeFile()
165-
165+
166166
try Task.checkCancellation()
167167
try FileManager.default.moveDownloadedFile(from: self.tempFilePath, to: self.destination)
168168
self.downloadState.value = .completed(self.destination)
@@ -194,16 +194,16 @@ class Downloader: NSObject, ObservableObject {
194194
guard let session else {
195195
throw DownloadError.unexpectedError
196196
}
197-
197+
198198
// Create a new request with Range header for resuming
199199
var newRequest = request
200200
if resumeSize > 0 {
201201
newRequest.setValue("bytes=\(resumeSize)-", forHTTPHeaderField: "Range")
202202
}
203-
203+
204204
// Start the download and get the byte stream
205205
let (asyncBytes, response) = try await session.bytes(for: newRequest)
206-
206+
207207
guard let httpResponse = response as? HTTPURLResponse else {
208208
throw DownloadError.unexpectedError
209209
}
@@ -213,7 +213,7 @@ class Downloader: NSObject, ObservableObject {
213213

214214
// Create a buffer to collect bytes before writing to disk
215215
var buffer = Data(capacity: chunkSize)
216-
216+
217217
var newNumRetries = numRetries
218218
do {
219219
for try await byte in asyncBytes {
@@ -231,7 +231,7 @@ class Downloader: NSObject, ObservableObject {
231231
}
232232
}
233233
}
234-
234+
235235
if !buffer.isEmpty {
236236
try tempFile.write(contentsOf: buffer)
237237
downloadedSize += buffer.count
@@ -243,10 +243,10 @@ class Downloader: NSObject, ObservableObject {
243243
throw error
244244
}
245245
try await Task.sleep(nanoseconds: 1_000_000_000)
246-
246+
247247
let config = URLSessionConfiguration.default
248248
self.session = URLSession(configuration: config, delegate: self, delegateQueue: nil)
249-
249+
250250
try await httpGet(
251251
request: request,
252252
tempFile: tempFile,
@@ -255,14 +255,14 @@ class Downloader: NSObject, ObservableObject {
255255
expectedSize: expectedSize
256256
)
257257
}
258-
258+
259259
// Verify the downloaded file size matches the expected size
260260
let actualSize = try tempFile.seekToEnd()
261261
if let expectedSize, expectedSize != actualSize {
262262
throw DownloadError.unexpectedError
263263
}
264264
}
265-
265+
266266
@discardableResult
267267
func waitUntilDone() throws -> URL {
268268
// It's either this, or stream the bytes ourselves (add to a buffer, save to disk, etc; boring and finicky)
@@ -321,7 +321,7 @@ extension FileManager {
321321
if fileExists(atPath: dstURL.path()) {
322322
try removeItem(at: dstURL)
323323
}
324-
324+
325325
let directoryURL = dstURL.deletingLastPathComponent()
326326
try createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil)
327327

Sources/Hub/Hub.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ public extension Hub {
5656
case datasets
5757
case spaces
5858
}
59-
59+
6060
struct Repo: Codable {
6161
public let id: String
6262
public let type: RepoType

0 commit comments

Comments
 (0)