Skip to content
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

[Bugfix] Fix Ray Metrics API usage #6354

Merged
merged 5 commits into from
Jul 17, 2024
Merged

Conversation

Yard1
Copy link
Collaborator

@Yard1 Yard1 commented Jul 11, 2024

Fixes RayMetrics not working correctly due to wrong API usage.

Fixes #5925 (comment) cc @kousun12

PR Checklist (Click to Expand)

Thank you for your contribution to vLLM! Before submitting the pull request, please ensure the PR meets the following criteria. This helps vLLM maintain the code quality and improve the efficiency of the review process.

PR Title and Classification

Only specific types of PRs will be reviewed. The PR title is prefixed appropriately to indicate the type of change. Please use one of the following:

  • [Bugfix] for bug fixes.
  • [CI/Build] for build or continuous integration improvements.
  • [Doc] for documentation fixes and improvements.
  • [Model] for adding a new model or improving an existing model. Model name should appear in the title.
  • [Frontend] For changes on the vLLM frontend (e.g., OpenAI API server, LLM class, etc.)
  • [Kernel] for changes affecting CUDA kernels or other compute kernels.
  • [Core] for changes in the core vLLM logic (e.g., LLMEngine, AsyncLLMEngine, Scheduler, etc.)
  • [Hardware][Vendor] for hardware-specific changes. Vendor name should appear in the prefix (e.g., [Hardware][AMD]).
  • [Misc] for PRs that do not fit the above categories. Please use this sparingly.

Note: If the PR spans more than one category, please include all relevant prefixes.

Code Quality

The PR need to meet the following code quality standards:

  • We adhere to Google Python style guide and Google C++ style guide.
  • Pass all linter checks. Please use format.sh to format your code.
  • The code need to be well-documented to ensure future contributors can easily understand the code.
  • Include sufficient tests to ensure the project to stay correct and robust. This includes both unit tests and integration tests.
  • Please add documentation to docs/source/ if the PR modifies the user-facing behaviors of vLLM. It helps vLLM user understand and utilize the new features or changes.

Notes for Large Changes

Please keep the changes as concise as possible. For major architectural changes (>500 LOC excluding kernel/data/config/test), we would expect a GitHub issue (RFC) discussing the technical design and justification. Otherwise, we will tag it with rfc-required and might not go through the PR.

What to Expect for the Reviews

The goal of the vLLM team is to be a transparent reviewing machine. We would like to make the review process transparent and efficient and make sure no contributor feel confused or frustrated. However, the vLLM team is small, so we need to prioritize some PRs over others. Here is what you can expect from the review process:

  • After the PR is submitted, the PR will be assigned to a reviewer. Every reviewer will pick up the PRs based on their expertise and availability.
  • After the PR is assigned, the reviewer will provide status update every 2-3 days. If the PR is not reviewed within 7 days, please feel free to ping the reviewer or the vLLM team.
  • After the review, the reviewer will put an action-required label on the PR if there are changes required. The contributor should address the comments and ping the reviewer to re-review the PR.
  • Please respond to all comments within a reasonable time frame. If a comment isn't clear or you disagree with a suggestion, feel free to ask for clarification or discuss the suggestion.

Thank You

Finally, thank you for taking the time to read these guidelines and for your interest in contributing to vLLM. Your contributions make vLLM a great tool for everyone!

@Yard1 Yard1 changed the title [Misc] Fix Ray Metrics [Bugfix] Fix Ray Metrics Jul 11, 2024
@Yard1 Yard1 changed the title [Bugfix] Fix Ray Metrics [Bugfix] Fix Ray Metrics API usage Jul 11, 2024
@simon-mo simon-mo requested a review from rkooo567 July 11, 2024 23:23
Copy link

@kousun12 kousun12 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks great. thank you!

@@ -168,8 +246,9 @@ def _unregister_vllm_metrics(self) -> None:
# No-op on purpose
pass


# end-metrics-definitions
def _create_info_cache_config(self) -> None:

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks for fixing this as well!

@bchandarr
Copy link

With the new stat_loggers param in LLMEngine, I get serialise error (in ray remote/ray actor) with passing the dict of RayPrometheusStatLogger object. Can this be updated to specify "ray" or "prometheus" as input and create PrometheusStatLogger or RayPrometheusStatLogger?

@Yard1
Copy link
Collaborator Author

Yard1 commented Jul 15, 2024

@bchandarr do you have a repro?

@bchandarr
Copy link

@bchandarr do you have a repro?

I use custom AsyncLLMEngine with from_engine_args function and tried like the code below, not sure this is the right way to use it.

  def from_engine_args(
      cls,
      engine_args: AsyncEngineArgs,
      start_engine_loop: bool = True,
      usage_context: UsageContext = UsageContext.ENGINE_CONTEXT,
  ) -> "AsyncLLMEngine":

     # rest of the original code here

      # create loggers
      stat_loggers = {
          "raymetrics":
          RayPrometheusStatLogger(
              local_interval=_LOCAL_LOGGING_INTERVAL_SEC,
              labels=dict(model_name=model_config.served_model_name),
              max_model_len=model_config.max_model_len),
      }

      # Create the async LLM engine.
      engine = cls(
          distributed_executor_backend == "ray",
          # parallel_config.worker_use_ray,
          engine_args.engine_use_ray,
          **engine_config.to_dict(),
          executor_class=executor_class,
          log_requests=not engine_args.disable_log_requests,
          log_stats=not engine_args.disable_log_stats,
          max_log_len=engine_args.max_log_len,
          start_engine_loop=start_engine_loop,
          usage_context=usage_context,
          stat_loggers=stat_loggers,
      )
      return engine

the error call stack.

  File "/home/ray/projects/llm_serve/app/backends/vllm/vllm_engine.py", line 131, in from_engine_args
    engine = cls(
  File "/home/ray/anaconda3/lib/python3.10/site-packages/vllm/engine/async_llm_engine.py", line 360, in __init__
    self.engine = self._init_engine(*args, **kwargs)
  File "/home/ray/anaconda3/lib/python3.10/site-packages/vllm/engine/async_llm_engine.py", line 507, in _init_engine
    return engine_class(*args, **kwargs)
  File "/home/ray/anaconda3/lib/python3.10/site-packages/ray/actor.py", line 715, in remote
    return self._remote(args=args, kwargs=kwargs, **self._default_options)
  File "/home/ray/anaconda3/lib/python3.10/site-packages/ray/actor.py", line 1161, in _remote
    actor_id = worker.core_worker.create_actor(
TypeError: Could not serialize the argument {'raymetrics': <llm_serve.app.backends.vllm.metrics.RayPrometheusStatLogger object at 0x7f008e183d90>} for a task or actor llm_serve.app.backends.vllm.vllm_engine.CustomLLMEngine.__init__:
================================================================================
Checking Serializability of {'raymetrics': <llm_serve.app.backends.vllm.metrics.RayPrometheusStatLogger object at 0x7f008e183d90>}
================================================================================
�[31m!!! FAIL�[39m serialization: cannot pickle '_thread.lock' object
WARNING: Did not find non-serializable object in {'raymetrics': <llm_serve.app.backends.vllm.metrics.RayPrometheusStatLogger object at 0x7f008e183d90>}. This may be an oversight.
================================================================================
Variable: 

	�[1mFailTuple({'raymetrics': <llm_serve.app.backends.vllm.metrics.RayPrometheusStatLogger object at 0x7f008e183d90>} [obj={'raymetrics': <llm_serve.app.backends.vllm.metrics.RayPrometheusStatLogger object at 0x7f008e183d90>}, parent=None])�[0m

was found to be non-serializable. There may be multiple other undetected variables that were non-serializable. 
Consider either removing the instantiation/imports of these variables or moving the instantiation into the scope of the function/class. 
================================================================================
Check https://docs.ray.io/en/master/ray-core/objects/serialization.html#troubleshooting for more information.
If you have any suggestions on how to improve this error message, please reach out to the Ray developers on github.com/ray-project/ray/issues/
================================================================================

@bchandarr
Copy link

@Yard1 Also I tried running the test script in v0.5.1 and get error from prometheus_client/registry.py

import ray
from vllm import EngineArgs, LLMEngine
from vllm.engine.arg_utils import AsyncEngineArgs
from vllm.engine.async_llm_engine import AsyncLLMEngine
from vllm.engine.metrics import RayPrometheusStatLogger
from vllm.sampling_params import SamplingParams

def test_engine_log_metrics_ray(
    example_prompts = ["prompt"],
    model: str = “some-model",
    dtype: str = "half",
    max_tokens: int = 16,
) -> None:
    # This test is quite weak - it only checks that we can use
    # RayPrometheusStatLogger without exceptions.
    # Checking whether the metrics are actually emitted is unfortunately
    # non-trivial.

    # We have to run in a Ray task for Ray metrics to be emitted correctly
    @ray.remote(num_gpus=1)
    def _inner():

        class _RayPrometheusStatLogger(RayPrometheusStatLogger):

            def __init__(self, *args, **kwargs):
                self._i = 0
                super().__init__(*args, **kwargs)

            def log(self, *args, **kwargs):
                self._i += 1
                return super().log(*args, **kwargs)

        engine_args = EngineArgs(
            model=model,
            dtype=dtype,
            disable_log_stats=False,
        )
        engine = LLMEngine.from_engine_args(engine_args)
        logger = _RayPrometheusStatLogger(
            local_interval=0.5,
            labels=dict(model_name=engine.model_config.served_model_name),
            max_model_len=engine.model_config.max_model_len)
        engine.add_logger("ray", logger)
        for i, prompt in enumerate(example_prompts):
            engine.add_request(
                f"request-id-{i}",
                prompt,
                SamplingParams(max_tokens=max_tokens),
            )
        while engine.has_unfinished_requests():
            engine.step()
        assert logger._i > 0, ".log must be called at least once"

    ray.get(_inner.remote())

test_engine_log_metrics_ray()
(venv) ray@raycluster:~/$ python test.py
(_inner pid=11587) INFO llm_engine.py:169] Initializing an LLM engine (v0.5.1) with config: model=‘some-model’, speculative_config=None, tokenizer=‘some-modelchat', skip_tokenizer_init=False, tokenizer_mode=auto, revision=None, rope_scaling=None, rope_theta=None, tokenizer_revision=None, trust_remote_code=False, dtype=torch.float16, max_seq_len=4096, download_dir=None, load_format=LoadFormat.AUTO, tensor_parallel_size=1, pipeline_parallel_size=1, disable_custom_all_reduce=False, quantization=None, enforce_eager=False, kv_cache_dtype=auto, quantization_param_path=None, device_config=cuda, decoding_config=DecodingConfig(guided_decoding_backend='outlines'), observability_config=ObservabilityConfig(otlp_traces_endpoint=None), seed=0, served_model_name=some-model, use_v2_block_manager=False, enable_prefix_caching=False)
(_inner pid=11587) INFO  model_runner.py:255] Loading model weights took 12.5523 GB
(_inner pid=11587) INFO  gpu_executor.py:84] # GPU blocks: 7447, # CPU blocks: 512
(_inner pid=11587) INFO  model_runner.py:924] Capturing the model for CUDA graphs. This may lead to unexpected consequences if the model is not static. To run the model in eager mode, set 'enforce_eager=True' or use '--enforce-eager' in the CLI.
(_inner pid=11587) INFO  model_runner.py:928] CUDA graphs can take additional 1~3 GiB memory per GPU. If you are running out of memory, consider decreasing `gpu_memory_utilization` or enforcing eager mode. You can also reduce the `max_num_seqs` as needed to decrease memory usage.
(_inner pid=11587) INFO  model_runner.py:1117] Graph capturing finished in 5 secs.
Traceback (most recent call last):
  File "/home/ray/test.py", line 60, in <module>
    test_engine_log_metrics_ray()
  File "/home/ray/test.py", line 58, in test_engine_log_metrics_ray
    ray.get(_inner.remote())
  File "/home/ray/anaconda3/lib/python3.10/site-packages/ray/_private/auto_init_hook.py", line 21, in auto_init_wrapper
    return fn(*args, **kwargs)
  File "/home/ray/anaconda3/lib/python3.10/site-packages/ray/_private/client_mode_hook.py", line 103, in wrapper
    return func(*args, **kwargs)
  File "/home/ray/anaconda3/lib/python3.10/site-packages/ray/_private/worker.py", line 2623, in get
    values, debugger_breakpoint = worker.get_objects(object_refs, timeout=timeout)
  File "/home/ray/anaconda3/lib/python3.10/site-packages/ray/_private/worker.py", line 861, in get_objects
    raise value.as_instanceof_cause()
ray.exceptions.RayTaskError(ValueError): ray::_inner() (pid=11587, ip=192.128.18.68)
  File "/home/ray/projects/llm_serve/python/test.py", line 43, in _inner
    logger = _RayPrometheusStatLogger(
  File "/home/ray/projects/llm_serve/python/test.py", line 31, in __init__
    super().__init__(*args, **kwargs)
  File "/home/ray/anaconda3/lib/python3.10/site-packages/vllm/engine/metrics.py", line 341, in __init__
    self.metrics = self._metrics_cls(labelnames=list(labels.keys()),
  File "/home/ray/anaconda3/lib/python3.10/site-packages/vllm/engine/metrics.py", line 165, in __init__
    super().__init__(labelnames, max_model_len)
  File "/home/ray/anaconda3/lib/python3.10/site-packages/vllm/engine/metrics.py", line 40, in __init__
    self.info_cache_config = prometheus_client.Info(
  File "/home/ray/anaconda3/lib/python3.10/site-packages/prometheus_client/metrics.py", line 155, in __init__
    registry.register(self)
  File "/home/ray/anaconda3/lib/python3.10/site-packages/prometheus_client/registry.py", line 43, in register
    raise ValueError(
ValueError: Duplicated timeseries in CollectorRegistry: {'vllm:cache_config', 'vllm:cache_config_info'}

@Yard1
Copy link
Collaborator Author

Yard1 commented Jul 16, 2024

thanks will take a look

@Yard1
Copy link
Collaborator Author

Yard1 commented Jul 16, 2024

@bchandarr I cannot reproduce either issue. The logger is serializable for me, and I am not getting the error you got in the second issue. Not sure what's going on here.

Note I was running with the changes from this PR. It's expected that things do not work without them.

@Yard1 Yard1 enabled auto-merge (squash) July 16, 2024 23:51
@github-actions github-actions bot added the ready ONLY add when PR is ready to merge/full CI is needed label Jul 16, 2024
@Yard1 Yard1 merged commit 5f0b993 into vllm-project:main Jul 17, 2024
72 checks passed
fialhocoelho pushed a commit to opendatahub-io/vllm that referenced this pull request Jul 19, 2024
xjpang pushed a commit to xjpang/vllm that referenced this pull request Jul 24, 2024
gnpinkert pushed a commit to gnpinkert/vllm that referenced this pull request Jul 26, 2024
Alvant pushed a commit to compressa-ai/vllm that referenced this pull request Oct 26, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
ready ONLY add when PR is ready to merge/full CI is needed
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants