Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

A small improvement on SGD with mementum optimizer #1545

Merged
merged 3 commits into from
Dec 9, 2024
Merged
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
17 changes: 11 additions & 6 deletions Compiler/ml.py
Original file line number Diff line number Diff line change
Expand Up @@ -2925,10 +2925,12 @@ def __init__(self, layers, n_epochs=1, debug=False, report_loss=None):
self.layers = layers
self.n_epochs = n_epochs
self.nablas = []
self.momentum_values = []
self.delta_thetas = []
for layer in layers:
self.nablas.extend(layer.nablas())
for theta in layer.thetas():
self.momentum_values.append(theta.same_shape())
self.delta_thetas.append(theta.same_shape())
self.set_learning_rate(0.01)
self.debug = debug
Expand All @@ -2948,23 +2950,27 @@ def _(i):
j = i + label * len(X_by_label[0])
self.layers[0].X[j] = X[i]
self.layers[-1].Y[j] = label
for y in self.momentum_values:
y.assign_all(0)
for y in self.delta_thetas:
y.assign_all(0)
super(SGD, self).reset()

def _update(self, i_epoch, i_batch, batch):
for nabla, theta, delta_theta in zip(self.nablas, self.thetas,
self.delta_thetas):
for nabla, theta, momentum_value, delta_theta in zip(self.nablas, self.thetas,
self.momentum_values, self.delta_thetas):
@multithread(self.n_threads, nabla.total_size())
def _(base, size):
old = delta_theta.get_vector(base, size)
old = momentum_value.get_vector(base, size)
red_old = self.momentum * old
rate = self.gamma.expand_to_vector(size)
nabla_vector = nabla.get_vector(base, size)
log_batch_size = math.log(len(batch), 2)
# divide by len(batch) by truncation
# increased rate if len(batch) is not a power of two
pre_trunc = nabla_vector.v * rate.v
diff = red_old - nabla_vector
pre_trunc = diff.v * rate.v
momentum_value.assign_vector(diff, base)
k = max(nabla_vector.k, rate.k) + rate.f
m = rate.f + int(log_batch_size)
if self.early_division:
Expand All @@ -2973,8 +2979,7 @@ def _(base, size):
v = pre_trunc.round(k, m, signed=True,
nearest=sfix.round_nearest)
new = nabla_vector._new(v)
diff = red_old - new
delta_theta.assign_vector(diff, base)
delta_theta.assign_vector(new, base)
theta.assign_vector(theta.get_vector(base, size) +
delta_theta.get_vector(base, size), base)
if self.print_update_average:
Expand Down