MCPcopy Create free account
hub / github.com/bitsandbytes-foundation/bitsandbytes / run_compare

Function run_compare

examples/cpu/cpu_training.py:193–236  ·  view source on GitHub ↗

Compare bnb AdamW vs torch AdamW on CPU to verify correctness.

(args)

Source from the content-addressed store, hash-verified

191
192
193def run_compare(args):
194 """Compare bnb AdamW vs torch AdamW on CPU to verify correctness."""
195 dtype = get_torch_dtype(args.dtype)
196 print(f"=== Comparing bnb AdamW vs torch AdamW on CPU ({args.dtype}) ===\n")
197
198 tokenizer = AutoTokenizer.from_pretrained(args.model)
199 if tokenizer.pad_token is None:
200 tokenizer.pad_token = tokenizer.eos_token
201
202 ds = prepare_data(tokenizer, args.dataset, args.max_length, num_samples=100)
203 dataloader = torch.utils.data.DataLoader(
204 ds,
205 batch_size=args.batch_size,
206 shuffle=False,
207 collate_fn=collate_fn,
208 )
209
210 results = {}
211 for label, make_opt in [
212 ("bnb.AdamW", lambda m: bnb.optim.AdamW(m.parameters(), lr=args.lr)),
213 ("torch.AdamW", lambda m: torch.optim.AdamW(m.parameters(), lr=args.lr)),
214 ]:
215 print(f"\n>> {label}")
216 torch.manual_seed(42)
217 model = AutoModelForCausalLM.from_pretrained(args.model, dtype=dtype)
218 optimizer = make_opt(model)
219 history = train_loop(model, optimizer, dataloader, args.steps, args.log_interval)
220 results[label] = history
221
222 print(f"\n{'Step':>5} | {'bnb Loss':>10} | {'torch Loss':>11} | {'Diff':>10}")
223 print("-" * 50)
224 h_bnb = results["bnb.AdamW"]
225 h_pt = results["torch.AdamW"]
226 for i in range(0, min(len(h_bnb), len(h_pt)), max(1, args.log_interval)):
227 s1, l1, _ = h_bnb[i]
228 _, l2, _ = h_pt[i]
229 print(f"{s1:5d} | {l1:10.4f} | {l2:11.4f} | {abs(l1 - l2):10.6f}")
230
231 final_diff = abs(h_bnb[-1][1] - h_pt[-1][1])
232 print(f"\nFinal loss difference: {final_diff:.6f}")
233 if final_diff < 0.01:
234 print("OK: bnb and torch AdamW produce nearly identical results on CPU.")
235 else:
236 print("NOTE: Some divergence detected (may grow over many steps).")
237
238
239def run_with_trainer(args):

Callers 1

mainFunction · 0.70

Calls 3

get_torch_dtypeFunction · 0.70
prepare_dataFunction · 0.70
train_loopFunction · 0.70

Tested by

no test coverage detected