Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications You must be signed in to change notification settings

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

UnboundLocalError: tokenizer_one referenced before assignment in train_dreambooth_lora_sd3.py #8594

@C0nsumption

C0nsumption commented Jun 16, 2024

I encountered an issue when trying to run train_dreambooth_lora_sd3.py. The script throws an UnboundLocalError because tokenizer_one is referenced before it is assigned. This prevents the training process from starting.

Clone the repository.
Set up the environment as per the instructions.
Run the following command:

Expected Behavior:
The script should initialize the tokenizers and proceed with the training process without any errors.

Actual Behavior:
The script fails with the following error:

--instance_data_dir=$INSTANCE_DIR --output_dir=$OUTPUT_DIR --mixed_precision="fp16" --instance_prompt="a photo of sks dog" --resolution=1024 --train_batch_size=1 --gradient_accumulation_steps=4 --learning_rate=1e-5 --lr_scheduler="constant" --lr_warmup_steps=0 --max_train_steps=500 --seed="0" /workspace/diffusers/src/diffusers/models/transformers/transformer_2d.py:34: FutureWarning: `Transformer2DModelOutput` is deprecated and will be removed in version 1.0.0. Importing `Transformer2DModelOutput` from `diffusers.models.transformer_2d` is deprecated and this will be removed in a future version. Please use `from diffusers.models.modeling_outputs import Transformer2DModelOutput`, instead. deprecate("Transformer2DModelOutput", "1.0.0", deprecation_message) 06/16/2024 23:42:29 - INFO - __main__ - Distributed environment: NO Num processes: 1 Process index: 0 Local process index: 0 Device: cuda Mixed precision type: fp16 You set `add_prefix_space`. The tokenizer needs to be converted from the slow tokenizers You are using a model of type clip_text_model to instantiate a model of type . This is not supported for all configurations of models and can yield errors. You are using a model of type clip_text_model to instantiate a model of type . This is not supported for all configurations of models and can yield errors. You are using a model of type t5 to instantiate a model of type . This is not supported for all configurations of models and can yield errors. Loading checkpoint shards: 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 2/2 [00:15<00:00, 7.69s/it] Traceback (most recent call last): File "/workspace/diffusers/examples/dreambooth/train_dreambooth_lora_sd3.py", line 1686, in <module> main(args) File "/workspace/diffusers/examples/dreambooth/train_dreambooth_lora_sd3.py", line 1347, in main tokens_one = tokenize_prompt(tokenizer_one, args.instance_prompt) UnboundLocalError: local variable 'tokenizer_one' referenced before assignment Traceback (most recent call last): File "/workspace/venv/bin/accelerate", line 8, in <module> sys.exit(main()) File "/workspace/venv/lib/python3.10/site-packages/accelerate/commands/accelerate_cli.py", line 48, in main args.func(args) File "/workspace/venv/lib/python3.10/site-packages/accelerate/commands/launch.py", line 1097, in launch_command simple_launcher(args) File "/workspace/venv/lib/python3.10/site-packages/accelerate/commands/launch.py", line 703, in simple_launcher raise subprocess.CalledProcessError(returncode=process.returncode, cmd=cmd) subprocess.CalledProcessError: Command '['/workspace/venv/bin/python', 'train_dreambooth_lora_sd3.py', '--pretrained_model_name_or_path=models/stable-diffusion-3-medium-diffusers', '--instance_data_dir=dog', '--output_dir=trained-sd3', '--mixed_precision=fp16', '--instance_prompt=a photo of sks dog', '--resolution=1024', '--train_batch_size=1', '--gradient_accumulation_steps=4', '--learning_rate=1e-5', '--lr_scheduler=constant', '--lr_warmup_steps=0', '--max_train_steps=500', '--seed=0']' returned non-zero exit status 1.

@C0nsumption

xhinker commented Jun 17, 2024

the same error

Sorry, something went wrong.

@satani99

satani99 commented Jun 17, 2024

comment out line 1320
from to this

  • 👍 3 reactions
  • 👎 1 reaction
  • 🎉 1 reaction
  • ❤️ 1 reaction

@Forainest

Forainest commented Jun 20, 2024

same error

@sayakpaul

Successfully merging a pull request may close this issue.

@xhinker

码龄 粉丝数 原力等级 --

unboundlocalerror local variable 'width' referenced before assignment

报错:UnboundLocalError: local variable 'encoder_extended_attention_mask' referenced before assignment

报错:UnboundLocalError: local variable 'encoder_extended_attention_mask' referenced before assignment

unboundlocalerror local variable 'width' referenced before assignment

  • 编辑 收藏 删除 结题

¥ 0 (可追加 ¥500)

提供问题酬金的用户不参与问题酬金结算和分配

支付即为同意 《付费问题酬金结算规则》

1 条回答 默认 最新

unboundlocalerror local variable 'width' referenced before assignment

引自免费微信小程序: 皆我百晓生

从你提供的代码片段来看,错误信息“UnboundLocalError: local variable 'encoder_extended_attention_mask' referenced before assignment”意味着你在尝试引用一个尚未被赋值的局部变量 encoder_extended_attention_mask 。这个问题通常发生在条件语句中,即根据不同的条件分别给变量赋值,但如果没有满足任何条件,那么该变量将保持未定义状态。

在 invert_attention_mask 方法中,你有两段代码用于根据 encoder_attention_mask 的维度来扩展它,但是这两段代码是互斥的,只有当 encoder_attention_mask 的维度为2或3时才会执行其中一个。如果 encoder_attention_mask 的维度既不是2也不是3,那么 encoder_extended_attention_mask 将不会被初始化,从而导致之后的代码引用未定义的变量。

为了解决这个问题,你需要确保无论输入的维度如何, encoder_extended_attention_mask 都会被正确初始化。你可以在方法的开始处添加一个检查,以处理所有可能的维度情况,或者至少确保即使在非预期的维度下也能安全地初始化该变量。

下面是一个修改后的 invert_attention_mask 方法,它首先检查 encoder_attention_mask 的维度,并在不匹配的情况下抛出异常,确保了 encoder_extended_attention_mask 总是在后续操作前被正确初始化:

通过这种方式,我们确保了在调用 invert_attention_mask 方法时,不论输入的 encoder_attention_mask 具有何种维度, encoder_extended_attention_mask 都将被正确初始化并返回。这样可以避免由于变量未定义而引发的运行时错误。

unboundlocalerror local variable 'width' referenced before assignment

  • 没有解决我的问题, 去提问

unboundlocalerror local variable 'width' referenced before assignment

  • ¥15 关于#linux#的问题(输入输出错误):出现这个界面接着我重新装系统,又让修电脑的师傅帮我扫描硬盘(没有问题)用着用着又卡死(相关搜索:固态硬盘)
  • ¥15 cv::resize不同线程时间不同
  • ¥15 web课程,怎么做啊😭没好好听课 根本不知道怎么下手
  • ¥15 做一个关于单片机的比较难的代码,然后搞一个PPT进行解释
  • ¥15 python提取.csv文件中的链接会经常出现爬取失败
  • ¥15 数据结构中的数组地址问题
  • ¥15 maya的mel里,怎样先选择模型A,然后利用mel脚本自动选择有相同名字的模型B呢。
  • ¥15 Python题,根本不会啊
  • ¥15 会会信号与系统和python的来
  • ¥15 关于#python#的问题

【Python】成功解决python报错:UnboundLocalError: local variable ‘xxx‘ referenced before assignment

unboundlocalerror local variable 'width' referenced before assignment

成功解决python报错:UnboundLocalError: local variable ‘xxx’ referenced before assignment。在Python中, UnboundLocalError 是一种特定的 NameError ,它会在尝试引用一个还未被赋值的局部变量时发生。Python解释器需要知道变量的类型和作用域,因此,在局部作用域内引用一个未被赋值的变量时,就会抛出这个错误。

🧑 博主简介:现任阿里巴巴嵌入式技术专家,15年工作经验,深耕嵌入式+人工智能领域,精通嵌入式领域开发、技术管理、简历招聘面试。CSDN优质创作者,提供产品测评、学习辅导、简历面试辅导、毕设辅导、项目开发、C/C++/Java/Python/Linux/AI等方面的服务,如有需要请站内私信或者联系任意文章底部的的VX名片(ID: gylzbk )
💬 博主粉丝群介绍:① 群内高中生、本科生、研究生、博士生遍布,可互相学习,交流困惑。② 热榜top10的常客也在群里,也有数不清的万粉大佬,可以交流写作技巧,上榜经验,涨粉秘籍。③ 群内也有职场精英,大厂大佬,可交流技术、面试、找工作的经验。④ 进群免费赠送写作秘籍一份,助你由写作小白晋升为创作大佬。⑤ 进群赠送CSDN评论防封脚本,送真活跃粉丝,助你提升文章热度。有兴趣的加文末联系方式,备注自己的CSDN昵称,拉你进群,互相学习共同进步。

【Python】解决Python报错:

1. 什么是unboundlocalerror?, 2. 常见的场景和原因, 方法一:全局变量, 方法二:函数参数, 方法三:局部变量初始化, 方法四:结合条件语句.

在这里插入图片描述

在Python编程中, UnboundLocalError: local variable 'xxx' referenced before assignment 是一个常见的错误,尤其是在写函数时可能会遇到。这篇技术博客将详细介绍 UnboundLocalError ,为什么会发生,以及如何解决这个错误。

在Python中, UnboundLocalError 是一种特定的 NameError ,它会在尝试引用一个还未被赋值的局部变量时发生。Python解释器需要知道变量的类型和作用域,因此,在局部作用域内引用一个未被赋值的变量时,就会抛出这个错误。

这是一个简单的代码示例来说明这个错误:

运行以上代码会抛出以下错误:

在这个例子中,Python解释器看到 print(x) 时,寻找局部作用域中的变量 x ,但这个变量在局部作用域内尚未被赋值(虽然在后面有赋值,解释器是从上到下执行代码的)。

理解错误的原因后,可以通过以下几种方式来解决 UnboundLocalError :

如果变量希望在函数内和函数外都使用,可以将其声明为全局变量:

通过在函数内使用 global 关键字,将 x 声明为全局变量,这样即使在函数内也能访问全局变量 x 。

通过将变量作为参数传递给函数,使得函数内可以访问并使用这个变量:

在这种情况下, x 是函数 my_function 的一个参数,无需在函数内部声明。

在使用变量之前,先初始化该局部变量:

确保在函数内部引用变量之前,该变量已经被赋值。

在复杂的逻辑中,特别是在涉及条件语句时,可以先在函数开始部分初始化变量,确保无论哪条路径都可以正确访问该变量:

在这个例子中,我们确保了变量 x 在函数内部任何地方都能被适当地引用。

  • 命名冲突 :在全局变量和局部变量重名情况下,优先使用局部变量。如果不小心混用,容易引发错误。
  • 提前规划变量作用域 :代码设计时,可以提前规划好变量应该属于哪个作用域,以减少变量冲突和未定义变量的情况。

UnboundLocalError: local variable 'xxx' referenced before assignment 错误是一个常见的初学者错误,但只要理解了Python的变量作用域规则和执行顺序,就可以轻松避开。通过合适的解决方法,如使用全局变量、函数参数、局部变量初始化或结合条件语句,可以高效且清晰地管理变量的使用。

希望这篇文章能帮助你理解和解决这个错误。如果有任何问题或其他建议,欢迎在评论中与我们讨论。Happy coding!

unboundlocalerror local variable 'width' referenced before assignment

“相关推荐”对你有帮助么?

unboundlocalerror local variable 'width' referenced before assignment

请填写红包祝福语或标题

unboundlocalerror local variable 'width' referenced before assignment

你的鼓励将是我创作的最大动力

unboundlocalerror local variable 'width' referenced before assignment

您的余额不足,请更换扫码支付或 充值

unboundlocalerror local variable 'width' referenced before assignment

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。 2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

unboundlocalerror local variable 'width' referenced before assignment

  • Stack Overflow Public questions & answers
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Talent Build your employer brand
  • Advertising Reach developers & technologists worldwide
  • Labs The future of collective knowledge sharing
  • About the company

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

UnboundLocalError: local variable 'L' referenced before assignment Python [duplicate]

when trying to compile the code below I get this error

Can someone explain why ? Isn't a global variable assigned before anything else?

My Python version is 2.7.3

Martijn Pieters's user avatar

  • 1 Note that UnboundLocalError is a run-time exception, not a compiler exception. –  Martijn Pieters ♦ Commented Jan 30, 2014 at 12:43

3 Answers 3

The minimal code to reproduce your bug is

This is happening for a number of reasons

  • First - because in python we have mutable and immutable classes. Ints are immutable, that is when you write x+=1 you actually create another object (which is not true for certain ints due to optimisations CPython does). What actually happens is x = x + 1.
  • Second - because python compiler checks every assignment made inside a scope and makes every variable assigned inside that scope local to it.
  • So as you see when you try to increment x compiler has to access a variable that's local to that scope, but was never assigned a value before.

If you're using python2 - you only have the option to declare variable global . But this way you would be unable to get a variable from an in-between function like

In python3 you have nonlocal keyword to address this situation.

Also I would advise you to avoid using globals. Also there is a collection.Counter class that might be useful to you.

Further reading: python docs

Kirill Zaitsev's user avatar

Isn't a global variable assigned before anything else?

Yes, but that's completely irrelevant. The compiler sees an assignment within the function and marks the name as being in the local scope. You need to use the global keyword at the beginning of the function to tell the compiler that the name should be in the global scope instead.

Ignacio Vazquez-Abrams's user avatar

  • Or, better, redesign to not use a global variable at all, since it's a really terrible design. –  Wooble Commented Jan 30, 2014 at 12:42

You are mixing tabs and spaces; don't do that.

Run your script with python -tt yourscript.py and fix all errors that finds.

Then configure your editor to stick to only spaces for indentation; using 4 spaces per indent is the recommended style by the Python Style Guide .

Next, you are trying to increment the global L here:

without declaring it a global. Add global L in that function. Assignment to a name inside a function marks such a name as a local, unless you specifically tell Python it is not.

  • @Wooble: Yup, you are correct; I missed the L+=1 in the function there. The indentation in the post was terrible and there were actual tabs on the later lines with L and a for loop. –  Martijn Pieters ♦ Commented Jan 30, 2014 at 12:42
  • Thank you for that. I fixed 2 mistakes but didn't solve my problem. –  lvi Commented Jan 30, 2014 at 12:42

Not the answer you're looking for? Browse other questions tagged python python-2.7 or ask your own question .

  • Featured on Meta
  • Upcoming sign-up experiments related to tags
  • The 2024 Developer Survey Is Live
  • Policy: Generative AI (e.g., ChatGPT) is banned
  • The return of Staging Ground to Stack Overflow

Hot Network Questions

  • Is it a "shifting of the burden of proof" if I show evidence in favor of a position, and ask the audience to debate that evidence if they disagree?
  • How can I have two plots progress on different rates of time?
  • Split Flaps and lift?
  • Comparing strings using LaTeX3
  • How to numerically solve noisy ODE
  • In "Romeo and Juliet", why is Juliet the "sun"?
  • "comfortable", but in the conceptual sense
  • Am I wasting my time self-studying program pre-requisites?
  • Horror movie that has a demon hand coming through a mirror
  • How would wyrms develop culture, houses, etc?
  • How should I interpret the impedance of an SMA connector?
  • Should I replace my three-prong dryer outlet with a four-prong outlet since I have a ground wire?
  • How should I end a campaign only the passive players are enjoying?
  • In Matthew 27:46, was Jesus fulfilling, quoting and/or citing Psalm 22?
  • Why focus on T gates and not some other single qubit rotation R making Clifford + R universal?
  • John, in his spaceship traveling at relativistic speed, is crossing the Milky Way in 500 years. How many supernovae explosions would he experience?
  • I'm a web developer but I am being asked to automate testing in Selenium
  • Chain slipping in 8th gear only
  • What the difference between View Distance and Ray Length?
  • Investigating a Fallen Tree: Cause and Prevention
  • Structure of a single automorphism of a finite abelian p-group
  • Can my grant pay for a conference marginally related to award?
  • Setup for proving equation 3.4 from Grinold
  • Is that a period or sentence

unboundlocalerror local variable 'width' referenced before assignment

  • Python Basics
  • Interview Questions
  • Python Quiz
  • Popular Packages
  • Python Projects
  • Practice Python
  • AI With Python
  • Learn Python3
  • Python Automation
  • Python Web Dev
  • DSA with Python
  • Python OOPs
  • Dictionaries
  • How to Fix - UnboundLocalError: Local variable Referenced Before Assignment in Python
  • UnboundLocalError Local variable Referenced Before Assignment in Python
  • How to use Pickle to save and load Variables in Python?
  • How to Use a Variable from Another Function in Python
  • How to fix Unresolved reference issue in PyCharm
  • Unused variable in for loop in Python
  • How to Access Dictionary Values in Python Using For Loop
  • Python | Accessing variable value from code scope
  • How to fix "SyntaxError: invalid character" in Python
  • Assign Function to a Variable in Python
  • How to Reference Elements in an Array in Python
  • How to Fix: SyntaxError: positional argument follows keyword argument in Python
  • How To Fix Valueerror Exceptions In Python
  • How To Fix - Python RuntimeWarning: overflow encountered in scalar
  • Different Forms of Assignment Statements in Python
  • Unused local variable in Python
  • Access environment variable values in Python
  • How to fix "ValueError: invalid literal for int() with base 10" in Python
  • How to import variables from another file in Python?
  • JavaScript ReferenceError - Can't access lexical declaration`variable' before initialization

How to Fix – UnboundLocalError: Local variable Referenced Before Assignment in Python

Developers often encounter the  UnboundLocalError Local Variable Referenced Before Assignment error in Python. In this article, we will see what is local variable referenced before assignment error in Python and how to fix it by using different approaches.

What is UnboundLocalError: Local variable Referenced Before Assignment?

This error occurs when a local variable is referenced before it has been assigned a value within a function or method. This error typically surfaces when utilizing try-except blocks to handle exceptions, creating a puzzle for developers trying to comprehend its origins and find a solution.

Below, are the reasons by which UnboundLocalError: Local variable Referenced Before Assignment error occurs in  Python :

Nested Function Variable Access

Global variable modification.

In this code, the outer_function defines a variable ‘x’ and a nested inner_function attempts to access it, but encounters an UnboundLocalError due to a local ‘x’ being defined later in the inner_function.

In this code, the function example_function tries to increment the global variable ‘x’, but encounters an UnboundLocalError since it’s treated as a local variable due to the assignment operation within the function.

Solution for Local variable Referenced Before Assignment in Python

Below, are the approaches to solve “Local variable Referenced Before Assignment”.

In this code, example_function successfully modifies the global variable ‘x’ by declaring it as global within the function, incrementing its value by 1, and then printing the updated value.

In this code, the outer_function defines a local variable ‘x’, and the inner_function accesses and modifies it as a nonlocal variable, allowing changes to the outer function’s scope from within the inner function.

Please Login to comment...

Similar reads.

  • Python Errors
  • Python How-to-fix
  • Python Programs

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

COMMENTS

  1. UnboundLocalError: tokenizer_one referenced before assignment ...

    UnboundLocalError: tokenizer_one referenced before assignment in train_dreambooth_lora_sd3.py #8594 Open C0nsumption opened this issue Jun 16, 2024 · 2 comments · May be fixed by #8600

  2. Oracle Linux: DNF Commands Report "UnboundLocalError: local ...

    Linux OS - Version Oracle Linux 8.0 and later: Oracle Linux: DNF Commands Report "UnboundLocalError: local variable 'response' referenced before assignment" Error

  3. 报错:UnboundLocalError: local variable 'encoder_extended ...

    从你提供的代码片段来看,错误信息“UnboundLocalError: local variable 'encoder_extended_attention_mask' referenced before assignment”意味着你在尝试引用一个尚未被赋值的局部变量encoder_extended_attention_mask。这个问题通常发生在条件语句中,即根据不同的条件分别给变量赋值,但 ...

  4. 【Python】成功解决python报错:UnboundLocalError: local variable ‘xxx...

    运行以上代码会抛出以下错误:. UnboundLocalError: local variable 'x' referenced before assignment. 1. 在这个例子中,Python解释器看到 print(x) 时,寻找局部作用域中的变量 x ,但这个变量在局部作用域内尚未被赋值(虽然在后面有赋值,解释器是从上到下执行代码的)。. 3 ...

  5. Python 3: UnboundLocalError: local variable referenced before ...

    UnboundLocalError: local variable 'f' referenced before assignment. Python sees the f is used as a local variable in [f for f in [1, 2, 3]], and decides that it is also a local variable in f(3). You could add a global f statement: def f(x): return x.

  6. UnboundLocalError: local variable ... referenced before ...

    1. make sure that the variable is initialized in every code path (in your case: including the else case) 2. initialize the variable to some reasonable default value at the beginning 3. return from the function in the code paths which cannot provide a value for the variable.

  7. python - UnboundLocalError: local variable referenced before ...

    In the function the variable rev_get_event is local to the scope of the function. If you mean the global variable the function should explicitly declare it, for example as follows: global rev_get_event. def Get_event(username, password, eventID): global rev_get_event. try:

  8. Unbound local error: ("local variable referenced before ...

    Another way to write this, using vectorized string methods is: import pandas as pd. import numpy as np. nan = np.nan. df = pd.DataFrame([{'Cabin': 'F G13'}, {'Cabin': 'A32 A45'}, {'Cabin': 'F23 F36'}, {'Cabin': 'B24'}, {'Cabin': nan}])

  9. UnboundLocalError: local variable 'L' referenced before ...">UnboundLocalError: local variable 'L' referenced before ...

    The compiler sees an assignment within the function and marks the name as being in the local scope. You need to use the global keyword at the beginning of the function to tell the compiler that the name should be in the global scope instead.

  10. UnboundLocalError: Local variable Referenced ...">How to Fix - UnboundLocalError: Local variable Referenced ...

    Developers often encounter the UnboundLocalError Local Variable Referenced Before Assignment error in Python. In this article, we will see what is local variable referenced before assignment error in Python and how to fix it by using different approaches.