from optimum.intel import OVModelForCausalLM
import openvino.properties as props
import openvino.properties.hint as hints
import openvino.properties.streams as streams
from transformers import AutoTokenizer, GenerationConfig
import torch
Configure optimization settings
ov_config = {
hints.performance_mode(): hints.PerformanceMode.LATENCY,
streams.num(): "1",
props.cache_dir(): "",
"DYNAMIC_QUANTIZATION_GROUP_SIZE": "32", # For CPU optimization
"KV_CACHE_PRECISION": "u8" # For memory optimization
}
model = OVModelForCausalLM.from_pretrained(
model_name_or_id,
export=True,
ov_config=ov_config,
device="CPU",
# load_in_8bit=True, # Int8 quantization for OpenVINO is applied differently
torch_dtype=torch.float16,
trust_remote_code=True # Include if the model uses custom code
)
/opt/app-root/lib64/python3.9/site-packages/transformers/cache_utils.py:458: TracerWarning: Using len to get tensor shape might cause the trace to be incorrect. Recommended usage would be tensor.shape[0]. Passing a tensor of different shape might lead to errors or silently give incorrect results.
or len(self.key_cache[layer_idx]) == 0 # the layer has no cache
/opt/app-root/src/.cache/huggingface/modules/transformers_modules/AI4Chem/CHEMLLM-2b-1_5/215c0dbc89417a06bbc3bae43a3ad61e58f0a56e/modeling_internlm2.py:1095: TracerWarning: Converting a tensor to a Python boolean might cause the trace to be incorrect. We can't record the data flow of Python values, so this value will be treated as a constant in the future. This means that the trace might not generalize to other inputs!
if sequence_length != 1:
/opt/app-root/src/.cache/huggingface/modules/transformers_modules/AI4Chem/CHEMLLM-2b-1_5/215c0dbc89417a06bbc3bae43a3ad61e58f0a56e/modeling_internlm2.py:147: TracerWarning: Converting a tensor to a Python boolean might cause the trace to be incorrect. We can't record the data flow of Python values, so this value will be treated as a constant in the future. This means that the trace might not generalize to other inputs!
if seq_len > self.max_position_embeddings:
/opt/app-root/lib64/python3.9/site-packages/transformers/cache_utils.py:443: TracerWarning: Using len to get tensor shape might cause the trace to be incorrect. Recommended usage would be tensor.shape[0]. Passing a tensor of different shape might lead to errors or silently give incorrect results.
elif len(self.key_cache[layer_idx]) == 0: # fills previously skipped layers; checking for tensor causes errors
INFO:nncf:Statistics of the bitwidth distribution:
┍━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┑
│ Num bits (N) │ % all parameters (layers) │ % ratio-defining parameters (layers) │
┝━━━━━━━━━━━━━━━━┿━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┿━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┥
│ 8 │ 100% (122 / 122) │ 100% (122 / 122) │
┕━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┙
Applying Weight Compression ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100% • 0:00:26 • 0:00:00
Model load and optimization time: 149.88100218772888 seconds
Assistant
Inference
start_time = time.time()
prompt = "Predict the aqueous solubility (in mg/mL) and explain the factors affecting solubility for: CC1=CC=C(C=C1)C(=O)CCCN"
File /opt/app-root/lib64/python3.9/site-packages/transformers/generation/utils.py:3249, in GenerationMixin._sample(self, input_ids, logits_processor, stopping_criteria, generation_config, synced_gpus, streamer, **model_kwargs)
3247 probs = nn.functional.softmax(next_token_scores, dim=-1)
3248 # TODO (joao): this OP throws "skipping cudagraphs due to ['incompatible ops']", find solution
-> 3249 next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)
3250 else:
3251 next_tokens = torch.argmax(next_token_scores, dim=-1)
File /opt/app-root/lib64/python3.9/site-packages/nncf/torch/dynamic_graph/wrappers.py:86, in wrap_operator..wrapped(*args, **kwargs)
84 ctx = get_current_context()
85 if not ctx or getattr(ctx, "in_operator", False) or not ctx.is_tracing:
---> 86 op1 = operator(*args, **kwargs)
87 return op1
89 ctx.in_operator = True
RuntimeError: probability tensor contains either inf, nan or element < 0
The error you're encountering:
RuntimeError: probability tensor contains either `inf`, `nan` or element < 0
is due to invalid probability values during the generation process, which typically originate from the model's output logits. In your case, this is likely caused by numerical instability arising from using half-precision (FP16) computations with your model. Here's how you can resolve this issue:
Change torch_dtype to torch.float32:
In your model loading code, you're specifying torch_dtype=torch.float16. While FP16 can speed up computations and reduce memory usage, it may introduce numerical instability, especially with models that are not specifically optimized for half-precision arithmetic. This can result in inf, nan, or negative values in the output logits after certain operations like softmax, leading to invalid probabilities.
Solution: Change torch_dtype to torch.float32 to ensure computations are performed in full precision, reducing the risk of numerical errors.
model = OVModelForCausalLM.from_pretrained(
model_name_or_id,
export=True,
ov_config=ov_config,
device="CPU",
torch_dtype=torch.float32, # Changed from torch.float16 to torch.float32
trust_remote_code=True # Include if the model uses custom code
)
Adjust or Remove Quantization Settings:
The ov_config includes quantization settings that can affect numerical precision:
ov_config = {
hints.performance_mode(): hints.PerformanceMode.LATENCY,
streams.num(): "1",
props.cache_dir(): "",
"DYNAMIC_QUANTIZATION_GROUP_SIZE": "32", # For CPU optimization
"KV_CACHE_PRECISION": "u8" # For memory optimization
}
Quantization can introduce numerical inaccuracies if not properly configured or if the model isn't robust to low-precision arithmetic.
Solution: Try commenting out or adjusting these settings to see if they are contributing to the problem.
Ensure that the pad_token_id is set correctly in both the tokenizer and the model configuration. An incorrect pad_token_id can cause issues during generation.
Solution: Explicitly set the pad_token_id in the model configuration if it's not already set.
The repetition_penalty can sometimes amplify small numerical errors in the logits, leading to invalid probabilities after applying the penalty.
Solution: Set repetition_penalty to 1.0 or remove it to test if it's causing the issue.
generation_config = GenerationConfig(
do_sample=True,
top_k=10,
temperature=0.9,
max_new_tokens=500,
repetition_penalty=1.0, # Changed to 1.0 or remove this line
pad_token_id=tokenizer.eos_token_id
)
Disable Sampling for Testing:
To determine if the issue is specifically with the sampling process, you can temporarily disable sampling by setting do_sample=False. This will use greedy decoding instead, which doesn't involve multinomial sampling and can help isolate the problem.
Solution: Set do_sample=False in your generation configuration.
generation_config = GenerationConfig(
do_sample=False, # Set to False to use greedy decoding
top_k=10,
temperature=0.9,
max_new_tokens=500,
pad_token_id=tokenizer.eos_token_id
)
Check the Input Prompt and Tokenization:
Ensure that the input prompt is tokenized correctly and that the tokenizer is compatible with the model.
Solution: Verify that the tokenizer and model are in sync and that the prompt doesn't introduce any unexpected issues.
Change torch_dtype to torch.float32 when loading the model.
Comment out or adjust quantization settings in ov_config.
Set model.config.pad_token_id to tokenizer.eos_token_id.
Adjust or remove the repetition_penalty.
Set do_sample=False to use greedy decoding for testing.
Verify the tokenizer settings and input prompt.
Updated Code:
import time
start_time = time.time()
from optimum.intel import OVModelForCausalLM
import openvino.properties as props
import openvino.properties.hint as hints
import openvino.properties.streams as streams
from transformers import AutoTokenizer, GenerationConfig
import torch
# Configure optimization settings
ov_config = {
hints.performance_mode(): hints.PerformanceMode.LATENCY,
streams.num(): "1",
props.cache_dir(): "",
# "DYNAMIC_QUANTIZATION_GROUP_SIZE": "32", # Commented out for testing
# "KV_CACHE_PRECISION": "u8" # Commented out for testing
}
# Load model with optimizations
model_name_or_id = "AI4Chem/CHEMLLM-2b-1_5"
tokenizer = AutoTokenizer.from_pretrained(model_name_or_id, trust_remote_code=True)
# Convert and optimize model
model = OVModelForCausalLM.from_pretrained(
model_name_or_id,
export=True,
ov_config=ov_config,
device="CPU",
torch_dtype=torch.float32, # Changed to torch.float32
trust_remote_code=True # Include if the model uses custom code
)
# Set pad_token_id if not set
if model.config.pad_token_id is None:
model.config.pad_token_id = tokenizer.eos_token_id
end_time = time.time()
execution_time = end_time - start_time
print(f"Model load and optimization time: {execution_time} seconds")
# Inference
start_time = time.time()
prompt = "Predict the aqueous solubility (in mg/mL) and explain the factors affecting solubility for: CC1=CC=C(C=C1)C(=O)CCCN"
inputs = tokenizer(prompt, return_tensors="pt", padding=True, truncation=True, max_length=512)
generation_config = GenerationConfig(
do_sample=False, # Set to False to use greedy decoding for testing
# top_k=10, # Optionally comment out when do_sample=False
temperature=1.0, # Set to 1.0 for deterministic results
max_new_tokens=500,
repetition_penalty=1.0, # Set to 1.0 or remove
pad_token_id=tokenizer.eos_token_id
)
# Generate output with the optimized model
outputs = model.generate(
**inputs,
generation_config=generation_config
)
generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
print(generated_text)
end_time = time.time()
execution_time = end_time - start_time
print(f"Inference time: {execution_time} seconds")
Note: After making these changes, test the code to see if the error is resolved. If it is, you can gradually reintroduce optimizations or settings (like quantization or sampling) to find a balance between performance and stability.