Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 86 additions & 0 deletions Source/MLXOptimizers/Schedulers.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
// Copyright © 2024 Apple Inc.

import Foundation

// Learning-rate schedules. Ports of `mlx.optimizers.schedulers`.
//
// Each function returns a closure mapping a step count to a learning rate.
// Use it by assigning the optimizer's `learningRate` each step, e.g.
//
// ```swift
// let schedule = cosineDecay(1e-1, decaySteps: 1000)
// let optimizer = SGD(learningRate: schedule(0))
// for step in 0 ..< 1000 {
// optimizer.learningRate = schedule(step)
// optimizer.update(model: model, gradients: grads)
// }
// ```

/// Make an exponential-decay schedule: `initial * decayRate ** step`.
///
/// - Parameters:
/// - initial: initial value
/// - decayRate: multiplicative factor to decay by each step
public func exponentialDecay(_ initial: Float, decayRate: Float) -> (Int) -> Float {
{ step in initial * pow(decayRate, Float(step)) }
}

/// Make a step-decay schedule: `initial * decayRate ** (step / stepSize)`.
///
/// - Parameters:
/// - initial: initial value
/// - decayRate: multiplicative factor to decay by
/// - stepSize: decay every `stepSize` steps
public func stepDecay(_ initial: Float, decayRate: Float, stepSize: Int) -> (Int) -> Float {
{ step in initial * pow(decayRate, Float(step / stepSize)) }
}

/// Make a cosine-decay schedule. The value is constant (`end`) for steps beyond
/// `decaySteps`.
///
/// - Parameters:
/// - initial: initial value
/// - decaySteps: number of steps to decay over
/// - end: final value to decay to (default 0)
public func cosineDecay(_ initial: Float, decaySteps: Int, end: Float = 0.0) -> (Int) -> Float {
{ step in
let s = Float(min(step, decaySteps))
let decay = 0.5 * (1.0 + cos((Float.pi / Float(decaySteps)) * s))
return end + decay * (initial - end)
}
}

/// Make a linear schedule from `initial` to `end` over `steps`. The value is
/// `end` for any steps beyond `steps`.
///
/// - Parameters:
/// - initial: initial value
/// - end: final value
/// - steps: number of steps to apply the schedule over (must be >= 1)
public func linearSchedule(_ initial: Float, end: Float, steps: Int) -> (Int) -> Float {
precondition(steps >= 1, "steps must be greater than 0, but got \(steps).")
return { step in
let s = Float(min(step, steps))
return s * ((end - initial) / Float(steps)) + initial
}
}

/// Join multiple schedules into one. Schedule `i + 1` receives a step count
/// indicating the number of steps since the `i`-th boundary.
///
/// - Parameters:
/// - schedules: the schedules to join
/// - boundaries: `schedules.count - 1` step counts marking transitions
public func joinSchedules(_ schedules: [(Int) -> Float], boundaries: [Int]) -> (Int) -> Float {
precondition(!schedules.isEmpty, "Must provide at least 1 schedule to join.")
precondition(
schedules.count == boundaries.count + 1,
"Received \(boundaries.count) boundaries but expected \(schedules.count - 1).")
return { step in
var output = schedules[0](step)
for (boundary, schedule) in zip(boundaries, schedules.dropFirst()) where step >= boundary {
output = schedule(step - boundary)
}
return output
}
}
59 changes: 59 additions & 0 deletions Tests/MLXTests/SchedulerTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// Copyright © 2024 Apple Inc.

import Foundation
import XCTest

@testable import MLXOptimizers

class SchedulerTests: XCTestCase {

func testExponentialDecay() {
let s = exponentialDecay(0.1, decayRate: 0.9)
XCTAssertEqual(s(0), 0.1, accuracy: 1e-6)
XCTAssertEqual(s(1), 0.09, accuracy: 1e-6)
XCTAssertEqual(s(2), 0.081, accuracy: 1e-6)
XCTAssertEqual(s(5), 0.1 * 0.9 * 0.9 * 0.9 * 0.9 * 0.9, accuracy: 1e-6)
}

func testStepDecay() {
let s = stepDecay(0.1, decayRate: 0.9, stepSize: 10)
XCTAssertEqual(s(0), 0.1, accuracy: 1e-6)
XCTAssertEqual(s(9), 0.1, accuracy: 1e-6) // constant within a step window
XCTAssertEqual(s(10), 0.09, accuracy: 1e-6)
XCTAssertEqual(s(21), 0.081, accuracy: 1e-6) // 0.1 * 0.9^2
}

func testCosineDecay() {
let s = cosineDecay(0.1, decaySteps: 1000)
XCTAssertEqual(s(0), 0.1, accuracy: 1e-6)
XCTAssertEqual(s(500), 0.05, accuracy: 1e-6) // half-way: 0.5*(1+cos(pi/2))*0.1
XCTAssertEqual(s(1000), 0.0, accuracy: 1e-6)
XCTAssertEqual(s(5000), 0.0, accuracy: 1e-6) // clamped beyond decaySteps

// non-zero end value
let s2 = cosineDecay(0.1, decaySteps: 100, end: 0.01)
XCTAssertEqual(s2(0), 0.1, accuracy: 1e-6)
XCTAssertEqual(s2(100), 0.01, accuracy: 1e-6)
}

func testLinearSchedule() {
let s = linearSchedule(0.0, end: 0.1, steps: 100)
XCTAssertEqual(s(0), 0.0, accuracy: 1e-6)
XCTAssertEqual(s(50), 0.05, accuracy: 1e-6)
XCTAssertEqual(s(100), 0.1, accuracy: 1e-6)
XCTAssertEqual(s(200), 0.1, accuracy: 1e-6) // clamped beyond steps
}

func testJoinSchedules() {
// warm-up linearly for 10 steps, then cosine-decay.
let linear = linearSchedule(0.0, end: 0.1, steps: 10)
let cosine = cosineDecay(0.1, decaySteps: 200)
let s = joinSchedules([linear, cosine], boundaries: [10])

XCTAssertEqual(s(0), 0.0, accuracy: 1e-6) // linear leg
XCTAssertEqual(s(5), 0.05, accuracy: 1e-6) // linear leg
XCTAssertEqual(s(10), 0.1, accuracy: 1e-6) // cosine leg at its step 0
// at step 11 we are 1 step into the cosine schedule
XCTAssertEqual(s(11), cosine(1), accuracy: 1e-6)
}
}
Loading