Repository navigation
Reduce vRAM usage during generation by allowing to transfer logits to CPU #40870
New issue
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
Closed
SamuelBarryCS
wants to merge
8
commits into
huggingface:main
from
SamuelBarryCS:transfer-logits-to-cpu
Closed
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
1d91cc9
Add CPU offloading option
SamuelBarryCS 8ace4f7
Lint
SamuelBarryCS d0b381d
Add test
SamuelBarryCS b336858
Push benchmarking script
SamuelBarryCS d49c7f5
Update test file
SamuelBarryCS 7140978
Update config
SamuelBarryCS 1e180bf
Merge branch 'main' into transfer-logits-to-cpu
SamuelBarryCS d1691e5
Update tests
SamuelBarryCS File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,123 @@ | ||
| """ | ||
| Test script to evaluate memory efficiency of CPU logits offloading. | ||
| """ | ||
|
|
||
| import gc | ||
| import time | ||
|
|
||
| import torch | ||
|
|
||
| from transformers import AutoModelForCausalLM, AutoTokenizer | ||
|
|
||
|
|
||
| def get_gpu_memory_mb(): | ||
| """Get current GPU memory usage in MB.""" | ||
| return torch.cuda.memory_allocated() / 1024 / 1024 | ||
|
|
||
|
|
||
| def clear_memory(): | ||
| """Clear GPU memory.""" | ||
| torch.cuda.empty_cache() | ||
| gc.collect() | ||
|
|
||
|
|
||
| def test_memory_scenario(): | ||
| """Test memory efficiency of CPU offloading with gpt2-large.""" | ||
|
|
||
| model_name = "gpt2-large" | ||
| max_new_tokens = 1000 | ||
| prompt_text = "This essay will start with a detailed and verbose introduction to deep learning. To start with," | ||
|
|
||
| print(f"Testing model: {model_name}") | ||
| print(f"Tokens to generate: {max_new_tokens}") | ||
| print(f"Device: {torch.cuda.get_device_name()}") | ||
|
|
||
| # Load model | ||
| print("Loading model...") | ||
| tokenizer = AutoTokenizer.from_pretrained(model_name) | ||
| model = AutoModelForCausalLM.from_pretrained(model_name, dtype=torch.float16).cuda() | ||
|
|
||
| if tokenizer.pad_token is None: | ||
| tokenizer.pad_token = tokenizer.eos_token | ||
|
|
||
| inputs = tokenizer(prompt_text, return_tensors="pt") | ||
| inputs = {k: v.cuda() for k, v in inputs.items()} | ||
|
|
||
|
|
||
| # Test WITHOUT CPU offloading | ||
| clear_memory() | ||
| print("\nTesting without CPU offloading...") | ||
|
|
||
| initial_memory = get_gpu_memory_mb() | ||
| start_time = time.time() | ||
|
|
||
| with torch.no_grad(): | ||
| outputs_gpu = model.generate( | ||
| **inputs, | ||
| max_new_tokens=max_new_tokens, | ||
| output_scores=True, | ||
| output_logits=True, | ||
| return_dict_in_generate=True, | ||
| offload_logits_to_cpu=False, | ||
| do_sample=False, | ||
| pad_token_id=tokenizer.eos_token_id, | ||
| ) | ||
|
|
||
| gpu_time = time.time() - start_time | ||
| gpu_peak = get_gpu_memory_mb() | ||
| gpu_increase = gpu_peak - initial_memory | ||
|
|
||
| print(f"Initial memory: {initial_memory:.1f} MB") | ||
| print(f"Peak memory: {gpu_peak:.1f} MB") | ||
| print(f"Memory increase: {gpu_increase:.1f} MB") | ||
| print(f"Generation time: {gpu_time:.2f}s") | ||
| print(f"Tokens generated: {len(outputs_gpu.logits) if outputs_gpu.logits else 0}") | ||
|
|
||
| # Store for comparison | ||
| gpu_sequences = outputs_gpu.sequences.clone() | ||
| del outputs_gpu | ||
| clear_memory() | ||
|
|
||
| # Test WITH CPU offloading | ||
| print("\nTesting with CPU offloading...") | ||
|
|
||
| initial_memory = get_gpu_memory_mb() | ||
| start_time = time.time() | ||
|
|
||
| with torch.no_grad(): | ||
| outputs_cpu = model.generate( | ||
| **inputs, | ||
| max_new_tokens=max_new_tokens, | ||
| output_scores=True, | ||
| output_logits=True, | ||
| return_dict_in_generate=True, | ||
| offload_logits_to_cpu=True, | ||
| do_sample=False, | ||
| pad_token_id=tokenizer.eos_token_id, | ||
| ) | ||
|
|
||
| cpu_time = time.time() - start_time | ||
| cpu_peak = get_gpu_memory_mb() | ||
| cpu_increase = cpu_peak - initial_memory | ||
|
|
||
| print(f"Initial memory: {initial_memory:.1f} MB") | ||
| print(f"Peak memory: {cpu_peak:.1f} MB") | ||
| print(f"Memory increase: {cpu_increase:.1f} MB") | ||
| print(f"Generation time: {cpu_time:.2f}s") | ||
| print(f"Tokens generated: {len(outputs_cpu.logits) if outputs_cpu.logits else 0}") | ||
|
|
||
| # Analysis | ||
| memory_saved = gpu_increase - cpu_increase | ||
| reduction_pct = (memory_saved / gpu_increase * 100) if gpu_increase > 0 else 0 | ||
| time_overhead = ((cpu_time - gpu_time) / gpu_time * 100) if gpu_time > 0 else 0 | ||
| sequences_match = torch.equal(gpu_sequences, outputs_cpu.sequences) | ||
|
|
||
| print("\nResults:") | ||
| print("Number of tokens generated:", outputs_cpu.sequences.shape[1]) | ||
| print(f"Memory saved: {memory_saved:.1f} MB") | ||
| print(f"Memory reduction: {reduction_pct:.1f}%") | ||
| print(f"Time overhead: {time_overhead:+.1f}%") | ||
| print(f"Sequences match: {sequences_match}") | ||
|
|
||
| if __name__ == "__main__": | ||
| test_memory_scenario() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
(This script will of course be deleted before merging)