Skip to content

Add support for CB with native transformers #3471

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

Open
wants to merge 13 commits into
base: main
Choose a base branch
from

Conversation

ArthurZucker
Copy link

@ArthurZucker ArthurZucker commented May 20, 2025

What does this PR do?

Testing this with:

from datasets import load_dataset
from trl import GRPOTrainer

dataset = load_dataset("trl-lib/tldr", split="train")

# Dummy reward function: count the number of unique characters in the completions
def reward_num_unique_chars(completions, **kwargs):
    return [len(set(c)) for c in completions]

trainer = GRPOTrainer(
    model="Qwen/Qwen2-0.5B-Instruct",
    reward_funcs=reward_num_unique_chars,
    train_dataset=dataset,
)
trainer.train()

@ArthurZucker ArthurZucker marked this pull request as ready for review May 22, 2025 15:49
@ArthurZucker
Copy link
Author

PR is merged to transformers!

@HuggingFaceDocBuilderDev

The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

@qgallouedec
Copy link
Member

I'm trying CB right now. Currently, when running (from here):

import time

import datasets
import torch

from transformers import AutoModelForCausalLM, AutoTokenizer
from transformers.generation import GenerationConfig


torch.set_float32_matmul_precision("high")

model_id = "meta-llama/Llama-3.2-3b-Instruct"
model = AutoModelForCausalLM.from_pretrained(
    model_id, attn_implementation="sdpa_paged", torch_dtype=torch.bfloat16, device_map="auto"
).eval()
tokenizer = AutoTokenizer.from_pretrained(model_id, padding_side="left")

generation_config = GenerationConfig(
    max_new_tokens=512,
    eos_token_id=tokenizer.eos_token_id,
    pad_token_id=tokenizer.pad_token_id,
    use_cache=False,
    num_blocks=2048,
    block_size=128,
    do_sample=True,
    max_batch_tokens=1024,  # Maximum number of tokens to process in a single batch
    scheduler="prefill_first",
)

train_dataset = datasets.load_dataset("openai/gsm8k", "socratic", split="test")

# --- Example 1: Simple Version using generate_batch ---
print("--- Running CB Generation Example ---")


def tokenize_function(examples):
    return tokenizer(examples["question"])


tokenized_datasets = train_dataset.map(tokenize_function, batched=True)
simple_batch_inputs = [item["input_ids"] for item in tokenized_datasets]

start_time_simple = time.time()
# model.forward = torch.compile(model.forward, mode="max-autotune-no-cudagraphs", fullgraph=True)
batch_outputs = model.generate_batch(
    inputs=simple_batch_inputs,
    generation_config=generation_config,
)
end_time_simple = time.time()

for request in batch_outputs:
    input_text = tokenizer.decode(batch_outputs[request].prompt_ids, skip_special_tokens=False)
    try:
        output_text = tokenizer.decode(batch_outputs[request].generated_tokens, skip_special_tokens=False)
    except Exception as e:
        print(f"Decoding failed for request {request}: {e}")
        output_text = tokenizer.decode(batch_outputs[request].generated_tokens[1:], skip_special_tokens=False)
    if len(output_text) > 0:
        print("-" * 20)
        print(f"{request} Input:  {input_text}")
        print(f"{request} Output: {output_text}")
    else:
        print("", end="\r\r\r\r")
print("-" * 20)
print("--- Finished CB Generation Example ---\n\n")


print(f"CB generation took: {end_time_simple - start_time_simple:.2f} seconds")

I'm getting

$ /fsx/qgallouedec/miniconda3/envs/trl/bin/python /fsx/qgallouedec/transformers/demo_cb.py
Loading checkpoint shards: 100%|████████████████████████████████████| 2/2 [00:00<00:00,  2.23it/s]
--- Running CB Generation Example ---
Error in generation loop: Meter.create_histogram() got an unexpected keyword argument 'explicit_bucket_boundaries_advisory'
Traceback (most recent call last):
  File "/fsx/qgallouedec/transformers/src/transformers/generation/continuous_batching.py", line 1256, in _run_generation_loop
    batch_processor = ContinuousBatchProcessor(
                      ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/fsx/qgallouedec/transformers/src/transformers/utils/metrics.py", line 75, in init_with_tracer
    original_init(self, *args, **kwargs)
  File "/fsx/qgallouedec/transformers/src/transformers/generation/continuous_batching.py", line 750, in __init__
    self.metrics = ContinuousBatchProcessorMetrics(self.max_batch_tokens)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/fsx/qgallouedec/transformers/src/transformers/utils/metrics.py", line 75, in init_with_tracer
    original_init(self, *args, **kwargs)
  File "/fsx/qgallouedec/transformers/src/transformers/utils/metrics.py", line 201, in __init__
    self._setup_metrics()
  File "/fsx/qgallouedec/transformers/src/transformers/utils/metrics.py", line 215, in _setup_metrics
    self.ttft_histogram = self.meter.create_histogram(
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Meter.create_histogram() got an unexpected keyword argument 'explicit_bucket_boundaries_advisory'
Solving 1319 requests:   0%|                                        | 0/1319 [00:00<?, ?request/s]Error in generation loop: Meter.create_histogram() got an unexpected keyword argument 'explicit_bucket_boundaries_advisory'
Traceback (most recent call last):
  File "/fsx/qgallouedec/transformers/src/transformers/generation/continuous_batching.py", line 1256, in _run_generation_loop
    batch_processor = ContinuousBatchProcessor(
                      ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/fsx/qgallouedec/transformers/src/transformers/utils/metrics.py", line 75, in init_with_tracer
    original_init(self, *args, **kwargs)
  File "/fsx/qgallouedec/transformers/src/transformers/generation/continuous_batching.py", line 750, in __init__
    self.metrics = ContinuousBatchProcessorMetrics(self.max_batch_tokens)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/fsx/qgallouedec/transformers/src/transformers/utils/metrics.py", line 75, in init_with_tracer
    original_init(self, *args, **kwargs)
  File "/fsx/qgallouedec/transformers/src/transformers/utils/metrics.py", line 201, in __init__
    self._setup_metrics()
  File "/fsx/qgallouedec/transformers/src/transformers/utils/metrics.py", line 215, in _setup_metrics
    self.ttft_histogram = self.meter.create_histogram(
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Meter.create_histogram() got an unexpected keyword argument 'explicit_bucket_boundaries_advisory'
Generation thread terminated unexpectedly.                                                        
Solving 1319 requests:   0%|                                        | 0/1319 [00:01<?, ?request/s]Generation thread terminated unexpectedly.
Solving 1319 requests:   0%|                                        | 0/1319 [00:01<?, ?request/s]
CB generation took: 1.01 seconds
Exception while exporting Span batch.
Traceback (most recent call last):
  File "/admin/home/quentin_gallouedec/.local/lib/python3.12/site-packages/urllib3/connection.py", line 198, in _new_conn
    sock = connection.create_connection(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/admin/home/quentin_gallouedec/.local/lib/python3.12/site-packages/urllib3/util/connection.py", line 85, in create_connection
    raise err
  File "/admin/home/quentin_gallouedec/.local/lib/python3.12/site-packages/urllib3/util/connection.py", line 73, in create_connection
    sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/admin/home/quentin_gallouedec/.local/lib/python3.12/site-packages/urllib3/connectionpool.py", line 787, in urlopen
    response = self._make_request(
               ^^^^^^^^^^^^^^^^^^^
  File "/admin/home/quentin_gallouedec/.local/lib/python3.12/site-packages/urllib3/connectionpool.py", line 493, in _make_request
    conn.request(
  File "/admin/home/quentin_gallouedec/.local/lib/python3.12/site-packages/urllib3/connection.py", line 445, in request
    self.endheaders()
  File "/fsx/qgallouedec/miniconda3/envs/trl/lib/python3.12/http/client.py", line 1333, in endheaders
    self._send_output(message_body, encode_chunked=encode_chunked)
  File "/fsx/qgallouedec/miniconda3/envs/trl/lib/python3.12/http/client.py", line 1093, in _send_output
    self.send(msg)
  File "/fsx/qgallouedec/miniconda3/envs/trl/lib/python3.12/http/client.py", line 1037, in send
    self.connect()
  File "/admin/home/quentin_gallouedec/.local/lib/python3.12/site-packages/urllib3/connection.py", line 276, in connect
    self.sock = self._new_conn()
                ^^^^^^^^^^^^^^^^
  File "/admin/home/quentin_gallouedec/.local/lib/python3.12/site-packages/urllib3/connection.py", line 213, in _new_conn
    raise NewConnectionError(
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPConnection object at 0x7fbafbb615e0>: Failed to establish a new connection: [Errno 111] Connection refused

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/admin/home/quentin_gallouedec/.local/lib/python3.12/site-packages/requests/adapters.py", line 667, in send
    resp = conn.urlopen(
           ^^^^^^^^^^^^^
  File "/admin/home/quentin_gallouedec/.local/lib/python3.12/site-packages/urllib3/connectionpool.py", line 841, in urlopen
    retries = retries.increment(
              ^^^^^^^^^^^^^^^^^^
  File "/admin/home/quentin_gallouedec/.local/lib/python3.12/site-packages/urllib3/util/retry.py", line 519, in increment
    raise MaxRetryError(_pool, url, reason) from reason  # type: ignore[arg-type]
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='localhost', port=4318): Max retries exceeded with url: /v1/traces (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fbafbb615e0>: Failed to establish a new connection: [Errno 111] Connection refused'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/fsx/qgallouedec/miniconda3/envs/trl/lib/python3.12/site-packages/opentelemetry/sdk/trace/export/__init__.py", line 367, in _export_batch
    self.span_exporter.export(self.spans_list[:idx])  # type: ignore
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/fsx/qgallouedec/miniconda3/envs/trl/lib/python3.12/site-packages/opentelemetry/exporter/otlp/proto/http/trace_exporter/__init__.py", line 169, in export
    return self._export_serialized_spans(serialized_data)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/fsx/qgallouedec/miniconda3/envs/trl/lib/python3.12/site-packages/opentelemetry/exporter/otlp/proto/http/trace_exporter/__init__.py", line 139, in _export_serialized_spans
    resp = self._export(serialized_data)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/fsx/qgallouedec/miniconda3/envs/trl/lib/python3.12/site-packages/opentelemetry/exporter/otlp/proto/http/trace_exporter/__init__.py", line 114, in _export
    return self._session.post(
           ^^^^^^^^^^^^^^^^^^^
  File "/admin/home/quentin_gallouedec/.local/lib/python3.12/site-packages/requests/sessions.py", line 637, in post
    return self.request("POST", url, data=data, json=json, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/admin/home/quentin_gallouedec/.local/lib/python3.12/site-packages/requests/sessions.py", line 589, in request
    resp = self.send(prep, **send_kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/admin/home/quentin_gallouedec/.local/lib/python3.12/site-packages/requests/sessions.py", line 703, in send
    r = adapter.send(request, **kwargs)
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/admin/home/quentin_gallouedec/.local/lib/python3.12/site-packages/requests/adapters.py", line 700, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='localhost', port=4318): Max retries exceeded with url: /v1/traces (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fbafbb615e0>: Failed to establish a new connection: [Errno 111] Connection refused'))

any idea why?

@ArthurZucker
Copy link
Author

Yes! That's open telemetry having issues with the cluster. cc @McPatate let's fix this!

@ArthurZucker
Copy link
Author

(TLDR if you do pip freeze | grep telemetry and uninstall all of these it will dissapear

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants