Run this model with HF Jobs
Run akhaliq/MOSS-Image-SFT-4-steps on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/akhaliq/MOSS-Image-SFT-4-steps. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/akhaliq/MOSS-Image-SFT-4-steps on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use akhaliq/MOSS-Image-SFT-4-steps with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Diffusers
How to use akhaliq/MOSS-Image-SFT-4-steps with Diffusers:
pip install -U diffusers transformers accelerate
import torch from diffusers import DiffusionPipeline # switch to "mps" for apple devices pipe = DiffusionPipeline.from_pretrained("OpenMOSS-Team/MOSS-Image-SFT", dtype=torch.bfloat16, device_map="cuda") pipe.load_lora_weights("akhaliq/MOSS-Image-SFT-4-steps") prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k" image = pipe(prompt).images[0] - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- Draw Things
- DiffusionBee
Add training script (data-space DMD, 4-step, warm-started LoRA-128)
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513"""Data-space DMD 4-step distillation of MOSS-Image-SFT.
Warm-starts from lodestones/MOSS-Image-SFT-8-steps-dmd: - generator = base SFT transformer (fp32) + its rank-128 LoRA (trainable, continued) + time_embedding / modulation-bias replacements (trainable) - latent_mix.Q and step_codes[:4] (trainable), 4-step prefix schedule - teacher = frozen base SFT transformer (bf16), CFG 3, uncond skip layer 22 - fake score = base SFT transformer (bf16) + fresh rank-128 LoRA (trainable)
Flow-matching DMD gradient (derived for v-parameterization, v = eps - x0): DMD grad wrt x0 = (s_fake - s_real)(1-t); s = (-x_t - (1-t)v)/t => grad ∝ (v_real - v_fake) — applied as x0.backward(v_real - v_fake).
Reference: arXiv 2610.12102 (data-space DMD), LightX2V DMD-LoRA recipe(1-2K generator updates, uniform fake-score timesteps), SiD App. E(fp32 master + bf16 autocast), Flash-DMD (TTUR 1 viable)."""
import argparseimport copyimport importlib.utilimport jsonimport mathimport randomimport sysimport timefrom pathlib import Path
import numpy as npimport signalimport torchfrom torch import nnfrom torch.utils.checkpoint import checkpointfrom huggingface_hub import HfApi, hf_hub_downloadfrom safetensors.torch import load_file, save_file
BASE_REPO = "OpenMOSS-Team/MOSS-Image-SFT"DMD_REPO = "lodestones/MOSS-Image-SFT-8-steps-dmd"LORA_TARGETS = ("q", "k", "v", "o", "ffn_up_gate", "ffn_down")
# ---------------------------------------------------------------- LoRA -----class LoRALinear(nn.Module): def __init__(self, base: nn.Linear, rank: int, alpha: float): super().__init__() self.base = base for p in self.base.parameters(): p.requires_grad_(False) self.lora_down = nn.Linear(base.in_features, rank, bias=False) self.lora_up = nn.Linear(rank, base.out_features, bias=False) nn.init.zeros_(self.lora_up.weight) self.rank = rank self.alpha = alpha
@property def weight(self): # pipeline_moss_image._Block reads self.proj['q'].weight.dtype return self.base.weight
def forward(self, x): out = self.base(x) # LoRA weights stay fp32 (Adam master); branch runs in weight dtype and # is cast back to the base output dtype (bf16 fake / autocast gen). delta = self.lora_up(self.lora_down(x.to(self.lora_down.weight.dtype))) return out + (delta * (self.alpha / self.rank)).to(out.dtype)
def apply_lora(transformer, rank, alpha): count = 0 for layer in transformer.layers: for name in LORA_TARGETS: layer.proj[name] = LoRALinear(layer.proj[name], rank, alpha) count += 1 return count
def patch_block_checkpointing(transformer): """Checkpoint each DiT block: backward stores one input per block (~50 MB) instead of every layer's activations (~40 GB at 1024px).""" for layer in transformer.layers: orig = layer.forward layer.forward = lambda x, rope, modulation, _orig=orig: checkpoint( _orig, x, rope, modulation, use_reentrant=False)
def lora_state_dict(transformer, prefix="diffusion_model."): state = {} for i, layer in enumerate(transformer.layers): for name in LORA_TARGETS: mod = layer.proj[name] key = f"{prefix}layers.{i}.proj.{name}" state[f"{key}.lora_down.weight"] = mod.lora_down.weight.detach().float().cpu() state[f"{key}.lora_up.weight"] = mod.lora_up.weight.detach().float().cpu() state[f"{key}.alpha"] = torch.tensor(float(mod.alpha)) return state
def load_lora_state(transformer, state, prefix="diffusion_model."): for i, layer in enumerate(transformer.layers): for name in LORA_TARGETS: mod = layer.proj[name] key = f"{prefix}layers.{i}.proj.{name}" mod.lora_down.weight.data.copy_(state[f"{key}.lora_down.weight"]) mod.lora_up.weight.data.copy_(state[f"{key}.lora_up.weight"]) mod.alpha = float(state[f"{key}.alpha"])
# ------------------------------------------------------------- prompts -----STYLES = ["photograph", "flat-design illustration", "watercolor painting", "3D render", "ink sketch", "isometric illustration", "oil painting", "studio product photo", "cinematic photo", "risograph print"]SCENES = [ ("a poster for a jazz night", "'JAZZ NIGHT'", "'周六 21:00 · 蓝鸟酒吧'"), ("a cafe chalkboard menu", "'TODAY'S SPECIAL'", "'手冲咖啡 ¥28'"), ("a whiteboard project plan", "'Launch Plan'", "'数据 → 模型 → 评估'"), ("a book cover", "'The Silent River'", "'静默之河'"), ("a concert ticket", "'SUMMER FEST 2026'", "'杭州 · 奥体中心'"), ("a tea package label", "'Dragon Well 龙井'", "'2026 明前新茶'"), ("a subway wayfinding sign", "'Line 2 · Exit C'", "'换乘2号线'"), ("a museum exhibition banner", "'DINOSAURS'", "'恐龙特展 · 3月1日开幕'"), ("a bakery storefront sign", "'Morning Bread'", "'每日新鲜出炉'"), ("a conference badge", "'AI EXPO 2026'", '"演讲者 · Speaker"'), ("a notebook page with a todo list", "'TODO'", "'买牛奶、寄快递、打电话'"), ("a gym class schedule board", "'YOGA 18:30'", "'周一三五 · 二楼'"), ("a ramen shop curtain", "'RAMEN'", "'ラーメン · 拉面'"), ("a farmers market stall sign", "'ORGANIC'", "'有机蔬菜 · 本地种植'"), ("a movie poster", "'NIGHT TRAIN'", "'午夜列车 · 12月上映'"), ("a library reading-room sign", "'SILENCE PLEASE'", "'请保持安静'"),]NO_TEXT_SCENES = [ "a red paper lantern floating over a misty river at dawn", "a lighthouse on a rocky coast under a stormy sky", "a Shiba Inu puppy sleeping in a wicker basket", "terraced rice fields in morning fog, aerial view", "an astronaut floating in a retro-futuristic space station", "a bowl of ramen with soft-boiled egg, top-down studio shot", "autumn ginkgo leaves falling on a quiet temple path", "a vintage steam train crossing a stone viaduct in the Alps",]
def make_prompt(rng: random.Random) -> str: if rng.random() < 0.3: scene = rng.choice(NO_TEXT_SCENES) return f"{rng.choice(STYLES).capitalize()} of {scene}, high detail" scene, en, zh = rng.choice(SCENES) if rng.random() < 0.5: return (f"{rng.choice(STYLES).capitalize()} of {scene}. The main text reads " f"{en}, with smaller text {zh}. Clean composition, legible typography.") items = [ {"description": f"title text {en}", "bbox": [-420, -400, -200, 400]}, {"description": f"subtitle text {zh}", "bbox": [250, -400, 380, 400]}, {"description": "decorative illustration matching the theme", "bbox": [-150, -250, 200, 250]}, ] layout = {"summary": {"caption": f"A {rng.choice(STYLES)} of {scene}"}, "bbox_format": "yxyx", "bbox_coord_space": "abs_centralized", "items": items} return json.dumps(layout, ensure_ascii=False)
# ----------------------------------------------------------------- EMA -----class EMA: def __init__(self, params, decay): self.decay = decay self.shadow = {k: v.detach().clone() for k, v in params.items()}
@torch.no_grad() def update(self, params): for k, v in params.items(): self.shadow[k].mul_(self.decay).add_(v.detach(), alpha=1 - self.decay)
# ---------------------------------------------------------------- main -----def parse_args(): p = argparse.ArgumentParser() p.add_argument("--updates", type=int, default=1500) p.add_argument("--batch", type=int, default=2) p.add_argument("--steps", type=int, default=4) p.add_argument("--lr", type=float, default=1e-5) p.add_argument("--fake-lr", type=float, default=1e-5) p.add_argument("--fake-updates", type=int, default=1) p.add_argument("--rank", type=int, default=128) p.add_argument("--ema-decay", type=float, default=0.999) p.add_argument("--num-prompts", type=int, default=2048) p.add_argument("--size", type=int, default=1024) p.add_argument("--guidance", type=float, default=3.0) p.add_argument("--seed", type=int, default=0) p.add_argument("--warm-start", action=argparse.BooleanOptionalAction, default=True) p.add_argument("--log-every", type=int, default=10) p.add_argument("--sample-every", type=int, default=250) p.add_argument("--save-every", type=int, default=250) p.add_argument("--out-repo", type=str, default="akhaliq/moss-image-turbo") p.add_argument("--eval-repo", type=str, default="akhaliq/moss-image-turbo-eval") p.add_argument("--trackio-space", type=str, default="") p.add_argument("--grad-sign", type=float, default=1.0) p.add_argument("--smoke", action="store_true") return p.parse_args()
def load_pipeline_module(): path = hf_hub_download(BASE_REPO, "pipeline_moss_image.py") spec = importlib.util.spec_from_file_location("pipeline_moss_image", path) module = importlib.util.module_from_spec(spec) sys.modules["pipeline_moss_image"] = module spec.loader.exec_module(module) return module
def main(): args = parse_args() if args.smoke: args.updates, args.batch, args.num_prompts = 6, 1, 16 args.sample_every, args.save_every = 4, 6 torch.manual_seed(args.seed) np.random.seed(args.seed) rng = random.Random(args.seed) device = torch.device("cuda") assert torch.cuda.is_available() print(f"[setup] {torch.cuda.get_device_name(0)} args={vars(args)}", flush=True)
mod = load_pipeline_module() from transformers import AutoModel, AutoTokenizer from diffusers import AutoencoderKLFlux2
# ---- generator: base fp32 transformer + warm-start artifacts # bf16 base (matches the card's recommended bf16-base + fp32-adapter # inference mode); the distillation delta lives in the fp32 LoRA and # the fp32 time_embedding / modulation-bias replacements. gen = mod.MOSSImageTransformer.from_pretrained( BASE_REPO, subfolder="transformer", torch_dtype=torch.bfloat16) te = load_file(hf_hub_download(DMD_REPO, "time_embedding.safetensors")) missing = gen.load_state_dict(te, strict=False) with torch.no_grad(): # restore these six tensors to fp32 (load casts to bf16) for k, v in te.items(): gen.get_parameter(k).data = v.clone() assert len(missing.unexpected_keys) == 0 print(f"[setup] time_embedding replacements applied ({len(te)} tensors, " f"{len(missing.missing_keys)} gen keys untouched)", flush=True) n_lora = apply_lora(gen, args.rank, args.rank) patch_block_checkpointing(gen) if args.warm_start: lora_sd = load_file(hf_hub_download(DMD_REPO, "lora.safetensors")) load_lora_state(gen, lora_sd) print(f"[setup] warm-started {n_lora} LoRA modules from {DMD_REPO}", flush=True) for name, p in gen.named_parameters(): if "lora_" in name or "time_embedding" in name or \ "shared_block_modulation.bias" in name or \ "video_head_modulation.bias" in name: p.requires_grad_(True) else: p.requires_grad_(False) ds = load_file(hf_hub_download(DMD_REPO, "dataspace.safetensors")) Q = nn.Parameter(ds["latent_mix.Q"].float().to(device)) codes = nn.Parameter(ds["step_codes"][:args.steps].float().to(device)) gen = gen.to(device)
# ---- teacher (frozen bf16) and fake score (bf16 + fresh LoRA) teacher = mod.MOSSImageTransformer.from_pretrained( BASE_REPO, subfolder="transformer", torch_dtype=torch.bfloat16).eval().to(device) for p in teacher.parameters(): p.requires_grad_(False) fake = mod.MOSSImageTransformer.from_pretrained( BASE_REPO, subfolder="transformer", torch_dtype=torch.bfloat16) apply_lora(fake, args.rank, args.rank) patch_block_checkpointing(fake) fake = fake.to(device) for name, p in fake.named_parameters(): p.requires_grad_("lora_" in name)
tokenizer = AutoTokenizer.from_pretrained(BASE_REPO, subfolder="tokenizer") text_encoder = AutoModel.from_pretrained( BASE_REPO, subfolder="text_encoder", dtype=torch.bfloat16).eval().to(device) vae = AutoencoderKLFlux2.from_pretrained( BASE_REPO, subfolder="vae", torch_dtype=torch.float32).eval().to(device) for p in list(text_encoder.parameters()) + list(vae.parameters()): p.requires_grad_(False) pipe = mod.MOSSImagePipeline(gen, mod.MOSSImageScheduler(), text_encoder, tokenizer, vae) pipe.to(device)
# ---- prompt embedding cache (CPU), negative = empty prompt prompts = [make_prompt(rng) for _ in range(args.num_prompts)] print(f"[setup] encoding {len(prompts)} prompts...", flush=True) with torch.no_grad(): neg_embeds, neg_mask = pipe.encode_prompt("") neg_embeds, neg_mask = neg_embeds.cpu(), neg_mask.cpu() cache = [] for i in range(0, len(prompts), 32): e, m = pipe.encode_prompt(prompts[i:i + 32]) for j in range(e.shape[0]): keep = m[j].bool() cache.append((e[j][keep].cpu(), keep.sum().item())) print(f"[setup] cache done, sample prompt: {prompts[0][:120]!r}", flush=True)
# precompute sample-grid embeds, then free the text encoder (~18 GB) with torch.no_grad(): sample_embeds = [] for prompt in SAMPLE_PROMPTS: e, m = pipe.encode_prompt(prompt) sample_embeds.append((e.cpu(), m.cpu())) del pipe.text_encoder, pipe.tokenizer, text_encoder, tokenizer torch.cuda.empty_cache() print(f"[setup] text encoder freed; mem={torch.cuda.memory_allocated() / 2**30:.1f} GB", flush=True)
def get_embeds(indices): rows, lens = [], [] for i in indices: row, ln = cache[i] rows.append(row) lens.append(ln) maxlen = max(lens) embeds = torch.zeros(len(indices), maxlen, rows[0].shape[-1], dtype=torch.bfloat16) mask = torch.zeros(len(indices), maxlen, dtype=torch.bool) for j, (row, ln) in enumerate(zip(rows, lens)): embeds[j, :ln] = row mask[j, :ln] = True return (embeds.to(device), mask.to(device), neg_embeds.expand(len(indices), -1, -1).to(device), neg_mask.expand(len(indices), -1).to(device))
gen_params = {n: p for n, p in gen.named_parameters() if p.requires_grad} gen_params["Q"] = Q gen_params["codes"] = codes opt = torch.optim.Adam(list(gen_params.values()), lr=args.lr, betas=(0.0, 0.999)) fake_params = [p for _, p in fake.named_parameters() if p.requires_grad] fake_opt = torch.optim.Adam(fake_params, lr=args.fake_lr, betas=(0.0, 0.999)) ema = EMA(gen_params, args.ema_decay)
# save-on-terminate: timeouts/SIGTERM must not lose the run state = {"update": 0}
def _on_sigterm(*_): if state["update"] > 0: save_checkpoint(args, state["update"], gen, Q, codes, ema, gen_params) sys.exit(0) signal.signal(signal.SIGTERM, _on_sigterm)
tracker = None if args.trackio_space: import trackio tracker = trackio.init(project="moss-image-turbo", space_id=args.trackio_space, name=f"dmd4-u{args.updates}", config=vars(args))
h = w = args.size // 16 t_start = time.time() for update in range(1, args.updates + 1): state["update"] = update idx = [rng.randrange(len(prompts)) for _ in range(args.batch)] embeds, mask, neg_e, neg_m = get_embeds(idx) z = torch.randn(args.batch, 128, h, w, device=device, dtype=torch.float32)
# generator rollout (grad); per-block checkpointing inside gen def rollout(): x0 = torch.zeros_like(z) for r in range(args.steps): x = z + torch.einsum("oc,bchw->bohw", Q, x0) with torch.autocast("cuda", dtype=torch.bfloat16): v = gen(x, codes[r], embeds, mask).sample.float() x0 = z - v return x0 x0 = rollout()
# ---- fake-score update(s): flow-matching denoising on gen outputs x0_det = x0.detach() fake_loss_val = 0.0 for _ in range(args.fake_updates): tau = torch.rand(args.batch, 1, 1, 1, device=device) * 0.96 + 0.02 eps = torch.randn_like(x0_det) x_t = (1 - tau) * x0_det + tau * eps v_target = eps - x0_det v_fake = fake(x_t, (tau.flatten() * 1000), embeds, mask).sample.float() fake_loss = ((v_fake - v_target) ** 2).mean() fake_opt.zero_grad(set_to_none=True) fake_loss.backward() fake_opt.step() fake_loss_val = fake_loss.item()
# ---- generator DMD update tau_g = torch.tensor(np.random.beta(2.5, 1.0, size=args.batch), dtype=torch.float32, device=device) tau_g = (tau_g * 0.96 + 0.02).view(-1, 1, 1, 1) eps_g = torch.randn_like(x0) x_g = (1 - tau_g) * x0 + tau_g * eps_g t_scaled = tau_g.flatten() * 1000 with torch.no_grad(): cond = teacher(x_g, t_scaled, embeds, mask).sample.float() uncond = teacher(x_g, t_scaled, neg_e, neg_m, skip_layers=(22,)).sample.float() v_real = uncond + args.guidance * (cond - uncond) v_fake_g = fake(x_g, t_scaled, embeds, mask).sample.float() grad = args.grad_sign * (v_real - v_fake_g) opt.zero_grad(set_to_none=True) x0.backward(grad) gn = torch.nn.utils.clip_grad_norm_(list(gen_params.values()), 1.0) opt.step() ema.update(gen_params)
if update % args.log_every == 0 or update == 1: sps = args.batch / max(time.time() - t_start, 1e-9) * update stats = {"fake_loss": fake_loss_val, "grad_gap": (v_real - v_fake_g).abs().mean().item(), "grad_norm": float(gn), "samples_per_min": sps * 60, "mem_gb": torch.cuda.max_memory_allocated() / 2**30} print(f"[u{update}] " + " ".join(f"{k}={v:.4g}" for k, v in stats.items()), flush=True) if tracker is not None: tracker.log(stats, step=update)
if update % args.sample_every == 0 or update == args.updates: sample_and_save(args, update, gen, Q, codes, ema, gen_params, pipe, sample_embeds, device, h, w) if update % args.save_every == 0 and update < args.updates: save_checkpoint(args, update, gen, Q, codes, ema, gen_params)
if tracker is not None: tracker.finish() save_checkpoint(args, args.updates, gen, Q, codes, ema, gen_params) print(f"[done] {args.updates} updates in " f"{(time.time() - t_start) / 60:.1f} min", flush=True)
def apply_ema_into(gen_params, ema): backup = {k: v.detach().clone() for k, v in gen_params.items()} with torch.no_grad(): for k, v in gen_params.items(): v.copy_(ema.shadow[k]) return backup
SAMPLE_PROMPTS = [ 'A cozy cafe chalkboard menu with hand-lettered white chalk text: ' '"TODAY\'S SPECIAL — Flat White $4.50", warm lighting', 'A rainy neon-lit street in Shanghai at night, a glowing shop sign ' 'reading "深夜食堂" above the door, reflections on wet pavement',]
@torch.no_grad()def sample_and_save(args, update, gen, Q, codes, ema, gen_params, pipe, sample_embeds, device, h, w): from PIL import Image backup = apply_ema_into(gen_params, ema) gen.eval() tiles = [] for i, _prompt in enumerate(SAMPLE_PROMPTS): embeds, mask = (t.to(device) for t in sample_embeds[i]) z = torch.randn(1, 128, h, w, generator=torch.Generator("cpu").manual_seed(99 + i), device="cpu").to(device) x0 = torch.zeros_like(z) for r in range(args.steps): x = z + torch.einsum("oc,bchw->bohw", Q, x0) with torch.autocast("cuda", dtype=torch.bfloat16): v = gen(x, codes[r], embeds, mask).sample.float() x0 = z - v zv = x0.to(dtype=pipe.vae.dtype) bn = pipe.vae.bn zv = zv * (bn.running_var + pipe.vae.config.batch_norm_eps).sqrt().to(zv).view(1, -1, 1, 1) \ + bn.running_mean.to(zv).view(1, -1, 1, 1) b, c, hh, ww = zv.shape zv = zv.reshape(b, c // 4, 2, 2, hh, ww).permute(0, 1, 4, 2, 5, 3) zv = zv.reshape(b, c // 4, 2 * hh, 2 * ww) img = pipe.vae.decode(zv, return_dict=False)[0].clamp(-1, 1) tiles.append(pipe.image_processor.postprocess(img, output_type="pil")[0]) strip = Image.new("RGB", (args.size * len(tiles), args.size)) for i, t in enumerate(tiles): strip.paste(t, (i * args.size, 0)) out = Path(f"/tmp/samples/u{update}.png") out.parent.mkdir(parents=True, exist_ok=True) strip.save(out) HfApi().upload_file(repo_id=args.eval_repo, repo_type="dataset", path_or_fileobj=str(out), path_in_repo=f"training/u{update}.png") with torch.no_grad(): for k, v in gen_params.items(): v.copy_(backup[k]) gen.train() print(f"[u{update}] sample strip uploaded", flush=True)
def save_checkpoint(args, update, gen, Q, codes, ema, gen_params): backup = apply_ema_into(gen_params, ema) out = Path(f"/tmp/ckpt/u{update}") out.mkdir(parents=True, exist_ok=True) save_file(lora_state_dict(gen), str(out / "lora.safetensors")) te = {k: v.detach().float().cpu() for k, v in gen.state_dict().items() if "time_embedding" in k or "shared_block_modulation.bias" in k or "video_head_modulation.bias" in k} save_file(te, str(out / "time_embedding.safetensors")) save_file({"latent_mix.Q": Q.detach().float().cpu(), "step_codes": codes.detach().float().cpu()}, str(out / "dataspace.safetensors")) with open(out / "train_args.json", "w") as f: json.dump(vars(args), f, indent=2, default=str) api = HfApi() api.upload_folder(repo_id=args.out_repo, repo_type="model", folder_path=str(out), path_in_repo=f"checkpoint-update-{update}") api.upload_folder(repo_id=args.out_repo, repo_type="model", folder_path=str(out), path_in_repo="latest") with torch.no_grad(): for k, v in gen_params.items(): v.copy_(backup[k]) print(f"[u{update}] checkpoint pushed to {args.out_repo}", flush=True)
if __name__ == "__main__": main()train_dmd.pyAdded+513