To modify your script to run entirely on the CPU, you'll need to make a few adjustments:
-
Remove GPU-Specific Configurations:
- Decorator: Remove the
@spaces.GPU decorator since it's intended for GPU usage.
- Device Mapping: Change the
device_map parameter from "auto" to "cpu" to ensure the model loads on the CPU.
- Data Types: While
torch_dtype="auto" generally works, you can explicitly set it to a CPU-friendly type like torch.float32 if needed.
-
Ensure Tensors Are on the CPU:
- Remove or adjust any
.to(model.device) calls to ensure tensors remain on the CPU.
Here's the revised code with these changes applied:
import spaces # Ensure this is necessary; if not, consider removing it.
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch # Make sure to import torch if not already
model_name = "happzy2633/qwen2.5-7b-ins-v3"
# Load the model on CPU
model = AutoModelForCausalLM.from_pretrained(
model_name,
torch_dtype=torch.float32, # Explicitly set dtype if needed
device_map="cpu"
)
tokenizer = AutoTokenizer.from_pretrained(model_name)
# Remove the GPU decorator since we're using CPU
# @spaces.GPU
def api_call(messages):
text = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True
)
# Tokenize without transferring to model.device
model_inputs = tokenizer([text], return_tensors="pt")
# Ensure inputs are on CPU
model_inputs = {k: v.to("cpu") for k, v in model_inputs.items()}
# Generate text
generated_ids = model.generate(
**model_inputs,
max_new_tokens=8192
)
# Separate generated tokens from input tokens
generated_ids = [
output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs['input_ids'], generated_ids)
]
# Decode the generated tokens
response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
return response
def call_gpt(history, prompt):
return api_call(history + [{"role": "user", "content": prompt}])
if __name__ == "__main__":
messages = [{"role": "user", "content": "Hello, how are you?"}]
print(api_call(messages))
breakpoint()
Detailed Changes Explained:
-
Removing the GPU Decorator:
# @spaces.GPU
def api_call(messages):
...
- The
@spaces.GPU decorator is removed to prevent any GPU-specific optimizations or allocations.
-
Loading the Model on CPU:
model = AutoModelForCausalLM.from_pretrained(
model_name,
torch_dtype=torch.float32, # Changed from "auto" to a specific dtype if necessary
device_map="cpu"
)
- Setting
device_map="cpu" ensures that the model is loaded on the CPU.
torch_dtype is explicitly set to torch.float32 for clarity, although "auto" often defaults appropriately.
-
Ensuring Tensors Are on CPU:
model_inputs = {k: v.to("cpu") for k, v in model_inputs.items()}
- This line ensures that all input tensors are explicitly on the CPU, preventing any accidental GPU allocations.
-
Additional Considerations:
- Performance: Running large models on the CPU can be significantly slower and may require more memory. Ensure your CPU has enough resources to handle the model.
- Dependencies: Ensure that all dependencies (
spaces, transformers, torch, etc.) are correctly installed and compatible with CPU usage.
- Error Handling: You might want to add error handling to manage scenarios where the model might not fit into the available CPU memory.
Optional: Removing the spaces Module
If the spaces module is solely used for the @spaces.GPU decorator and isn't needed elsewhere in your code, you can consider removing it entirely to simplify your script:
#from spaces import GPU # Remove this import if not needed
And ensure that any other references to spaces are also removed or adjusted accordingly.
Final Notes
Running large language models like qwen2.5-7b-ins-v3 on the CPU can be resource-intensive and may lead to long inference times. If you encounter performance issues, consider the following:
- Model Quantization: Reducing the model size by quantizing it can help improve performance on CPUs.
- Optimized Libraries: Utilize optimized libraries like Intel® Extension for PyTorch for better CPU performance.
- Batch Processing: If possible, process inputs in batches to maximize CPU utilization.
By applying these changes, your script should run entirely on the CPU without attempting to utilize GPU resources.