Skip to content

[BUG]ValueError: Tried to launch on distributed with multinode, but MASTER_ADDR env was not set #2266

Closed as not planned

Description

@chuangzhidan

i guess it has something to do with the env,mainly changed model and dataset path for this colab script case.

Describe the bug
Dataset({
features: ['image', 'text'],
num_rows: 68686
})
<PIL.PngImagePlugin.PngImageFile image mode=RGB size=320x50 at 0x7F728C1079D0>
H ^ { \prime } = \beta N \int d \lambda \biggl { \frac { 1 } { 2 \beta ^ { 2 } N ^ { 2 } } \partial _ { \lambda } \zeta ^ { \dagger } \partial _ { \lambda } \zeta + V ( \lambda ) \zeta ^ { \dagger } \zeta \biggr } \ .
<IPython.core.display.Math object>
{'messages': [{'role': 'user', 'content': [{'type': 'text', 'text': 'Write the LaTeX representation for this image.'}, {'type': 'image', 'image': <PIL.PngImagePlugin.PngImageFile image mode=RGB size=160x40 at 0x7F724814FB90>}]}, {'role': 'assistant', 'content': [{'type': 'text', 'text': '{ \frac { N } { M } } \in { \bf Z } , { \frac { M } { P } } \in { \bf Z } , { \frac { P } { Q } } \in { \bf Z }'}]}]}
$$\mathrm { ~ n a ~ }$$&lt;|im_end|>
Unsloth: Model does not have a default image size - using 512
Traceback (most recent call last):
File "/data/scripts/Qwen2_VL_(7B)-Vision_OCR copy.py", line 121, in
args = SFTConfig(
^^^^^^^^^^
File "/media/data/xgp/scripts/unsloth_compiled_cache/UnslothSFTTrainer.py", line 254, in init
super().init(
File "", line 146, in init
File "/home/ubuntu/.conda/envs/unsloth_env/lib/python3.11/site-packages/trl/trainer/sft_config.py", line 145, in post_init
super().post_init()
File "/home/ubuntu/.conda/envs/unsloth_env/lib/python3.11/site-packages/transformers/training_args.py", line 1808, in post_init
self.device
File "/home/ubuntu/.conda/envs/unsloth_env/lib/python3.11/site-packages/transformers/training_args.py", line 2344, in device
return self._setup_devices
^^^^^^^^^^^^^^^^^^^
File "/home/ubuntu/.conda/envs/unsloth_env/lib/python3.11/site-packages/transformers/utils/generic.py", line 62, in get
cached = self.fget(obj)
^^^^^^^^^^^^^^
**File "/home/ubuntu/.conda/envs/unsloth_env/lib/python3.11/site-packages/transformers/training_args.py", line 2271, in _setup_devices
self.distributed_state = PartialState(accelerator_state_kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/ubuntu/.conda/envs/unsloth_env/lib/python3.11/site-packages/accelerate/state.py", line 242, in init
raise ValueError(
ValueError: Tried to launch on distributed with multinode, but MASTER_ADDR env was not set, please try exporting rank 0's hostname as MASTER_ADDR

  1. Environment Setup:

    • OS: [e.g., Ubuntu 20.04]
    • Python Version: 3.11.11
    • Frameworks/Libraries:
    • accelerate==1.5.2
      aiohappyeyeballs==2.6.1
      aiohttp==3.11.14
      aiosignal==1.3.2
      airportsdata==20250224
      annotated-types==0.7.0
      anyio==4.9.0
      astor==0.8.1
      asttokens==3.0.0
      attrs==25.3.0
      bitsandbytes==0.45.4
      blake3==1.0.4
      cachetools==5.5.2
      certifi==2025.1.31
      charset-normalizer==3.4.1
      click==8.1.8
      cloudpickle==3.1.1
      compressed-tensors==0.9.2
      cupy-cuda12x==13.4.1
      cut-cross-entropy==25.1.1
      datasets==3.4.1
      decorator==5.2.1
      depyf==0.18.0
      diffusers==0.32.2
      dill==0.3.8
      diskcache==5.6.3
      distro==1.9.0
      dnspython==2.7.0
      docker-pycreds==0.4.0
      docstring_parser==0.16
      einops==0.8.1
      email_validator==2.2.0
      executing==2.2.0
      fastapi==0.115.12
      fastapi-cli==0.0.7
      fastrlock==0.8.3
      filelock==3.18.0
      frozenlist==1.5.0
      fsspec==2024.12.0
      gguf==0.10.0
      gitdb==4.0.12
      GitPython==3.1.44
      gmpy2 @ file:///croot/gmpy2_1738085463648/work
      h11==0.14.0
      hf_transfer==0.1.9
      httpcore==1.0.7
      httptools==0.6.4
      httpx==0.28.1
      huggingface-hub==0.29.3
      idna==3.10
      importlib_metadata==8.6.1
      interegular==0.3.3
      ipython==9.0.2
      ipython_pygments_lexers==1.1.1
      jedi==0.19.2
      Jinja2 @ file:///croot/jinja2_1741710844255/work
      jiter==0.9.0
      jsonschema==4.23.0
      jsonschema-specifications==2024.10.1
      lark==1.2.2
      llguidance==0.7.10
      llvmlite==0.43.0
      lm-format-enforcer==0.10.11
      markdown-it-py==3.0.0
      MarkupSafe @ file:///croot/markupsafe_1738584038848/work
      matplotlib-inline==0.1.7
      mdurl==0.1.2
      mistral_common==1.5.4
      mpmath @ file:///croot/mpmath_1690848262763/work
      msgpack==1.1.0
      msgspec==0.19.0
      multidict==6.2.0
      multiprocess==0.70.16
      nest-asyncio==1.6.0
      networkx @ file:///croot/networkx_1737039604450/work
      ninja==1.11.1.4
      numba==0.60.0
      numpy==1.26.4
      nvidia-cublas-cu12==12.4.5.8
      nvidia-cuda-cupti-cu12==12.4.127
      nvidia-cuda-nvrtc-cu12==12.4.127
      nvidia-cuda-runtime-cu12==12.4.127
      nvidia-cudnn-cu12==9.1.0.70
      nvidia-cufft-cu12==11.2.1.3
      nvidia-curand-cu12==10.3.5.147
      nvidia-cusolver-cu12==11.6.1.9
      nvidia-cusparse-cu12==12.3.1.170
      nvidia-cusparselt-cu12==0.6.2
      nvidia-nccl-cu12==2.21.5
      nvidia-nvjitlink-cu12==12.4.127
      nvidia-nvtx-cu12==12.4.127
      openai==1.68.2
      opencv-python-headless==4.11.0.86
      outlines==0.1.11
      outlines_core==0.1.26
      packaging==24.2
      pandas==2.2.3
      parso==0.8.4
      partial-json-parser==0.2.1.1.post5
      peft==0.15.0
      pexpect==4.9.0
      pillow==11.1.0
      platformdirs==4.3.7
      prometheus-fastapi-instrumentator==7.1.0
      prometheus_client==0.21.1
      prompt_toolkit==3.0.50
      propcache==0.3.1
      protobuf==3.20.3
      psutil==7.0.0
      ptyprocess==0.7.0
      pure_eval==0.2.3
      py-cpuinfo==9.0.0
      pyarrow==19.0.1
      pycountry==24.6.1
      pydantic==2.10.6
      pydantic_core==2.27.2
      Pygments==2.19.1
      python-dateutil==2.9.0.post0
      python-dotenv==1.1.0
      python-json-logger==3.3.0
      python-multipart==0.0.20
      pytz==2025.2
      PyYAML @ file:///croot/pyyaml_1728657952215/work
      pyzmq==26.3.0
      ray==2.44.0
      referencing==0.36.2
      regex==2024.11.6
      requests==2.32.3
      rich==13.9.4
      rich-toolkit==0.14.0
      rpds-py==0.24.0
      safetensors==0.5.3
      scipy==1.15.2
      sentencepiece==0.2.0
      sentry-sdk==2.24.1
      setproctitle==1.3.5
      shellingham==1.5.4
      shtab==1.7.1
      six==1.17.0
      smmap==5.0.2
      sniffio==1.3.1
      stack-data==0.6.3
      starlette==0.46.1
      sympy==1.13.1
      tiktoken==0.9.0
      tokenizers==0.21.1
      torch==2.6.0
      torchaudio==2.6.0
      torchvision==0.21.0
      tqdm==4.67.1
      traitlets==5.14.3
      transformers==4.50.1
      triton==3.2.0
      trl==0.15.2
      typeguard==4.4.2
      typer==0.15.2
      typing_extensions @ file:///croot/typing_extensions_1734714854207/work
      tyro==0.9.17
      tzdata==2025.2
      unsloth==2025.3.19
      unsloth_zoo==2025.3.17
      urllib3==2.3.0
      uvicorn==0.34.0
      uvloop==0.21.0
      vllm==0.8.2
      wandb==0.19.8
      watchfiles==1.0.4
      wcwidth==0.2.13
      websockets==15.0.1
      xformers==0.0.29.post2
      xgrammar==0.1.16
      xxhash==3.5.0
      yarl==1.18.3
      zipp==3.21.0
      **- colab / script - yes
  2. Dataset Details:

    • Dataset Name: unsloth/LaTeX_OCR
  3. Model Details:

    • Model ID:Qwen2-VL-7B-Instruct
    • Model Configuration: lora
  4. Training Configuration:

    • Trainer Args: SFTConfig**
  5. Reproduction Steps:

import os
from unsloth import FastVisionModel
import torch
import wandb
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "3"
os.environ["GRADIO_SHARE"]="3"
os.environ["WORLD_SIZE"] = "3"
os.environ["WANDB_API_KEY"] = "029a79963·········662e2de9a9"
os.environ["WANDB_PROJECT"] = "qwen2.5_7b_vl_ocr"
wandb.init()

model, tokenizer = FastVisionModel.from_pretrained(
"/data2/models/unsloth/Qwen2-VL-7B-Instruct", # unsloth/Qwen2-VL-7B-Instruct
load_in_4bit = True,
use_gradient_checkpointing = "unsloth", # True or "unsloth" for long context
)

model = FastVisionModel.get_peft_model(
model,
finetune_vision_layers = True, # False if not finetuning vision layers
finetune_language_layers = True, # False if not finetuning language layers
finetune_attention_modules = True, # False if not finetuning attention layers
finetune_mlp_modules = True, # False if not finetuning MLP layers

r = 16,           # The larger, the higher the accuracy, but might overfit
lora_alpha = 16,  # Recommended alpha == r at least
lora_dropout = 0,
bias = "none",
random_state = 3407,
use_rslora = False,  # We support rank stabilized LoRA
loftq_config = None, # And LoftQ
# target_modules = "all-linear", # Optional now! Can specify a list if needed

)

from datasets import load_dataset
dataset = load_dataset("/data/llm/dataset/LaTeX_OCR", split = "train")

dataset = load_dataset("unsloth/LaTeX_OCR", split = "train")

print(dataset)
print(dataset[2]["image"])
print(dataset[2]["text"])

from IPython.display import display, Math, Latex
latex = dataset[2]["text"]
display(Math(latex))

instruction = "Write the LaTeX representation for this image."

def convert_to_conversation(sample):
conversation = [
{ "role": "user",
"content" : [
{"type" : "text", "text" : instruction},
{"type" : "image", "image" : sample["image"]} ]
},
{ "role" : "assistant",
"content" : [
{"type" : "text", "text" : sample["text"]} ]
},
]
return { "messages" : conversation }
pass
converted_dataset = [convert_to_conversation(sample) for sample in dataset]
print(converted_dataset[0])

FastVisionModel.for_inference(model) # Enable for inference!

image = dataset[2]["image"]
instruction = "Write the LaTeX representation for this image."

messages = [
{"role": "user", "content": [
{"type": "image"},
{"type": "text", "text": instruction}
]}
]
input_text = tokenizer.apply_chat_template(messages, add_generation_prompt = True)
inputs = tokenizer(
image,
input_text,
add_special_tokens = False,
return_tensors = "pt",
).to("cuda")

from transformers import TextStreamer
text_streamer = TextStreamer(tokenizer, skip_prompt = True)
_ = model.generate(**inputs, streamer = text_streamer, max_new_tokens = 128, use_cache = True, temperature = 1.5, min_p = 0.1)

from unsloth import is_bf16_supported
from unsloth.trainer import UnslothVisionDataCollator
from trl import SFTTrainer, SFTConfig

FastVisionModel.for_training(model) # Enable for training!

trainer = SFTTrainer(
model = model,
tokenizer = tokenizer,
data_collator = UnslothVisionDataCollator(model, tokenizer), # Must use!
train_dataset = converted_dataset,
args = SFTConfig(
per_device_train_batch_size = 2,
gradient_accumulation_steps = 4,
warmup_steps = 5,
max_steps = 300,
# num_train_epochs = 1, # Set this instead of max_steps for full training runs
learning_rate = 2e-4,
fp16 = not is_bf16_supported(),
bf16 = is_bf16_supported(),
logging_steps = 1,
optim = "adamw_8bit",
weight_decay = 0.01,
lr_scheduler_type = "linear",
seed = 3407,
output_dir = "outputs",
report_to = "wandb", # For Weights and Biases none

    # You MUST put the below items for vision finetuning:
    remove_unused_columns = False,
    dataset_text_field = "",
    dataset_kwargs = {"skip_prepare_dataset": True},
    dataset_num_proc = 4,
    max_seq_length = 2048,
),

)

@title Show current memory stats

gpu_stats = torch.cuda.get_device_properties(0)
start_gpu_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)
print(f"GPU = {gpu_stats.name}. Max memory = {max_memory} GB.")
print(f"{start_gpu_memory} GB of memory reserved.")

trainer_stats = trainer.train()

@title Show final memory and time stats

used_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
used_memory_for_lora = round(used_memory - start_gpu_memory, 3)
used_percentage = round(used_memory / max_memory * 100, 3)
lora_percentage = round(used_memory_for_lora / max_memory * 100, 3)
print(f"{trainer_stats.metrics['train_runtime']} seconds used for training.")
print(f"{round(trainer_stats.metrics['train_runtime']/60, 2)} minutes used for training.")
print(f"Peak reserved memory = {used_memory} GB.")
print(f"Peak reserved memory for training = {used_memory_for_lora} GB.")
print(f"Peak reserved memory % of max memory = {used_percentage} %.")
print(f"Peak reserved memory for training % of max memory = {lora_percentage} %.")

FastVisionModel.for_inference(model) # Enable for inference!

image = dataset[2]["image"]
instruction = "Write the LaTeX representation for this image."

messages = [
{"role": "user", "content": [
{"type": "image"},
{"type": "text", "text": instruction}
]}
]
input_text = tokenizer.apply_chat_template(messages, add_generation_prompt = True)
inputs = tokenizer(
image,
input_text,
add_special_tokens = False,
return_tensors = "pt",
).to("cuda")

from transformers import TextStreamer
text_streamer = TextStreamer(tokenizer, skip_prompt = True)
_ = model.generate(**inputs, streamer = text_streamer, max_new_tokens = 128,
use_cache = True, temperature = 1.5, min_p = 0.1)

model.save_pretrained("lora_model") # Local saving
tokenizer.save_pretrained("lora_model")

model.push_to_hub("your_name/lora_model", token = "...") # Online saving

tokenizer.push_to_hub("your_name/lora_model", token = "...") # Online saving

if False:
from unsloth import FastVisionModel
model, tokenizer = FastVisionModel.from_pretrained(
model_name = "lora_model", # YOUR MODEL YOU USED FOR TRAINING
load_in_4bit = True, # Set to False for 16bit LoRA
)
FastVisionModel.for_inference(model) # Enable for inference!

image = dataset[0]["image"]
instruction = "Write the LaTeX representation for this image."

messages = [
{"role": "user", "content": [
{"type": "image"},
{"type": "text", "text": instruction}
]}
]
input_text = tokenizer.apply_chat_template(messages, add_generation_prompt = True)
inputs = tokenizer(
image,
input_text,
add_special_tokens = False,
return_tensors = "pt",
).to("cuda")

from transformers import TextStreamer
text_streamer = TextStreamer(tokenizer, skip_prompt = True)
_ = model.generate(**inputs, streamer = text_streamer, max_new_tokens = 128,
use_cache = True, temperature = 1.5, min_p = 0.1)

Select ONLY 1 to save! (Both not needed!)

Save locally to 16bit

if False: model.save_pretrained_merged("unsloth_finetune", tokenizer,)

To export and save to your Hugging Face account

if False: model.push_to_hub_merged("YOUR_USERNAME/unsloth_finetune", tokenizer, token = "PUT_HERE")

Activity

  1. self-assigned this
    on Oct 8, 2026
  2. danielhanchen commented on Oct 8, 2026

    @danielhanchen
    Member

    Sorry on the delay! This error is not coming from Unsloth, it is caused by os.environ["WORLD_SIZE"] = "3" in the script.

    WORLD_SIZE tells Accelerate that this process is one of 3 distributed workers. When a script is run with plain python (no torchrun / accelerate launch), there is no LOCAL_RANK or MASTER_ADDR, so older Accelerate versions (1.12.0 and below, you had 1.5.2) fall into the multi node CPU path and raise exactly this MASTER_ADDR error inside TrainingArguments. It reproduces with plain transformers.TrainingArguments and no Unsloth import at all.

    To fix it:

    1. Remove os.environ["WORLD_SIZE"] = "3". With CUDA_VISIBLE_DEVICES = "3" only one GPU is visible anyway, so this is a single GPU run.
    2. Set CUDA_VISIBLE_DEVICES (and CUDA_DEVICE_ORDER) at the very top of the script, before from unsloth import FastVisionModel, so it applies before CUDA is initialized.
    3. For multi GPU training, do not set WORLD_SIZE by hand. Launch with torchrun --nproc_per_node 3 script.py or accelerate launch, which set RANK, LOCAL_RANK, WORLD_SIZE and MASTER_ADDR for you.

    Accelerate 1.13.0 and newer no longer raise here for a single process run, so uv pip install --upgrade accelerate also avoids the error, but removing the WORLD_SIZE line is the real fix.

    Closing since this is a configuration issue, but feel free to reopen if it still happens without that line.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions