Why am I getting this message after running this code?
Code:
code
#!/usr/bin/env python3
"""
Full training script with low-memory loading and offload for DeepSeek model + LoRA adapters.
"""
import os
import json
import random
import numpy as np
import pandas as pd
import torch
from datasets import Dataset
from transformers import (
AutoTokenizer,
AutoModelForCausalLM,
BitsAndBytesConfig,
TrainingArguments,
Trainer,
DataCollatorForLanguageModeling
)
from peft import prepare_model_for_kbit_training, LoraConfig, get_peft_model
# ------------- Reproducibility Setup -------------
SEED = 42
random.seed(SEED)
np.random.seed(SEED)
torch.manual_seed(SEED)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(SEED)
# -----------------------------
# Step 1: Load and preprocess data
# -----------------------------
with open("balanced_labeled_conversations.json", "r") as f:
data = json.load(f)
df = pd.DataFrame(data)
traits = ["witty", "sarcastic", "charming"]
df = df[df['trait'].isin(traits)].dropna(subset=["dialogue"])
def format_conversation_with_expert_token(row):
token = f"[EXPERT: {row['trait'].upper()}]"
return f"{token} <|user|> {row['dialogue']}\n<|assistant|>"
df["text"] = df.apply(format_conversation_with_expert_token, axis=1)
# Sample 10% for quick iteration
df = df.sample(frac=0.1, random_state=SEED).reset_index(drop=True)
print(f"Using {len(df)} examples ({len(df)/len(data):.0%} of original)")
# -----------------------------
# Step 2: Tokenization and special token addition
# -----------------------------
model_checkpoint = "deepseek-ai/deepseek-moe-16b-base"
tokenizer = AutoTokenizer.from_pretrained(model_checkpoint, trust_remote_code=True)
# Add expert tokens
special_tokens = [f"[EXPERT: {t.upper()}]" for t in traits]
num_added = tokenizer.add_tokens(special_tokens)
print(f"Added {num_added} special tokens: {special_tokens}")
if tokenizer.pad_token is None:
tokenizer.pad_token = tokenizer.eos_token
def tokenize_data(batch):
return tokenizer(
batch["text"], padding="max_length", truncation=True, max_length=512
)
dataset = Dataset.from_pandas(df[["text"]])
tokenized_dataset = dataset.map(tokenize_data, batched=True, remove_columns=["text"])
# -----------------------------
# Step 3: Load model with offload + prepare for LoRA
# -----------------------------
bnb_config = BitsAndBytesConfig(
load_in_8bit=True,
bnb_8bit_compute_dtype=torch.bfloat16,
bnb_8bit_quant_type="nf4",
bnb_8bit_use_double_quant=True
)
model = AutoModelForCausalLM.from_pretrained(
model_checkpoint,
trust_remote_code=True,
torch_dtype=torch.bfloat16,
quantization_config=bnb_config,
device_map="auto",
offload_folder="offload",
offload_state_dict=True,
low_cpu_mem_usage=True
)
model.resize_token_embeddings(len(tokenizer))
# Prepare for 8-bit training and add LoRA adapters
model = prepare_model_for_kbit_training(model)
lora_config = LoraConfig(
r=16,
lora_alpha=32,
target_modules=["q_proj", "v_proj"],
lora_dropout=0.05,
bias="none",
task_type="CAUSAL_LM"
)
model = get_peft_model(model, lora_config)
model.print_trainable_parameters()
# -----------------------------
# Step 4: Training setup and run
# -----------------------------
output_dir = "./deepseek_moe_expert_prompting"
training_args = TrainingArguments(
output_dir=output_dir,
per_device_train_batch_size=1,
gradient_accumulation_steps=8,
num_train_epochs=1,
save_strategy="steps",
save_steps=500,
save_total_limit=2,
logging_strategy="steps",
logging_steps=50,
do_eval=False,
report_to="none",
seed=SEED,
load_best_model_at_end=False
)
trainer = Trainer(
model=model,
args=training_args,
train_dataset=tokenized_dataset,
tokenizer=tokenizer,
data_collator=DataCollatorForLanguageModeling(tokenizer, mlm=False)
)
# Resume from checkpoint if available
epoch_ckpts = [d for d in os.listdir(output_dir)
if d.startswith("checkpoint-")]
if epoch_ckpts:
latest = max(epoch_ckpts, key=lambda x: int(x.split('-')[1]))
trainer.train(resume_from_checkpoint=os.path.join(output_dir, latest))
else:
trainer.train()
print("Training complete.")
trainer.save_model(output_dir)
tokenizer.save_pretrained(output_dir)
Message:
config.json:
1.07k/? [00:00<00:00, 198kB/s]
configuration_deepseek.py:
10.2k/? [00:00<00:00, 1.33MB/s]
A new version of the following files was downloaded from https://huggingface.co/deepseek-ai/deepseek-moe-16b-base:
configuration_deepseek.py
. Make sure to double-check they do not contain any added malicious code. To avoid downloading new versions of the code file, you can pin a revision.
modeling_deepseek.py:
72.7k/? [00:00<00:00, 13.0MB/s]
A new version of the following files was downloaded from https://huggingface.co/deepseek-ai/deepseek-moe-16b-base:
modeling_deepseek.py
. Make sure to double-check they do not contain any added malicious code. To avoid downloading new versions of the code file, you can pin a revision.
model.safetensors.index.json:
490k/? [00:00<00:00, 60.6MB/s]
Fetching 7 files: 100%
7/7 [00:21<00:00, 21.45s/it]
model-00006-of-00007.safetensors: 100%
5.00G/5.00G [00:21<00:00, 607MB/s]
model-00002-of-00007.safetensors: 100%
5.00G/5.00G [00:19<00:00, 292MB/s]
model-00007-of-00007.safetensors: 100%
2.77G/2.77G [00:15<00:00, 246MB/s]
model-00005-of-00007.safetensors: 100%
5.00G/5.00G [00:21<00:00, 651MB/s]
model-00001-of-00007.safetensors: 100%
5.00G/5.00G [00:21<00:00, 652MB/s]
model-00004-of-00007.safetensors: 100%
5.00G/5.00G [00:21<00:00, 515MB/s]
model-00003-of-00007.safetensors: 100%
5.00G/5.00G [00:21<00:00, 870MB/s]
Loading checkpoint shards: 86%
6/7 [02:28<00:26, 26.51s/it]
Error Starting Kernel
Kernel died unexpectedly
Assistant
The message you're seeing includes:
Downloading the model and config files successfully from Hugging Face.
Loading checkpoint shards, progressing but eventually,
"Error Starting Kernel" and "Kernel died unexpectedly"
What does this mean?
Your Python kernel (likely in a Jupyter notebook or an IDE terminal) crashes during or right after loading the model into memory. The line:
code
Loading checkpoint shards: 86% (6/7) [...]
indicates it happens while loading large model shards from the safetensors checkpoint.
Possible Causes - Kernel Death While Loading Large Models:
Out of Memory (OOM):
Your GPU or CPU runs out of memory trying to load the 16B parameter model.
Typical symptoms: Kernel dies abruptly, no explicit Python exception visible.
Although you specified bnb_config for 8-bit quantization and offloading, the model is massive and might still exceed your hardware capacity.
Mismatch Between Quantization and Model or Device Setup:
torch_dtype=torch.bfloat16 and load_in_8bit=True might conflict if your GPU or PyTorch setup does not fully support bfloat16.
Using bfloat16 requires newer GPUs (e.g., A100, H100) and appropriate CUDA/cuDNN versions.
Disk Space or IO Bottleneck:
offload_folder="offload" is used for CPU offloading, make sure:
The folder exists or can be created.
You have enough disk space.
Slow IO or corrupted download shards can cause failures.
Environment Issues:
Incompatible versions of Transformers, PEFT, BitsAndBytes, or PyTorch.
Outdated or buggy BitsAndBytes can cause issues loading huge models.
Mixed libraries or CUDA/cuDNN versions mismatch.
Trust Remote Code Security Prompt:
Not exactly a cause for crash but if environment is sandboxed or restricted, dynamically loaded code (because of trust_remote_code=True) might not execute properly.
User
1 x RTX 6000 Ada
16 vCPU 62 GB RAM
500 GB Disk
500 GB Pod Volume
Assistant
Thanks for the hardware details:
GPU: NVIDIA RTX 6000 Ada (48 GB VRAM)
CPU: 16 vCPU
RAM: 62 GB
Disk: Plenty of disk space
Analysis
Your RTX 6000 Ada has 48 GB of GPU memory, which should in principle be able to handle loading large models with 8-bit quantization and offloading.
62 GB RAM is good for offloading some tensors, and your disk storage is sufficient.
You are using bnb_8bit_compute_dtype=torch.bfloat16. The Ada architecture (Ada Lovelace) does not fully support bfloat16, it rather has FP16/fp32/TF32 support.
This is likely a crucial cause of the crash:
bnb_8bit_compute_dtype=torch.bfloat16 is incompatible with your GPU's supported dtypes.
Recommendations based on hardware:
Change bnb_8bit_compute_dtype to torch.float16:
Modify your BitsAndBytesConfig initialization from:
Does this successfull apply the suggested changes?
code
Assistant
Yes, your code does successfully apply the suggested changes regarding the quantization dtype and model loading for your RTX 6000 Ada GPU. Let's verify the key points:
happens because mkdir -p offload is a shell command, but you are running it directly as Python code in a Jupyter notebook cell, where it's invalid syntax.
How to fix this in a Jupyter notebook:
Run shell commands with a leading exclamation mark !, like this:
File /usr/local/lib/python3.10/dist-packages/transformers/modeling_utils.py:3301, in PreTrainedModel._get_resized_embeddings(self, old_embeddings, new_num_tokens, pad_to_multiple_of, mean_resizing)
3289 raise TypeError(
3290 f"Old embeddings are of type {type(old_embeddings)}, which is not an instance of {nn.Embedding}. You"
3291 " should either use a different resize function or make sure that old_embeddings are an instance of"
3292 f" {nn.Embedding}."
3293 )
3295 # Build new embeddings
3296
3297 # When using DeepSpeed ZeRO-3, we shouldn't create new embeddings with DeepSpeed init
3298 # because the shape of the new embedding layer is used across various modeling files
3299 # as well as to update config vocab size. Shape will be 0 when using DeepSpeed init leading
3300 # to errors when training.
-> 3301 new_embeddings = nn.Embedding(
3302 new_num_tokens,
3303 old_embedding_dim,
3304 device=old_embeddings.weight.device,
3305 dtype=old_embeddings.weight.dtype,
3306 )
3308 if new_num_tokens > old_num_tokens and not mean_resizing:
3309 # initialize new embeddings (in particular added tokens) with a mean of 0 and std equals .
3310 self._init_weights(new_embeddings)
Assistant
The key error here is:
code
RuntimeError: CUDA error: no kernel image is available for execution on the device
This is a CUDA compatibility issue between your installed PyTorch (and/or bitsandbytes) binaries and your GPU architecture (NVIDIA RTX 6000 Ada, Ada Lovelace architecture).
What does this mean?
Your GPU uses Ada Lovelace architecture (compute capability 8.9).
The PyTorch or bitsandbytes version you installed does not have CUDA kernels compiled for this new GPU architecture.
This leads to "no kernel image" errors when CUDA tries to run kernels not compatible with your GPU.
Why did this happen?
Pre-built PyTorch and bitsandbytes wheels are compiled targeting commonly used CUDA versions and GPU architectures present at their release time.
Ada Lovelace is new; older PyTorch versions may not support it yet.
CUDA versions too old, or binary incompatibilities cause these runtime errors.
How to fix it?
1. Check your CUDA version and PyTorch + bitsandbytes versions
This ensures you have PyTorch + bitsandbytes built for CUDA 11.8, supporting Ada GPUs.
3. Verify bitsandbytes is installed correctly
BitsAndBytes releases must support your GPU. BitsAndBytes v0.39+ includes support for newer CUDA and GPUs.
4. If you use accelerate, upgrade it too:
User
Option 6 did work after running it. Does this mean that bitsandbytes is the problem?
Assistant
Yes, exactly — since loading the model without 8-bit quantization (i.e., without bitsandbytes) worked fine, but your original code using bitsandbytes (8-bit quantization) crashes with the CUDA kernel error, it strongly indicates the problem is with bitsandbytes and its compatibility with your GPU or CUDA environment.
Why bitsandbytes is the likely culprit:
bitsandbytes provides custom CUDA kernels and quantization routines compiled for specific CUDA versions and GPU architectures.
If bitsandbytes version installed does not support your GPU (NVIDIA RTX 6000 Ada, Ada Lovelace), or the CUDA version it was built for is incompatible, you get the no kernel image runtime error.
The fact that model loading without bitsandbytes works proves your PyTorch and GPU setup itself is working fine.
How to fix bitsandbytes compatibility:
Upgrade bitsandbytes to latest version
bash
pip install --upgrade bitsandbytes
BitsAndBytes v0.39+ adds support for recent CUDA and GPUs including Ada Lovelace.
Ensure CUDA version on your system matches bitsandbytes build
If using CUDA 11.8, install PyTorch and bitsandbytes built for CUDA 11.8 (see earlier messages).
You can check your system CUDA version: nvcc --version or nvidia-smi
Or rely on the CUDA runtime included in your installed PyTorch wheels.
Reinstall PyTorch and bitsandbytes together for CUDA 11.8
Check bitsandbytes Github issues for Ada Lovelace related problems.
Possibly build bitsandbytes from source (requires CUDA toolkit and build tools).
Summary
Model loads fine without 8-bit quant → bitsandbytes is triggering the CUDA error.
Update bitsandbytes + PyTorch to CUDA 11.8 compatible versions that support Ada Lovelace GPUs.
Then retry your original workflow with 8-bit quantization enabled.
If you want, I can guide you through the exact installation commands or troubleshooting steps for bitsandbytes on your GPU setup.
User
How's it look with changes?
code
# -----------------------------
# Step 3: Load model and resize embeddings
# -----------------------------
# Configure 8-bit quantization
bnb_config = BitsAndBytesConfig(
load_in_8bit=True,
bnb_8bit_compute_dtype=torch.float16,
bnb_8bit_quant_type="nf4",
bnb_8bit_use_double_quant=True
)
model = AutoModelForCausalLM.from_pretrained(
model_checkpoint,
trust_remote_code=True,
torch_dtype=torch.float16,
quantization_config=bnb_config,
device_map="auto",
offload_folder="offload",
offload_state_dict=True,
low_cpu_mem_usage=True
)
model.resize_token_embeddings(len(tokenizer))
# Prepare model for 8-bit training and add LoRA adapters
model = prepare_model_for_kbit_training(model)
lora_config = LoraConfig(
r=16, # LoRA attention dimension
lora_alpha=32, # Alpha parameter for LoRA scaling
target_modules=["q_proj", "v_proj"], # Modules to apply LoRA to
lora_dropout=0.05, # Dropout probability for LoRA layers
bias="none", # Bias type
task_type="CAUSAL_LM", # Task type
)
model = get_peft_model(model, lora_config)
model.print_trainable_parameters()
# -----------------------------
# Step 4: Training setup
# -----------------------------
output_dir = "./deepseek_moe_expert_prompting"
training_args = TrainingArguments(
output_dir=output_dir,
per_device_train_batch_size=1, # Reduced batch size
gradient_accumulation_steps=8, # Increased gradient accumulation steps
num_train_epochs=1,
save_steps=500,
logging_dir="./logs",
logging_steps=50,
do_eval=False,
report_to="none",
seed=SEED,
# Add checkpointing arguments
save_strategy="steps",
save_total_limit=2, # Keep up to 2 checkpoints
load_best_model_at_end=False, # We are not doing evaluation
)
trainer = Trainer(
model=model,
args=training_args,
train_dataset=tokenized_dataset,
tokenizer=tokenizer,
data_collator=DataCollatorForLanguageModeling(tokenizer, mlm=False),
)
print("Starting training...")
# Check if a checkpoint exists to resume from
latest_checkpoint = None
if os.path.exists(output_dir):
# This assumes checkpoint directories are named like "checkpoint-XXX"
checkpoint_dirs = [d for d in os.listdir(output_dir) if os.path.isdir(os.path.join(output_dir, d)) and d.startswith("checkpoint-")]
if checkpoint_dirs:
# Find the latest checkpoint based on step number
latest_checkpoint_dir = max(checkpoint_dirs, key=lambda d: int(d.split("-")[1]))
latest_checkpoint = os.path.join(output_dir, latest_checkpoint_dir)
print(f"Resuming from checkpoint: {latest_checkpoint}")
# Use resume_from_checkpoint if a checkpoint is found
trainer.train(resume_from_checkpoint=latest_checkpoint)
print("Training complete.")
trainer.save_model(output_dir)
tokenizer.save_pretrained(output_dir)
Assistant
Your updated code snippet looks well-structured and incorporates the needed adjustments correctly. Here’s a detailed review and some minor suggestions to ensure robustness:
What you did well:
BitsAndBytesConfig: Using bnb_8bit_compute_dtype=torch.float16 aligned with your GPU's architecture.
Model loading: Specifying quantization_config=bnb_config and torch_dtype=torch.float16.
Resizing token embeddings after loading the model is correctly placed.
Preparing model for k-bit training and adding LoRA adapters with appropriate arguments.
TrainingArguments and the Trainer setup look solid and correctly configured.
Checkpoint resuming logic is well-implemented.
Prints and comments improve readability.
Minor suggestions / potential improvements
Ensure tokenizer and model_checkpoint are defined
Make sure, before this snippet, you have something like:
resize_token_embeddings with caching/loading models
Sometimes resizing embeddings after loading a checkpoint or with offload may trigger device placement issues or slowdowns. Usually okay here.
Offload folder
Confirm offload directory exists and is writable before loading the model to avoid silent failures:
python
import os
os.makedirs("offload", exist_ok=True)
Catch exceptions for training start
Optional but useful for debugging:
python
try:
trainer.train(resume_from_checkpoint=latest_checkpoint)
except Exception as e:
print(f"Training failed: {e}")
raise
User
Can do without bitsandbytes?
Assistant
Yes, you can absolutely run your training without bitsandbytes and 8-bit quantization, i.e., in full precision (fp16 mixed precision or fp32), but:
Your model is very large (16B parameters), so running it without memory optimizations will require a lot of GPU RAM.
With your RTX 6000 Ada (48 GB VRAM), you might be able to load a 16B model in fp16 depending on model architecture and transformers optimizations, but it’s tight and might require additional offloading or smaller batch sizes.
What you need to do to run without bitsandbytes:
Remove or comment out all bitsandbytes config, and do not provide quantization_config.
Load the model in fp16 or float32 without load_in_8bit:
Example:
python
model = AutoModelForCausalLM.from_pretrained(
model_checkpoint,
trust_remote_code=True,
torch_dtype=torch.float16, # or torch.float32 if desired but uses more memory
device_map="auto",
offload_folder="offload", # Optional, to reduce GPU memory pressure
offload_state_dict=True, # Optional
low_cpu_mem_usage=True # Optional
)
No need to define or import BitsAndBytesConfig.
Keep the rest of your training code unchanged (tokenizer, prepare_model_for_kbit_training is NOT needed now since you are not doing k-bit training).
Important notes:
Remove steps related to LoRA + k-bit training if you don’t intend to use LoRA or PEFT.
But you can keep LoRA adapters even without 8-bit quantization!
prepare_model_for_kbit_training() prepares the model for quantized training and is not necessary if you are not quantizing. If you want to use PEFT/LoRA anyway (which you can), just skip that function call.
Depending on model size, mixed precision (torch_dtype=torch.float16) will reduce VRAM usage compared to float32.
Minimal example for full precision / fp16 without bitsandbytes
User
Please do!
Assistant
Certainly! Here’s your full training step rewritten without bitsandbytes and 8-bit quantization, but still using LoRA adapters and mixed precision (fp16) for efficient GPU memory use. I also removed prepare_model_for_kbit_training() because it’s for k-bit training and not needed here.
python
User
Does this look right?
code
# -----------------------------
# Step 3: Load model and resize embeddings
# -----------------------------
model = AutoModelForCausalLM.from_pretrained(
model_checkpoint,
trust_remote_code=True,
torch_dtype=torch.float16,
device_map="auto",
offload_folder="offload",
offload_state_dict=True,
low_cpu_mem_usage=True
)
model.resize_token_embeddings(len(tokenizer))
# Prepare model for 8-bit training and add LoRA adapters
model = prepare_model_for_kbit_training(model)
lora_config = LoraConfig(
r=16, # LoRA attention dimension
lora_alpha=32, # Alpha parameter for LoRA scaling
target_modules=["q_proj", "v_proj"], # Modules to apply LoRA to
lora_dropout=0.05, # Dropout probability for LoRA layers
bias="none", # Bias type
task_type="CAUSAL_LM", # Task type
)
model = get_peft_model(model, lora_config)
model.print_trainable_parameters()
# -----------------------------
# Step 4: Training setup
# -----------------------------
output_dir = "./deepseek_moe_expert_prompting"
training_args = TrainingArguments(
output_dir=output_dir,
per_device_train_batch_size=1, # Reduced batch size
gradient_accumulation_steps=8, # Increased gradient accumulation steps
num_train_epochs=1,
save_steps=500,
logging_dir="./logs",
logging_steps=50,
do_eval=False,
report_to="none",
seed=SEED,
# Add checkpointing arguments
save_strategy="steps",
save_total_limit=2, # Keep up to 2 checkpoints
load_best_model_at_end=False, # We are not doing evaluation
)
trainer = Trainer(
model=model,
args=training_args,
train_dataset=tokenized_dataset,
tokenizer=tokenizer,
data_collator=DataCollatorForLanguageModeling(tokenizer, mlm=False),
)
print("Starting training...")
# Check if a checkpoint exists to resume from
latest_checkpoint = None
if os.path.exists(output_dir):
# This assumes checkpoint directories are named like "checkpoint-XXX"
checkpoint_dirs = [d for d in os.listdir(output_dir) if os.path.isdir(os.path.join(output_dir, d)) and d.startswith("checkpoint-")]
if checkpoint_dirs:
# Find the latest checkpoint based on step number
latest_checkpoint_dir = max(checkpoint_dirs, key=lambda d: int(d.split("-")[1]))
latest_checkpoint = os.path.join(output_dir, latest_checkpoint_dir)
print(f"Resuming from checkpoint: {latest_checkpoint}")
# Use resume_from_checkpoint if a checkpoint is found
trainer.train(resume_from_checkpoint=latest_checkpoint)
print("Training complete.")
trainer.save_model(output_dir)
tokenizer.save_pretrained(output_dir)
Assistant
Your code looks mostly correct and well-structured for the training setup, but there is one important inconsistency:
The inconsistency:
python
model = prepare_model_for_kbit_training(model)
prepare_model_for_kbit_training() is intended specifically for k-bit (4-bit or 8-bit) training setups using bitsandbytes.
Since you are now not using bitsandbytes or 8-bit quantization, this call is unnecessary.
Moreover, this function may alter weights or layers expecting quantized weights, so it can cause unexpected behavior or errors if used outside a k-bit training context.
What you should do:
If you’re training without bitsandbytes and without k-bit quantization (so full precision fp16 here), remove the line:
python
model = prepare_model_for_kbit_training(model)
and simply do:
python
model = AutoModelForCausalLM.from_pretrained(
model_checkpoint,
trust_remote_code=True,
torch_dtype=torch.float16,
device_map="auto",
offload_folder="offload",
offload_state_dict=True,
low_cpu_mem_usage=True
)
model.resize_token_embeddings(len(tokenizer))
# Then add LoRA adapters as you do
Why remove it?
prepare_model_for_kbit_training() is mostly:
Wrapping layers for 8-bit parameter training.
Disabling gradients on some parameters.
Adding layer norm fixes for stable quantized training.
Without quantization, this is not necessary and might cause issues.
Other points — everything else looks good
Training args setup and Trainer use is fine.
Checkpoint resume logic is sound.
Token embeddings resize is correct.
Use of LoRA is appropriate.
Good logging and seed control.
Summary:
User
/usr/local/lib/python3.10/dist-packages/torch/cuda/init.py:287: UserWarning:
NVIDIA GeForce RTX 5090 with CUDA capability sm_120 is not compatible with the current PyTorch installation.
The current PyTorch install supports CUDA capabilities sm_50 sm_60 sm_70 sm_75 sm_80 sm_86 sm_37 sm_90.
If you want to use the NVIDIA GeForce RTX 5090 GPU with PyTorch, please check the instructions at https://pytorch.org/get-started/locally/
File /usr/local/lib/python3.10/dist-packages/transformers/modeling_utils.py:3301, in PreTrainedModel._get_resized_embeddings(self, old_embeddings, new_num_tokens, pad_to_multiple_of, mean_resizing)
3289 raise TypeError(
3290 f"Old embeddings are of type {type(old_embeddings)}, which is not an instance of {nn.Embedding}. You"
3291 " should either use a different resize function or make sure that are an instance of"
3292 f" {nn.Embedding}."
3293 )
3295 # Build new embeddings
3296
3297 # When using DeepSpeed ZeRO-3, we shouldn't create new embeddings with DeepSpeed init
3298 # because the shape of the new embedding layer is used across various modeling files
3299 # as well as to update config vocab size. Shape will be 0 when using DeepSpeed init leading
3300 # to errors when training.
-> 3301 new_embeddings = nn.Embedding(
3302 new_num_tokens,
3303 old_embedding_dim,
3304 device=old_embeddings.weight.device,
3305 dtype=old_embeddings.weight.dtype,
3306 )
3308 if new_num_tokens > old_num_tokens and not mean_resizing:
3309 # initialize new embeddings (in particular added tokens) with a mean of 0 and std equals .
3310 self._init_weights(new_embeddings)
Assistant
The key things here:
Warning:
code
NVIDIA GeForce RTX 5090 with CUDA capability sm_120 is not compatible with the current PyTorch installation.
The current PyTorch install supports CUDA capabilities sm_50 sm_60 sm_70 sm_75 sm_80 sm_86 sm_37 sm_90.
Your GPU (RTX 5090) has CUDA compute capability 12.0 (sm_120), which is very new.
The PyTorch version installed does not have precompiled CUDA kernels targeting sm_120.
That means PyTorch can't run native CUDA kernels on your GPU properly, resulting in no kernel image runtime errors.
How to fix this:
Step 1: Check your PyTorch + CUDA compatibility with RTX 5090.
Currently (as of mid-2024), official PyTorch wheels do not yet include support for compute capability 12.0 GPUs out of the box.
You need a PyTorch build that includes CUDA 12.x support and kernels for sm_120.
Step 2: Install CUDA 12.x + PyTorch nightly or custom build
Options:
Install latest CUDA 12.x toolkits and drivers on your system.
Use PyTorch nightly builds compiled with CUDA 12.x support:
If this crashes, problem is model+quant config or hardware limits.
Check offload_folder Permissions:
Ensure folder exists and is writable:
bash
mkdir -p offload
chmod u+rwx offload
Avoid Kernel in Jupyter for Large Models:
Try running script directly from terminal to catch full traceback.
Pin model revision for consistent code:
Sometimes latest modeling_deepseek.py updates cause issues.
Pin by setting revision="commit-hash" in from_pretrained().
Summary
The "Kernel died unexpectedly" is very likely due to out-of-memory error or incompatibilities when loading an extremely large model with 8-bit quantization + offloading + bfloat16 dtype.
Short-term fixes you can try
Load model without quantization first to verify working environment:
python
model = AutoModelForCausalLM.from_pretrained(
model_checkpoint,
trust_remote_code=True,
torch_dtype=torch.float16,
device_map="auto"
)
Disable offloading and load everything on GPU or CPU depending on hardware availability.
Make sure offload_folder exists.
Run code on a machine with more GPU memory or multiple GPUs.
If you provide your hardware specs (GPU model & RAM size), I can suggest more tailored advice.
Check your bitsandbytes version:
Make sure you have at least bitsandbytes v0.39.0+ which has better support for Ada GPUs and nf4 quantization.
Upgrade with:
bash
pip install --upgrade bitsandbytes
Offload folder perms
Verify your offload folder exists and is writable since you configure offloading there:
bash
mkdir -p offload
chmod u+rwx offload
Try simpler loading first
Try to just load the model with 8-bit float16 config and without LoRA first to verify your environment:
python
from transformers import AutoModelForCausalLM, BitsAndBytesConfig
bnb_config = BitsAndBytesConfig(load_in_8bit=True, bnb_8bit_compute_dtype=torch.float16)
model = AutoModelForCausalLM.from_pretrained(
"deepseek-ai/deepseek-moe-16b-base",
trust_remote_code=True,
torch_dtype=torch.float16,
quantization_config=bnb_config,
device_map="auto",
)
If that works, then proceed adding PEFT/LoRA layers.
Why bfloat16 causes issues here
bfloat16 is primarily supported on NVIDIA A100, H100, and newer data center GPUs.
Ada Lovelace cards (like RTX 4090 / RTX 6000 Ada) do not support bfloat16 natively, so attempts to use it on this card often cause runtime errors or silent crashes.
float16 (fp16) is the correct choice for this hardware.
Summary
Your kernel likely dies because your RTX 6000 Ada does not support bfloat16 compute in bitsandbytes. Change to bnb_8bit_compute_dtype=torch.float16 and torch_dtype=torch.float16 and retry.
If you do that and still have problems, please share any logs or errors you get. But this is the main issue given your hardware specs and error pattern.
!pip install --upgrade transformers peft bitsandbytes accelerate torch huggingface_hub pandas numpy datasets
mkdir -p offload
chmod u+rwx offload
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
import torch
import os
import json
import pandas as pd
from datasets import Dataset
from transformers import (
AutoTokenizer, AutoModelForCausalLM, TrainingArguments, Trainer,
DataCollatorForLanguageModeling, pipeline, BitsAndBytesConfig
)
import random
import numpy as np
# Configure 8-bit quantization
bnb_config = BitsAndBytesConfig(
load_in_8bit=True,
bnb_8bit_compute_dtype=torch.float16,
bnb_8bit_quant_type="nf4",
bnb_8bit_use_double_quant=True
)
model = AutoModelForCausalLM.from_pretrained(
model_checkpoint,
trust_remote_code=True,
torch_dtype=torch.float16,
quantization_config=bnb_config,
device_map="auto",
offload_folder="offload",
offload_state_dict=True,
low_cpu_mem_usage=True
)
model.resize_token_embeddings(len(tokenizer))
# Prepare model for 8-bit training and add LoRA adapters
model = prepare_model_for_kbit_training(model)
lora_config = LoraConfig(
r=16, # LoRA attention dimension
lora_alpha=32, # Alpha parameter for LoRA scaling
target_modules=["q_proj", "v_proj"], # Modules to apply LoRA to
lora_dropout=0.05, # Dropout probability for LoRA layers
bias="none", # Bias type
task_type="CAUSAL_LM", # Task type
)
model = get_peft_model(model, lora_config)
model.print_trainable_parameters()
# -----------------------------
# Step 4: Training setup
# -----------------------------
output_dir = "./deepseek_moe_expert_prompting"
training_args = TrainingArguments(
output_dir=output_dir,
per_device_train_batch_size=1, # Reduced batch size
gradient_accumulation_steps=8, # Increased gradient accumulation steps
num_train_epochs=1,
save_steps=500,
logging_dir="./logs",
logging_steps=50,
do_eval=False,
report_to="none",
seed=SEED,
# Add checkpointing arguments
save_strategy="steps",
save_total_limit=2, # Keep up to 2 checkpoints
load_best_model_at_end=False, # We are not doing evaluation
)
trainer = Trainer(
model=model,
args=training_args,
train_dataset=tokenized_dataset,
tokenizer=tokenizer,
data_collator=DataCollatorForLanguageModeling(tokenizer, mlm=False),
)
print("Starting training...")
# Check if a checkpoint exists to resume from
latest_checkpoint = None
if os.path.exists(output_dir):
# This assumes checkpoint directories are named like "checkpoint-XXX"
checkpoint_dirs = [d for d in os.listdir(output_dir) if os.path.isdir(os.path.join(output_dir, d)) and d.startswith("checkpoint-")]
if checkpoint_dirs:
# Find the latest checkpoint based on step number
latest_checkpoint_dir = max(checkpoint_dirs, key=lambda d: int(d.split("-")[1]))
latest_checkpoint = os.path.join(output_dir, latest_checkpoint_dir)
print(f"Resuming from checkpoint: {latest_checkpoint}")
# Use resume_from_checkpoint if a checkpoint is found
trainer.train(resume_from_checkpoint=latest_checkpoint)
print("Training complete.")
trainer.save_model(output_dir)
tokenizer.save_pretrained(output_dir)
RuntimeError: CUDA error: no kernel image is available for execution on the device
CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect.
For debugging consider passing CUDA_LAUNCH_BLOCKING=1
Compile with TORCH_USE_CUDA_DSA to enable device-side assertions.
bash
pip install --upgrade accelerate
5. Set TORCH_USE_CUDA_DSA=1 (optional)
You can enable device-side assertions to get more debugging info:
bash
export TORCH_USE_CUDA_DSA=1
Run this before executing your script.
6. As a test, try lowest complexity code snippet:
Test model loading without 8-bit quantization to isolate issue:
python
from transformers import AutoModelForCausalLM
model_checkpoint = "deepseek-ai/deepseek-moe-16b-base"
model = AutoModelForCausalLM.from_pretrained(
model_checkpoint,
trust_remote_code=True,
torch_dtype=torch.float16,
device_map="auto"
)
print("Model loaded successfully")
If this works, then 8-bit quantization or bitsandbytes is the culprit.
7. Alternative: Build from source (advanced)
If your pip packages do not support Ada Lovelace GPUs, building PyTorch and bitsandbytes from source with latest CUDA toolkit is a last resort.
Summary
Your CUDA runtime does not support Ada Lovelace GPU with current PyTorch/bitsandbytes.
Install PyTorch & bitsandbytes wheels built for CUDA 11.8.
Upgrade packages with compatible CUDA support.
Verify CUDA and GPU visible from PyTorch.
Optionally test simpler model load without 8-bit quant.
If you want, I can provide exact installation commands for CUDA 11.8 PyTorch + bitsandbytes setup tailored for your environment.
Set save_total_limit appropriately
Currently you keep 2 checkpoints, which is reasonable. Just ensure disk space is sufficient.
Potential memory optimization flag
If you still run into OOM at any point, consider adjusting batch size or gradient accumulation.
Final thoughts
Your code snippet should work as intended, assuming your environment (PyTorch, bitsandbytes, CUDA drivers) is properly set up and compatible.
If you experience runtime crashes related to device compatibility or memory, revisit versions of PyTorch/bitsandbytes and your CUDA driver installation.
TL;DR
✅ Your changes are correct and appropriate for your hardware setup.
✅ Just ensure dependencies are compatible and offload folder exists before model load.
✅ Minor additions (error handling, folder creation) can improve robustness.
If you want, I can help you create a minimal reproducible script or provide step-by-step environment setup commands.
python
# Remove import bitsandbytes and BitsAndBytesConfig
model = AutoModelForCausalLM.from_pretrained(
model_checkpoint,
trust_remote_code=True,
torch_dtype=torch.float16,
device_map="auto",
offload_folder="offload",
offload_state_dict=True,
low_cpu_mem_usage=True
)
# If using LoRA adapters WITHOUT 8-bit:
from peft import LoraConfig, get_peft_model
lora_config = LoraConfig(
r=16,
lora_alpha=32,
target_modules=["q_proj", "v_proj"],
lora_dropout=0.05,
bias="none",
task_type="CAUSAL_LM"
)
model = get_peft_model(model, lora_config)
# Note: skip prepare_model_for_kbit_training()
Summary
Yes, you can train without bitsandbytes.
Just remove the bitsandbytes config and quantization flags.
Load model in torch.float16 or torch.float32 (fp16 recommended).
Adjust batch sizes accordingly for your GPU memory.
Optionally still use LoRA PEFT adapters without k-bit training.
Model load time and memory usage will increase but it'll be simpler and avoid compatibility pitfalls.
If you want, I can help you rewrite your full script to run without bitsandbytes — just ask!
# ------------- Imports -------------
import os
import random
import numpy as np
import pandas as pd
import torch
from datasets import Dataset
from transformers import (
AutoTokenizer,
AutoModelForCausalLM,
TrainingArguments,
Trainer,
DataCollatorForLanguageModeling,
)
from peft import LoraConfig, get_peft_model
# ------------- Reproducibility Setup -------------
SEED = 42
random.seed(SEED)
np.random.seed(SEED)
torch.manual_seed(SEED)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(SEED)
# ------------- Step 1: Load & preprocess your data -------------
# (Your existing code for loading JSON, filtering, formatting, tokenization)
# Make sure you have these variables defined below accordingly:
# - df: pandas DataFrame with your data filtered and formatted
# - traits: List of traits
# - model_checkpoint: model repo string
# - tokenizer: loaded tokenizer object
# - tokenized_dataset: your huggingface Dataset after tokenization
# (example snippet)
# model_checkpoint = "deepseek-ai/deepseek-moe-16b-base"
# tokenizer = AutoTokenizer.from_pretrained(model_checkpoint, trust_remote_code=True)
# tokenized_dataset = Dataset.from_pandas(df).map(tokenize_data, batched=True, remove_columns=["text"])
# ------------- Step 2: Ensure 'offload' folder exists -------------
os.makedirs("offload", exist_ok=True)
# ------------- Step 3: Load model WITHOUT bitsandbytes -------------
model = AutoModelForCausalLM.from_pretrained(
model_checkpoint,
trust_remote_code=True,
torch_dtype=torch.float16, # mixed precision
device_map="auto",
offload_folder="offload",
offload_state_dict=True,
low_cpu_mem_usage=True
)
# Resize embeddings for added special tokens if you have any
model.resize_token_embeddings(len(tokenizer))
# ------------- Step 4: Add LoRA adapters -------------
lora_config = LoraConfig(
r=16, # LoRA attention dimension
lora_alpha=32, # LoRA scaling alpha
target_modules=["q_proj", "v_proj"],
lora_dropout=0.05,
bias="none",
task_type="CAUSAL_LM"
)
model = get_peft_model(model, lora_config)
model.print_trainable_parameters()
# ------------- Step 5: Training setup -------------
output_dir = "./deepseek_moe_expert_prompting"
training_args = TrainingArguments(
output_dir=output_dir,
per_device_train_batch_size=1,
gradient_accumulation_steps=8,
num_train_epochs=1,
save_steps=500,
save_strategy="steps",
save_total_limit=2,
logging_dir="./logs",
logging_steps=50,
do_eval=False,
report_to="none",
seed=SEED,
load_best_model_at_end=False,
)
trainer = Trainer(
model=model,
args=training_args,
train_dataset=tokenized_dataset,
tokenizer=tokenizer,
data_collator=DataCollatorForLanguageModeling(tokenizer, mlm=False),
)
# ------------- Step 6: Resume training if checkpoint exists -------------
latest_checkpoint = None
if os.path.exists(output_dir):
checkpoint_dirs = [
d for d in os.listdir(output_dir)
if os.path.isdir(os.path.join(output_dir, d)) and d.startswith("checkpoint-")
]
if checkpoint_dirs:
latest_checkpoint_dir = max(checkpoint_dirs, key=lambda x: int(x.split("-")[1]))
latest_checkpoint = os.path.join(output_dir, latest_checkpoint_dir)
print(f"Resuming from checkpoint: {latest_checkpoint}")
# ------------- Step 7: Start training -------------
trainer.train(resume_from_checkpoint=latest_checkpoint)
print("Training complete.")
# ------------- Step 8: Save final model and tokenizer -------------
trainer.save_model(output_dir)
tokenizer.save_pretrained(output_dir)
Summary of changes:
Removed BitsAndBytesConfig and load_in_8bit=True stuff.
Removed call to prepare_model_for_kbit_training().
Kept torch_dtype=torch.float16 for fp16 mixed precision to reduce GPU memory usage.
Kept your LoRA adapter setup (get_peft_model) — works perfectly fine without bitsandbytes.
Made sure offload folder exists to help with memory management.
Everything else same.
Notes for running without bitsandbytes:
This will use more GPU memory compared to 8-bit training, so monitor VRAM usage.
Reduce per_device_train_batch_size or increase gradient_accumulation_steps if needed.
Offloading will help shift some model params to CPU when needed.
Mixed precision (fp16) gives a good tradeoff between speed and memory without bitsandbytes.
If you want me to help with the full data loading and tokenization snippet integration or environment setup, just ask!
If you want to do k-bit training (i.e., with bitsandbytes 8-bit quantization), then use prepare_model_for_kbit_training() alongside bitsandbytes config during model loading.
Feel free to ask if you want a fully cleaned script without bitsandbytes or the full 8-bit/LoRA combo!
old_embeddings
config.initializer_range
File /usr/local/lib/python3.10/dist-packages/torch/nn/modules/sparse.py:170, in Embedding.init(self, num_embeddings, embedding_dim, padding_idx, max_norm, norm_type, scale_grad_by_freq, sparse, _weight, _freeze, device, dtype)
165 if _weight is None:
166 self.weight = Parameter(
167 torch.empty((num_embeddings, embedding_dim), **factory_kwargs),
168 requires_grad=not _freeze,
169 )
--> 170 self.reset_parameters()
171 else:
172 assert list(_weight.shape) == [
173 num_embeddings,
174 embedding_dim,
175 ], "Shape of weight does not match num_embeddings and embedding_dim"
RuntimeError: CUDA error: no kernel image is available for execution on the device
CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect.
For debugging consider passing CUDA_LAUNCH_BLOCKING=1
Compile with TORCH_USE_CUDA_DSA to enable device-side assertions.