运行Huggingface Diffuser教程时遇NameError错误求助
问题:Huggingface Diffusers训练时触发NameError: name '{myusername}' is not defined
我在学习Huggingface Diffusers基础训练教程时,运行训练代码出现以下错误:
╭─────────────────────────────── Traceback (most recent call last) ────────────────────────────────╮ │ in <cell line: 5>:5 │ │ │ │ /usr/local/lib/python3.10/dist-packages/accelerate/launchers.py:103 in notebook_launcher │ │ │ │ 100 │ │ │ print("Launching training on one GPU.") │ │ 101 │ │ else: │ │ 102 │ │ │ print("Launching training on one CPU.") │ │ ❱ 103 │ │ function(*args) │ │ 104 │ else: │ │ 105 │ │ if num_processes is None: │ │ 106 │ │ │ raise ValueError( │ │ in train_loop:28 │ │ in get_full_repo_name:13 │ ╰──────────────────────────────────────────────────────────────────────────────────────────────────╯ NameError: name '{myusername}' is not defined
我尝试在代码中插入个人用户名但未解决,相关代码如下:
from huggingface_hub import HfFolder, Repository, whoami from tqdm.auto import tqdm from pathlib import Path import os def get_full_repo_name(model_id: str, organization: str = None, token: str = None): if token is None: token = HfFolder.get_token() if organization is None: username = whoami(token)["name"] return f"{username}/{model_id}" else: return f"{organization}/{model_id}" def train_loop(config, model, noise_scheduler, optimizer, train_dataloader, lr_scheduler): # Initialize accelerator and tensorboard logging accelerator = Accelerator( mixed_precision=config.mixed_precision, gradient_accumulation_steps=config.gradient_accumulation_steps, log_with="tensorboard", logging_dir=os.path.join(config.output_dir, "logs"), ) if accelerator.is_main_process: if config.push_to_hub: repo_name = get_full_repo_name(Path(config.output_dir).name) repo = Repository(config.output_dir, clone_from=repo_name) elif config.output_dir is not None: os.makedirs(config.output_dir, exist_ok=True) accelerator.init_trackers("train_example") # Prepare everything # There is no specific order to remember, you just need to unpack the # objects in the same order you gave them to the prepare method. model, optimizer, train_dataloader, lr_scheduler = accelerator.prepare( model, optimizer, train_dataloader, lr_scheduler ) global_step = 0 # Now you train the model for epoch in range(config.num_epochs): progress_bar = tqdm(total=len(train_dataloader), disable=not accelerator.is_local_main_process) progress_bar.set_description(f"Epoch {epoch}") for step, batch in enumerate(train_dataloader): clean_images = batch["images"] # Sample noise to add to the images noise = torch.randn(clean_images.shape).to(clean_images.device) bs = clean_images.shape[0] # Sample a random timestep for each image timesteps = torch.randint( 0, noise_scheduler.config.num_train_timesteps, (bs,), device=clean_images.device ).long() # Add noise to the clean images according to the noise magnitude at each timestep # (this is the forward diffusion process) noisy_images = noise_scheduler.add_noise(clean_images, noise, timesteps) with accelerator.accumulate(model): # Predict the noise residual noise_pred = model(noisy_images, timesteps, return_dict=False)[0] loss = F.mse_loss(noise_pred, noise) accelerator.backward(loss) accelerator.clip_grad_norm_(model.parameters(), 1.0) optimizer.step() lr_scheduler.step() optimizer.zero_grad() progress_bar.update(1) logs = {"loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0], "step": global_step} progress_bar.set_postfix(**logs) accelerator.log(logs, step=global_step) global_step += 1 # After each epoch you optionally sample some demo images with evaluate() and save the model if accelerator.is_main_process: pipeline = DDPMPipeline(unet=accelerator.unwrap_model(model), scheduler=noise_scheduler) if (epoch + 1) % config.save_image_epochs == 0 or epoch == config.num_epochs - 1: evaluate(config, epoch, pipeline) if (epoch + 1) % config.save_model_epochs == 0 or epoch == config.num_epochs - 1: if config.push_to_hub: repo.push_to_hub(commit_message=f"Epoch {epoch}", blocking=True) else: pipeline.save_pretrained(config.output_dir)
解决方案
这个错误是因为whoami(token)["name"]无法正确获取你的Hugging Face用户名,或者你未完成Hub登录,以下是三种解决方式:
1. 手动指定用户名(最直接)
修改get_full_repo_name函数,直接替换为你的Hugging Face用户名,跳过自动获取逻辑:
def get_full_repo_name(model_id: str, organization: str = None, token: str = None): # 替换成你的Hugging Face用户名 username = "你的HF用户名" if organization is None: return f"{username}/{model_id}" else: return f"{organization}/{model_id}"
2. 完成Hugging Face Hub登录
如果想保留自动获取逻辑,需要确保已登录Hub:
- 命令行登录:
huggingface-cli login
- 或者在代码中手动传入token:
from huggingface_hub import login login(token="你的HF访问令牌")
登录后whoami(token)就能正确返回用户名信息。
3. 关闭推送到Hub的功能
如果暂时不需要将模型推送到Hub,可将config.push_to_hub设置为False,这样代码会跳过get_full_repo_name的调用,直接本地保存模型。
内容的提问来源于stack exchange,提问作者Gamma1
相关产品推荐
相关产品推荐

