Initialize optimizer research workspace with official baselines and history-free coverage

Vendor pinned MeZO, AGZO, LOZO and LoREN sources with independent environments. Add direct in-place fix/adjust/node training, derived history-free basis gradients, development-best checkpoints and experiment tooling. Keep models, datasets, caches and credentials outside Git.

Validation: 93 project tests passed; 521 vendored author files verified.
This commit is contained in:
gloamxun committed 2026-11-12 23:32:33 +08:00
commit e0feabec8f
596 files changed
+87356

No files matched your search

+4
View File
@@ -0,0 +1,4 @@
from .logging import get_logger
__all__ = ['get_logger']
+73
View File
@@ -0,0 +1,73 @@
import math
import torch
@torch.no_grad()
def generate_basis(m, rank, ref_mat, orthogonal=False):
Z = torch.randn(m, rank, dtype=ref_mat.dtype, device=ref_mat.device)
if orthogonal is True:
U, S, Vt = torch.linalg.svd(Z.T @ Z)
S = 1. / torch.sqrt(S)
return (Z @ U @ torch.diag(S) @ Vt) * math.sqrt(rank)
else:
return Z
@torch.no_grad()
def sgd_with_wdecay(param, grad, lr, weight_decay):
param.mul_(1 - lr * weight_decay)
param.add_(grad, alpha=-lr)
@torch.no_grad()
def ema_update(param, grad, lr, weight_decay, beta):
updated_param = param.mul(1 - lr * weight_decay)
updated_param.add_(grad, alpha=-lr)
param.mul_(beta).add_(updated_param, alpha=1.0 - beta)
def exponential_cooling_schedule(initial_temp, alpha, iteration):
"""
Exponential cooling schedule function for simulated annealing.
Parameters:
initial_temp (float): The initial temperature.
alpha (float): The cooling rate (0 < alpha < 1).
iteration (int): The current iteration number.
Returns:
float: The temperature at the given iteration.
"""
return initial_temp * (alpha ** iteration)
def logarithmic_cooling_schedule(initial_temp, iteration):
"""
Logarithmic cooling schedule function for simulated annealing.
Parameters:
initial_temp (float): The initial temperature.
iteration (int): The current iteration number.
Returns:
float: The temperature at the given iteration.
"""
return initial_temp / (1 + math.log(1 + iteration))
def linear_cooling_schedule(initial_temp, final_temp, max_iterations, iteration):
"""
Linear cooling schedule function for simulated annealing.
Parameters:
initial_temp (float): The initial temperature.
final_temp (float): The final temperature.
max_iterations (int): The maximum number of iterations.
iteration (int): The current iteration number.
Returns:
float: The temperature at the given iteration.
"""
return initial_temp - (initial_temp - final_temp) * (iteration / max_iterations)
@@ -0,0 +1,208 @@
import math
import warnings
from functools import partial
from typing import Callable, Iterable, Optional, Tuple, Union
import torch
from torch import nn
# from torch.optim import Optimizer
# from torch.optim.lr_scheduler import LambdaLR, ReduceLROnPlateau
from transformers.utils import logging
from transformers.utils.versions import require_version
logger = logging.get_logger(__name__)
def get_reduce_on_plateau_schedule(learning_rate, name, num_warmup_steps, num_decay_steps, current_step,
num_training_steps):
# to be updated
return learning_rate
def _get_inverse_sqrt_schedule_lr_lambda(current_step: int, *, num_warmup_steps: int, timescale: int = None):
if current_step < num_warmup_steps:
return float(current_step) / float(max(1, num_warmup_steps))
shift = timescale - num_warmup_steps
decay = 1.0 / math.sqrt((current_step + shift) / timescale)
return decay
def get_inverse_sqrt_schedule(learning_rate, name, num_warmup_steps, num_decay_steps, current_step, num_training_steps):
# to be updated
return learning_rate
def get_constant_schedule_with_warmup(learning_rate, name, num_warmup_steps, num_decay_steps, current_step,
num_training_steps):
if current_step < num_warmup_steps:
return float(current_step) / float(max(1.0, num_warmup_steps)) * learning_rate
return learning_rate
def get_linear_schedule_with_warmup(learning_rate, name, num_warmup_steps, num_decay_steps, current_step,
num_training_steps):
if current_step < num_warmup_steps:
return float(current_step) / float(max(1, num_warmup_steps)) * learning_rate
return max(0.0, float(num_training_steps - current_step) / float(
max(1, num_training_steps - num_warmup_steps))) * learning_rate
def get_cosine_schedule_with_warmup(learning_rate, name, num_warmup_steps, num_decay_steps, current_step,
num_training_steps):
num_cycles = 2
if current_step < num_warmup_steps:
return float(current_step) / float(max(1, num_warmup_steps)) * learning_rate
progress = float(current_step - num_warmup_steps) / float(max(1, num_training_steps - num_warmup_steps))
return max(0.0, 0.5 * (1.0 + math.cos(math.pi * float(num_cycles) * 2.0 * progress))) * learning_rate
def get_cosine_with_hard_restarts_schedule_with_warmup(learning_rate, name, num_warmup_steps, num_decay_steps,
current_step, num_training_steps):
num_cycles = 2
if current_step < num_warmup_steps:
return float(current_step) / float(max(1, num_warmup_steps)) * learning_rate
progress = float(current_step - num_warmup_steps) / float(max(1, num_training_steps - num_warmup_steps))
if progress >= 1.0:
return 0.0 * learning_rate
return max(0.0, 0.5 * (1.0 + math.cos(math.pi * ((float(num_cycles) * progress) % 1.0)))) * learning_rate
def get_polynomial_decay_schedule_with_warmup(learning_rate, name, num_warmup_steps, num_decay_steps, current_step,
num_training_steps):
lr_init = learning_rate
lr_end = 1e-10
power = 3
if current_step < num_warmup_steps:
return float(current_step) / float(max(1, num_warmup_steps)) * learning_rate
elif current_step > num_training_steps:
return lr_end / lr_init * learning_rate # as LambdaLR multiplies by lr_init
else:
lr_range = lr_init - lr_end
decay_steps = num_training_steps - num_warmup_steps
pct_remaining = 1 - (current_step - num_warmup_steps) / decay_steps
decay = lr_range * pct_remaining ** power + lr_end
return decay / lr_init * learning_rate # as LambdaLR multiplies by lr_init
def get_polynomial_decay_schedule(learning_rate, name, num_warmup_steps, num_decay_steps, current_step,
num_training_steps):
lr_init = learning_rate
lr_end = 1e-10
power = 3
if current_step > num_training_steps:
return lr_end / lr_init * learning_rate # as LambdaLR multiplies by lr_init
else:
lr_range = lr_init - lr_end
decay_steps = num_training_steps - 0
pct_remaining = 1 - (current_step - 0) / decay_steps
decay = lr_range * pct_remaining ** power + lr_end
return decay / lr_init * learning_rate # as LambdaLR multiplies by lr_init
def get_constant_polynomial_decay_schedule(learning_rate, name, num_warmup_steps, num_decay_steps, current_step,
num_training_steps):
lr_init = learning_rate
lr_end = 1e-10
power = 3
if current_step < num_decay_steps:
return learning_rate
elif current_step > num_training_steps:
return lr_end / lr_init * learning_rate # as LambdaLR multiplies by lr_init
else:
lr_range = lr_init - lr_end
decay_steps = num_training_steps - num_decay_steps
pct_remaining = 1 - (current_step - num_decay_steps) / decay_steps
decay = lr_range * pct_remaining ** power + lr_end
return decay / lr_init * learning_rate / 100 # as LambdaLR multiplies by lr_init
def get_constant_decay1_schedule(current_step, num_training_steps):
if current_step < 9800:
return 1e-6
else:
return 1e-8
def get_constant6_schedule(current_step, num_training_steps):
return 1e-6
def get_constant8_schedule(current_step, num_training_steps):
return 1e-8
def get_constant10_schedule(current_step, num_training_steps):
return 1e-10
def get_constant12_schedule(current_step, num_training_steps):
return 1e-12
def get_constant4_schedule(current_step, num_training_steps):
return 1e-4
def get_constant2_schedule(current_step, num_training_steps):
return 1e-2
def get_constant0_schedule(current_step, num_training_steps):
return 0
def get_constant_schedule_with_warmup(current_step, num_training_steps):
if current_step < num_warmup_steps:
return float(current_step) / float(max(1.0, num_warmup_steps)) * 1e-6
return 0
def get_constant_polynomial_decay_schedule_with_warmup(learning_rate, name, num_warmup_steps, num_decay_steps,
current_step, num_training_steps):
lr_init = learning_rate
lr_end = 1e-7
power = 3
if current_step < num_warmup_steps:
return float(current_step) / float(max(1, num_warmup_steps)) * learning_rate
elif current_step >= num_warmup_steps and current_step < num_decay_steps:
return learning_rate
elif current_step > num_training_steps:
return lr_end / lr_init * learning_rate # as LambdaLR multiplies by lr_init
else:
lr_range = lr_init - lr_end
decay_steps = num_training_steps - num_decay_steps
pct_remaining = 1 - (current_step - num_decay_steps) / decay_steps
decay = lr_range * pct_remaining ** power + lr_end
return decay / lr_init * learning_rate # as LambdaLR multiplies by lr_init
TYPE_TO_SCHEDULER_FUNCTION = {
'linear_with_warmup': get_linear_schedule_with_warmup,
'cosine_with_warmup': get_cosine_schedule_with_warmup,
'cosine_with_hard_restarts_with_warmup': get_cosine_with_hard_restarts_schedule_with_warmup,
'polynomial_decay_with_warmup': get_polynomial_decay_schedule_with_warmup,
'inverse_sqrt': get_inverse_sqrt_schedule,
'reduce_on_plateau': get_reduce_on_plateau_schedule,
'constant_polynomial_decay': get_constant_polynomial_decay_schedule,
'constant_polynomial_decay_with_warmup': get_constant_polynomial_decay_schedule_with_warmup,
'polynomial_decay': get_polynomial_decay_schedule,
'constant0': get_constant0_schedule,
'constant1e-6': get_constant6_schedule,
'constant1e-8': get_constant8_schedule,
'constant1e-10': get_constant10_schedule,
'constant1e-12': get_constant12_schedule,
'constant1e-2': get_constant2_schedule,
'constant1e-4': get_constant4_schedule,
'constant_with_warmup': get_constant_schedule_with_warmup,
'constant_decay1': get_constant_decay1_schedule,
}
def Hessian_smooth_scheduler(Hessian_smooth_type, current_step, num_training_steps):
schedule_func = TYPE_TO_SCHEDULER_FUNCTION[Hessian_smooth_type]
return schedule_func(current_step, num_training_steps)
+39
View File
@@ -0,0 +1,39 @@
import sys
from loguru import logger
__all__ = ["get_logger"]
logger_sink = {}
LOG_FORMAT = (
"[<green>{time:MM-DD HH:mm:ss}</green>] "
# "<red>[{process.name}]</red>|"
# "<yellow>{level: <6}</yellow> "
# "<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan>\n\t - <level>{message}</level>\n"
"<yellow>{function}</yellow>:<cyan>{line:<4}</cyan>| {message}"
)
logger.remove()
def get_logger(file_name=None, clear=False, **kwargs):
global logger_sink
if clear:
logger.remove()
logger_sink.clear()
if file_name is None:
file_name = sys.stderr
if "level" not in kwargs:
kwargs["level"] = "INFO"
if "format" not in kwargs:
kwargs["format"] = LOG_FORMAT
if file_name in logger_sink.values():
logger.debug(f"{str(file_name)} already registered")
else:
sink_id = logger.add(file_name, **kwargs)
logger_sink[sink_id] = file_name
logger.debug(f"sink_id: {sink_id:02d} ---> {str(file_name)}")
return logger
+171
View File
@@ -0,0 +1,171 @@
import os
import pickle
import torch
import contextlib
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
matplotlib.rcParams['pdf.fonttype'] = 42
plt.rcParams.update({'font.size': 12})
def save_pickle(data, folder, filename):
os.makedirs(folder, exist_ok=True)
filepath = os.path.join(folder, filename)
with open(filepath, 'wb') as file:
pickle.dump(data, file)
def load_pickle(file_path, key):
try:
with open(file_path, 'rb') as file:
# Load the data from the pickle file
data = pickle.load(file)
# Print the contents of the pickle file
print("Contents of the pickle file:")
if key == 'Tr_Loss':
arr = windowed_mean(data[key], window_size=4)
print(np.nanmin(arr))
elif key == 'Val_Acc':
arr = windowed_mean(data[key], window_size=4)
print(np.max(arr))
elif key == 'Query':
print(np.sum(data[key]))
else:
print(data[key])
except FileNotFoundError:
print(f"Error: File '{file_path}' not found.")
except Exception as e:
print(f"Error: Unable to load the pickle file. {e}")
def convert_to_cpu_float(dictionary):
"""
Convert PyTorch tensors in a dictionary from cuda:0 to floats on CPU.
Parameters:
- dictionary: Dictionary with keys and PyTorch tensors/lists of tensors on cuda:0.
Returns:
- Converted dictionary with tensors/lists as floats on CPU.
"""
converted_dict = {}
for key, value in dictionary.items():
if isinstance(value, torch.Tensor):
converted_dict[key] = value.cpu().float()
elif isinstance(value, list):
converted_dict[key] = [item.cpu().numpy() for item in value]
else:
converted_dict[key] = value # Non-tensor values remain unchanged
return converted_dict
def average_across_batch(arr, epochs):
arr_np = np.array(arr)
arr_avg = np.mean(np.array(np.split(arr_np, epochs)), axis=1)
return np.reshape(arr_avg, (1, arr_avg.shape[0]))
def moving_average(a, n=20):
ret = np.cumsum(a, dtype=float)
ret[n:] = ret[n:] - ret[:-n]
return ret[n - 1:] / n
def plot_results(title, d, loss="Train Loss: ", lim_x=1000, lim_y=3):
plt.figure()
for k, val in d.items():
v = np.array([val])
means = np.mean(v, axis=0)
# mins = np.amin(v, axis=0)
# maxes = np.amax(v, axis=0)
means = moving_average(means)
plt.plot(range(1, len(means)+1), means, linewidth=2, linestyle='solid', markersize=12, label=k)
plt.title(title)
plt.yscale('log')
plt.xlim(1, lim_x)
plt.ylim(0.9, lim_y)
plt.ylabel(loss)
plt.xlabel('Step')
plt.legend(bbox_to_anchor=(0.65, 1.0), loc="upper left")
plt.grid()
plt.tight_layout()
plt.savefig(title + '.pdf')
def plot_results_time(title, d_y, d_x, loss="Train Loss: ", lim_x=1000, lim_y=3):
plt.figure()
for k, val in d_y.items():
v = np.array([val])
v_x = np.cumsum(np.array([d_x[k]]))*(1e-17)
means = np.mean(v, axis=0)
# mins = np.amin(v, axis=0)
# maxes = np.amax(v, axis=0)
means = moving_average(means)
ll = len(means)
plt.plot(v_x[:ll], means, linewidth=2, linestyle='solid', markersize=12, label=k)
plt.title(title)
plt.yscale('log')
plt.xscale('log')
plt.xlim(0, lim_x)
# plt.ylim(0.7, lim_y)
plt.ylabel(loss)
plt.xlabel('Time (s)')
plt.legend(bbox_to_anchor=(0.0, 1), loc="upper left")
plt.grid()
plt.tight_layout()
plt.savefig(title + '.pdf')
def plot_results_query(title, d_y, d_x, loss="Train Loss: ", lim_x=1000, lim_y=3):
plt.figure()
for k, val in d_y.items():
v = np.array([val])
v_x = np.cumsum(np.array([d_x[k]]))
means = np.mean(v, axis=0)
# mins = np.amin(v, axis=0)
# maxes = np.amax(v, axis=0)
means = moving_average(means)
ll = len(means)
plt.plot(v_x[:ll], means, linewidth=2, linestyle='solid', markersize=12, label=k)
plt.title(title)
plt.yscale('log')
plt.xscale('log')
plt.xlim(1e3, lim_x)
plt.ylim(0.7, lim_y)
plt.ylabel(loss)
plt.xlabel('Queries')
plt.legend(bbox_to_anchor=(0.0, 1), loc="upper left")
plt.grid()
plt.tight_layout()
plt.savefig(title + '.pdf')
def windowed_mean(arr, window_size):
arr = np.array(arr)
return np.mean(arr.reshape(-1, window_size), axis=1)
@contextlib.contextmanager
def temp_seed(seed):
state = np.random.get_state()
np.random.seed(seed)
try:
yield
finally:
np.random.set_state(state)