in_source_id
stringlengths
13
58
issue
stringlengths
3
241k
before_files
listlengths
0
3
after_files
listlengths
0
3
pr_diff
stringlengths
109
107M
vllm-project__vllm-3211
Support for grammar It would be highly beneficial if the library could incorporate support for Grammar and GBNF files. https://github.com/ggerganov/llama.cpp/blob/master/grammars/README.md
[ { "content": "# Copyright 2024- the Outlines developers\n# This file is adapted from\n# https://github.com/outlines-dev/outlines/blob/main/outlines/serve/vllm.py\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may...
[ { "content": "# Copyright 2024- the Outlines developers\n# This file is adapted from\n# https://github.com/outlines-dev/outlines/blob/main/outlines/serve/vllm.py\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may...
diff --git a/tests/entrypoints/test_openai_server.py b/tests/entrypoints/test_openai_server.py index a5b2bf4c0f0c..86d9a85af80b 100644 --- a/tests/entrypoints/test_openai_server.py +++ b/tests/entrypoints/test_openai_server.py @@ -660,5 +660,55 @@ async def test_guided_decoding_type_error(server, client: openai.AsyncOpenAI): extra_body=dict(guided_regex=TEST_REGEX, guided_json=TEST_SCHEMA)) +async def test_response_format_json_object(server, client: openai.AsyncOpenAI): + resp = await client.chat.completions.create( + model=MODEL_NAME, + messages=[{ + "role": + "user", + "content": ('what is 1+1? please respond with a JSON object, ' + 'the format is {"result": 2}') + }], + response_format={"type": "json_object"}) + + content = resp.choices[0].message.content + loaded = json.loads(content) + assert loaded == {"result": 2}, loaded + + +async def test_guided_grammar(server, client: openai.AsyncOpenAI): + simple_sql_grammar = """ +start: select_statement + +select_statement: "SELECT" column "from" table "where" condition + +column: "col_1" | "col_2" +table: "table_1" | "table_2" +condition: column "=" number + +number: "1" | "2" +""" + + completion = await client.completions.create( + model=MODEL_NAME, + prompt=("Generate a sql state that select col_1 from " + "table_1 where it is equals to 1"), + temperature=1.0, + max_tokens=500, + extra_body=dict(guided_grammar=simple_sql_grammar)) + + content = completion.choices[0].text + + # use Lark to parse the output, and make sure it's a valid parse tree + from lark import Lark + parser = Lark(simple_sql_grammar) + parser.parse(content) + + # remove spaces for comparison b/c we removed them in the grammar + ground_truth = "SELECT col_1 from table_1 where col_1 = 1".replace(" ", "") + + assert content.strip() == ground_truth + + if __name__ == "__main__": pytest.main([__file__]) diff --git a/tests/kernels/test_prefix_prefill.py b/tests/kernels/test_prefix_prefill.py index 4d051593f40a..2b35335a9c92 100644 --- a/tests/kernels/test_prefix_prefill.py +++ b/tests/kernels/test_prefix_prefill.py @@ -36,8 +36,8 @@ def test_contexted_kv_attention( torch.cuda.manual_seed(0) torch.set_default_device(device) - # Need this, otherwise when we capture the graph the process for GPU 1 would run on both - # GPU0 and GPU1 and things would hang + # Need this, otherwise when we capture the graph the process for GPU 1 would + # run on both GPU0 and GPU1 and things would hang # # see also similar issue: https://github.com/Dao-AILab/flash-attention/issues/523 torch.cuda.set_device(device) diff --git a/vllm/entrypoints/openai/protocol.py b/vllm/entrypoints/openai/protocol.py index 26499b8d7a66..942188041161 100644 --- a/vllm/entrypoints/openai/protocol.py +++ b/vllm/entrypoints/openai/protocol.py @@ -55,6 +55,11 @@ class UsageInfo(BaseModel): completion_tokens: Optional[int] = 0 +class ResponseFormat(BaseModel): + # type must be "json_object" or "text" + type: str = Literal["text", "json_object"] + + class ChatCompletionRequest(BaseModel): model: str messages: List[Dict[str, str]] @@ -89,6 +94,8 @@ class ChatCompletionRequest(BaseModel): guided_json: Optional[Union[str, dict, BaseModel]] = None guided_regex: Optional[str] = None guided_choice: Optional[List[str]] = None + guided_grammar: Optional[str] = None + response_format: Optional[ResponseFormat] = None def to_sampling_params(self) -> SamplingParams: if self.logprobs and not self.top_logprobs: @@ -183,6 +190,8 @@ class CompletionRequest(BaseModel): guided_json: Optional[Union[str, dict, BaseModel]] = None guided_regex: Optional[str] = None guided_choice: Optional[List[str]] = None + guided_grammar: Optional[str] = None + response_format: Optional[ResponseFormat] = None def to_sampling_params(self): echo_without_generation = self.echo and self.max_tokens == 0 diff --git a/vllm/model_executor/guided_decoding.py b/vllm/model_executor/guided_decoding.py index 00984460d79a..bd09cf9cb6ee 100644 --- a/vllm/model_executor/guided_decoding.py +++ b/vllm/model_executor/guided_decoding.py @@ -6,19 +6,50 @@ from json import dumps as json_dumps from re import escape as regex_escape from typing import Union, Tuple + from pydantic import BaseModel +from transformers import PreTrainedTokenizerBase from vllm.entrypoints.openai.protocol import (CompletionRequest, ChatCompletionRequest) from vllm.model_executor.guided_logits_processors import (JSONLogitsProcessor, - RegexLogitsProcessor) + RegexLogitsProcessor, + CFGLogitsProcessor) class GuidedDecodingMode(Enum): JSON = "json" REGEX = "regex" CHOICE = "choice" + GRAMMAR = "grammar" + + +# https://github.com/outlines-dev/outlines/blob/main/outlines/grammars/json.lark +# the main difference is that we changed the start: value to +# start: object | array, so we are denying scalar values as the root of the +# JSON. Starting with scalars as the root seems to cause llama to generate +# without stop. +JSON_GRAMMAR = r""" +?start: object | array + +?value: object +| array +| UNESCAPED_STRING +| SIGNED_NUMBER -> number +| "true" -> true +| "false" -> false +| "null" -> null + +array : "[" [value ("," value)*] "]" +object : "{" [pair ("," pair)*] "}" +pair : UNESCAPED_STRING ":" value + +%import common.UNESCAPED_STRING +%import common.SIGNED_NUMBER +%import common.WS +%ignore WS +""" global_thread_pool = None # used for generating logits processor fsm @@ -57,9 +88,6 @@ def _get_guide_and_mode( ) -> Tuple[str, GuidedDecodingMode]: if request.guided_json: - if not isinstance(request.guided_json, (str, dict, BaseModel)): - raise TypeError("JSON schema must be str, dict, or BaseModel") - json = request.guided_json if isinstance(json, dict): # turn dict into hashable string @@ -69,33 +97,33 @@ def _get_guide_and_mode( # with the same fields will get hashed the same json = str(json.__signature__) return json, GuidedDecodingMode.JSON - elif request.guided_regex: - if not isinstance(request.guided_regex, str): - raise TypeError("Regex must be string") return request.guided_regex, GuidedDecodingMode.REGEX - elif request.guided_choice: - if not isinstance(request.guided_choice, list): - raise TypeError("Choices must be a list") - # choice just uses regex choices = [ regex_escape(str(choice)) for choice in request.guided_choice ] choices_regex = "(" + "|".join(choices) + ")" return choices_regex, GuidedDecodingMode.CHOICE - + elif request.guided_grammar: + return request.guided_grammar, GuidedDecodingMode.GRAMMAR + elif (request.response_format is not None + and request.response_format.type == "json_object"): + return JSON_GRAMMAR, GuidedDecodingMode.GRAMMAR else: return None, None @lru_cache(maxsize=32) -def _get_cached_logits_processor(guide: str, tokenizer, +def _get_cached_logits_processor(guide: str, + tokenizer: PreTrainedTokenizerBase, mode: GuidedDecodingMode): if mode == GuidedDecodingMode.JSON: return JSONLogitsProcessor(guide, tokenizer) elif mode == GuidedDecodingMode.REGEX or mode == GuidedDecodingMode.CHOICE: return RegexLogitsProcessor(guide, tokenizer) + elif mode == GuidedDecodingMode.GRAMMAR: + return CFGLogitsProcessor(guide, tokenizer) else: raise ValueError(f"Unknown guided decoding mode {mode}") diff --git a/vllm/model_executor/guided_logits_processors.py b/vllm/model_executor/guided_logits_processors.py index 76d41aa37dd7..2cd1ae157106 100644 --- a/vllm/model_executor/guided_logits_processors.py +++ b/vllm/model_executor/guided_logits_processors.py @@ -16,30 +16,60 @@ import json import math from collections import defaultdict -from typing import Union, DefaultDict, Dict, List, Optional +from typing import Union, DefaultDict, Dict, List, Optional, Callable import torch from pydantic import BaseModel -from outlines.fsm.fsm import RegexFSM +from transformers import PreTrainedTokenizerBase +from outlines.fsm.fsm import RegexFSM, CFGFSM from outlines.fsm.json_schema import build_regex_from_schema -class RegexLogitsProcessor: +class BaseLogitsProcessor: - def __init__(self, regex_string: str, tokenizer): - """Compile the FSM that drives the regex-structured generation. + def adapt_tokenizer(self, tokenizer: PreTrainedTokenizerBase): + """Adapt vLLM's tokenizer to use to compile the FSM. - Parameters - ---------- - regex_string - A string that represents a regular expression - tokenizer - The model's tokenizer + The API of Outlines tokenizers is slightly different to that of + `transformers`. The decoder of outlines, returns a list whereas + the decode of vLLM returns an str. To sync the vLLM decoder with + outlines internal api, the decoder should be adapted. In addition + we need to handle the missing spaces to Llama's tokenizer to be + able to compile FSMs for this model. """ - tokenizer = self.adapt_tokenizer(tokenizer) - fsm = RegexFSM(regex_string, tokenizer) - self.fsm = fsm + if getattr(tokenizer, "_outlines_adapted", False): + return tokenizer + + tokenizer.vocabulary = tokenizer.get_vocab() + tokenizer.special_tokens = set(tokenizer.all_special_tokens) + + def convert_token_to_string(token: str) -> str: + from transformers.file_utils import SPIECE_UNDERLINE + + string = tokenizer.convert_tokens_to_string([token]) + + # A hack to handle missing spaces to HF's Llama tokenizers + if token.startswith(SPIECE_UNDERLINE) or token == "<0x20>": + return " " + string + + return string + + def change_decoder( + decoder: Callable[[List[int]], str] + ) -> Callable[[List[int]], List[str]]: + """Sync vLLM's decoder with the outlines by returning list.""" + + def new_decoder(inp_tokens: List[int]) -> List[str]: + return [decoder(inp_tokens)] + + return new_decoder + + tokenizer.convert_token_to_string = convert_token_to_string + tokenizer.decode = change_decoder(tokenizer.decode) + setattr(tokenizer, "_outlines_adapted", True) # noqa: B010 + + return tokenizer def init_state(self): """Initialize the FSM states.""" @@ -69,38 +99,30 @@ def __call__(self, input_ids: List[int], return scores - def adapt_tokenizer(self, tokenizer): - """Adapt vLLM's tokenizer to use to compile the FSM. - - The API of Outlines tokenizers is slightly different to that of - `transformers`. In addition we need to handle the missing spaces to - Llama's tokenizer to be able to compile FSMs for this model. - - """ - tokenizer.vocabulary = tokenizer.get_vocab() - tokenizer.special_tokens = set(tokenizer.all_special_tokens) - - def convert_token_to_string(token: str) -> str: - from transformers.file_utils import SPIECE_UNDERLINE - string = tokenizer.convert_tokens_to_string([token]) +class RegexLogitsProcessor(BaseLogitsProcessor): - # A hack to handle missing spaces to HF's Llama tokenizers - if token.startswith(SPIECE_UNDERLINE) or token == "<0x20>": - return " " + string - - return string + def __init__(self, regex_string: str, tokenizer: PreTrainedTokenizerBase): + """Compile the FSM that drives the regex-structured generation. - tokenizer.convert_token_to_string = convert_token_to_string + Parameters + ---------- + regex_string + A string that represents a regular expression + tokenizer + The model's tokenizer - return tokenizer + """ + tokenizer = self.adapt_tokenizer(tokenizer) + fsm = RegexFSM(regex_string, tokenizer) + self.fsm = fsm class JSONLogitsProcessor(RegexLogitsProcessor): def __init__(self, schema: Union[str, Dict, BaseModel], - tokenizer, + tokenizer: PreTrainedTokenizerBase, whitespace_pattern: Optional[str] = None): """Compile the FSM that drives the JSON-guided generation. @@ -130,3 +152,21 @@ def __init__(self, f"the JSON Schema specification") regex_string = build_regex_from_schema(schema_str, whitespace_pattern) super().__init__(regex_string, tokenizer) + + +class CFGLogitsProcessor(BaseLogitsProcessor): + + def __init__(self, cfg: str, tokenizer: PreTrainedTokenizerBase): + """Compile the FSM that drives the context free grammar generation. + + Parameters + ---------- + cfg + A string that represents a context-free grammar + tokenizer + The model's tokenizer + + """ + tokenizer = self.adapt_tokenizer(tokenizer) + fsm = CFGFSM(cfg, tokenizer) + self.fsm = fsm
vllm-project__vllm-3239
Automatic Prefix Caching Bug If I enable automatic prefix caching, it occasionally crashes. ``` Future exception was never retrieved future: <Future finished exception=RuntimeError('step must be nonzero')> Traceback (most recent call last): File "/root/vllm/vllm/engine/async_llm_engine.py", line 29, in _raise_exception_on_finish task.result() File "/root/vllm/vllm/engine/async_llm_engine.py", line 412, in run_engine_loop has_requests_in_progress = await self.engine_step() File "/root/vllm/vllm/engine/async_llm_engine.py", line 391, in engine_step request_outputs = await self.engine.step_async() File "/root/vllm/vllm/engine/async_llm_engine.py", line 189, in step_async all_outputs = await self._run_workers_async( File "/root/vllm/vllm/engine/async_llm_engine.py", line 274, in _run_workers_async all_outputs = await asyncio.gather(*coros) File "/root/miniconda3/envs/vllm/lib/python3.10/concurrent/futures/thread.py", line 58, in run result = self.fn(*self.args, **self.kwargs) File "/root/miniconda3/envs/vllm/lib/python3.10/site-packages/torch/utils/_contextlib.py", line 115, in decorate_context return func(*args, **kwargs) File "/root/vllm/vllm/worker/worker.py", line 223, in execute_model output = self.model_runner.execute_model(seq_group_metadata_list, File "/root/miniconda3/envs/vllm/lib/python3.10/site-packages/torch/utils/_contextlib.py", line 115, in decorate_context return func(*args, **kwargs) File "/root/vllm/vllm/worker/model_runner.py", line 575, in execute_model lora_mapping) = self.prepare_input_tensors(seq_group_metadata_list) File "/root/vllm/vllm/worker/model_runner.py", line 494, in prepare_input_tensors lora_requests) = self._prepare_prompt(seq_group_metadata_list) File "/root/vllm/vllm/worker/model_runner.py", line 243, in _prepare_prompt start_loc_tensor = torch.arange(0, RuntimeError: step must be nonzero Exception in callback functools.partial(<function _raise_exception_on_finish at 0x7f87f65c35b0>, request_tracker=<vllm.engine.async_llm_engine.RequestTracker object at 0x7f87ec4e3fd0>) handle: <Handle functools.partial(<function _raise_exception_on_finish at 0x7f87f65c35b0>, request_tracker=<vllm.engine.async_llm_engine.RequestTracker object at 0x7f87ec4e3fd0>)> Traceback (most recent call last): File "/root/vllm/vllm/engine/async_llm_engine.py", line 29, in _raise_exception_on_finish task.result() File "/root/vllm/vllm/engine/async_llm_engine.py", line 412, in run_engine_loop has_requests_in_progress = await self.engine_step() File "/root/vllm/vllm/engine/async_llm_engine.py", line 391, in engine_step request_outputs = await self.engine.step_async() File "/root/vllm/vllm/engine/async_llm_engine.py", line 189, in step_async all_outputs = await self._run_workers_async( File "/root/vllm/vllm/engine/async_llm_engine.py", line 274, in _run_workers_async all_outputs = await asyncio.gather(*coros) File "/root/miniconda3/envs/vllm/lib/python3.10/asyncio/tasks.py", line 650, in _wrap_awaitable return (yield from awaitable.__await__()) ray.exceptions.RayTaskError(KeyError): ray::RayWorkerVllm.execute_method() (pid=1030270, ip=0.0.0.0, actor_id=be1ed7b0fca5fd6227e71c0101000000, repr=<vllm.engine.ray_utils.RayWorkerVllm object at 0x7f5f2f9ad630>) File "/root/vllm/vllm/engine/ray_utils.py", line 37, in execute_method return executor(*args, **kwargs) File "/root/miniconda3/envs/vllm/lib/python3.10/site-packages/torch/utils/_contextlib.py", line 115, in decorate_context return func(*args, **kwargs) File "/root/vllm/vllm/worker/worker.py", line 212, in execute_model num_seq_groups = data["num_seq_groups"] KeyError: 'num_seq_groups' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "uvloop/cbhandles.pyx", line 63, in uvloop.loop.Handle._run File "/root/vllm/vllm/engine/async_llm_engine.py", line 38, in _raise_exception_on_finish raise exc File "/root/vllm/vllm/engine/async_llm_engine.py", line 33, in _raise_exception_on_finish raise AsyncEngineDeadError( vllm.engine.async_llm_engine.AsyncEngineDeadError: Task finished unexpectedly. This should never happen! Please open an issue on Github. See stack trace above for the actual cause. INFO 03-04 20:37:48 async_llm_engine.py:133] Aborted request cmpl-7edf10b340a74b3e8c7c2e07325ae5c6. ERROR: Exception in ASGI application Traceback (most recent call last): File "/root/miniconda3/envs/vllm/lib/python3.10/site-packages/starlette/responses.py", line 264, in __call__ await wrap(partial(self.listen_for_disconnect, receive)) File "/root/miniconda3/envs/vllm/lib/python3.10/site-packages/starlette/responses.py", line 260, in wrap await func() File "/root/miniconda3/envs/vllm/lib/python3.10/site-packages/starlette/responses.py", line 237, in listen_for_disconnect message = await receive() File "/root/miniconda3/envs/vllm/lib/python3.10/site-packages/uvicorn/protocols/http/httptools_impl.py", line 580, in receive await self.message_event.wait() File "/root/miniconda3/envs/vllm/lib/python3.10/asyncio/locks.py", line 214, in wait await fut asyncio.exceptions.CancelledError: Cancelled by cancel scope 7f87bc0d52d0 During handling of the above exception, another exception occurred: + Exception Group Traceback (most recent call last): | File "/root/miniconda3/envs/vllm/lib/python3.10/site-packages/uvicorn/protocols/http/httptools_impl.py", line 419, in run_asgi | result = await app( # type: ignore[func-returns-value] | File "/root/miniconda3/envs/vllm/lib/python3.10/site-packages/uvicorn/middleware/proxy_headers.py", line 84, in __call__ | return await self.app(scope, receive, send) | File "/root/miniconda3/envs/vllm/lib/python3.10/site-packages/fastapi/applications.py", line 1054, in __call__ | await super().__call__(scope, receive, send) | File "/root/miniconda3/envs/vllm/lib/python3.10/site-packages/starlette/applications.py", line 123, in __call__ | await self.middleware_stack(scope, receive, send) | File "/root/miniconda3/envs/vllm/lib/python3.10/site-packages/starlette/middleware/errors.py", line 186, in __call__ | raise exc | File "/root/miniconda3/envs/vllm/lib/python3.10/site-packages/starlette/middleware/errors.py", line 164, in __call__ | await self.app(scope, receive, _send) | File "/root/miniconda3/envs/vllm/lib/python3.10/site-packages/starlette/middleware/cors.py", line 83, in __call__ | await self.app(scope, receive, send) | File "/root/miniconda3/envs/vllm/lib/python3.10/site-packages/starlette/middleware/exceptions.py", line 62, in __call__ | await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send) | File "/root/miniconda3/envs/vllm/lib/python3.10/site-packages/starlette/_exception_handler.py", line 64, in wrapped_app | raise exc | File "/root/miniconda3/envs/vllm/lib/python3.10/site-packages/starlette/_exception_handler.py", line 53, in wrapped_app | await app(scope, receive, sender) | File "/root/miniconda3/envs/vllm/lib/python3.10/site-packages/starlette/routing.py", line 758, in __call__ | await self.middleware_stack(scope, receive, send) | File "/root/miniconda3/envs/vllm/lib/python3.10/site-packages/starlette/routing.py", line 778, in app | await route.handle(scope, receive, send) | File "/root/miniconda3/envs/vllm/lib/python3.10/site-packages/starlette/routing.py", line 299, in handle | await self.app(scope, receive, send) | File "/root/miniconda3/envs/vllm/lib/python3.10/site-packages/starlette/routing.py", line 79, in app | await wrap_app_handling_exceptions(app, request)(scope, receive, send) | File "/root/miniconda3/envs/vllm/lib/python3.10/site-packages/starlette/_exception_handler.py", line 64, in wrapped_app | raise exc | File "/root/miniconda3/envs/vllm/lib/python3.10/site-packages/starlette/_exception_handler.py", line 53, in wrapped_app | await app(scope, receive, sender) | File "/root/miniconda3/envs/vllm/lib/python3.10/site-packages/starlette/routing.py", line 77, in app | await response(scope, receive, send) | File "/root/miniconda3/envs/vllm/lib/python3.10/site-packages/starlette/responses.py", line 257, in __call__ | async with anyio.create_task_group() as task_group: | File "/root/miniconda3/envs/vllm/lib/python3.10/site-packages/anyio/_backends/_asyncio.py", line 678, in __aexit__ | raise BaseExceptionGroup( | exceptiongroup.ExceptionGroup: unhandled errors in a TaskGroup (1 sub-exception) +-+---------------- 1 ---------------- | Traceback (most recent call last): | File "/root/vllm/vllm/engine/async_llm_engine.py", line 29, in _raise_exception_on_finish | task.result() | File "/root/vllm/vllm/engine/async_llm_engine.py", line 412, in run_engine_loop | has_requests_in_progress = await self.engine_step() | File "/root/vllm/vllm/engine/async_llm_engine.py", line 391, in engine_step | request_outputs = await self.engine.step_async() | File "/root/vllm/vllm/engine/async_llm_engine.py", line 189, in step_async | all_outputs = await self._run_workers_async( | File "/root/vllm/vllm/engine/async_llm_engine.py", line 274, in _run_workers_async | all_outputs = await asyncio.gather(*coros) | File "/root/miniconda3/envs/vllm/lib/python3.10/asyncio/tasks.py", line 650, in _wrap_awaitable | return (yield from awaitable.__await__()) | ray.exceptions.RayTaskError(KeyError): ray::RayWorkerVllm.execute_method() (pid=1030270, ip=0.0.0.0, actor_id=be1ed7b0fca5fd6227e71c0101000000, repr=<vllm.engine.ray_utils.RayWorkerVllm object at 0x7f5f2f9ad630>) | File "/root/vllm/vllm/engine/ray_utils.py", line 37, in execute_method | return executor(*args, **kwargs) | File "/root/miniconda3/envs/vllm/lib/python3.10/site-packages/torch/utils/_contextlib.py", line 115, in decorate_context | return func(*args, **kwargs) | File "/root/vllm/vllm/worker/worker.py", line 212, in execute_model | num_seq_groups = data["num_seq_groups"] | KeyError: 'num_seq_groups' | | The above exception was the direct cause of the following exception: | | Traceback (most recent call last): | File "/root/miniconda3/envs/vllm/lib/python3.10/site-packages/starlette/responses.py", line 260, in wrap | await func() | File "/root/miniconda3/envs/vllm/lib/python3.10/site-packages/starlette/responses.py", line 249, in stream_response | async for chunk in self.body_iterator: | File "/root/vllm/vllm/entrypoints/openai/serving_chat.py", line 148, in chat_completion_stream_generator | async for res in result_generator: | File "/root/vllm/vllm/engine/async_llm_engine.py", line 565, in generate | raise e | File "/root/vllm/vllm/engine/async_llm_engine.py", line 559, in generate | async for request_output in stream: | File "/root/vllm/vllm/engine/async_llm_engine.py", line 69, in __anext__ | raise result | File "uvloop/cbhandles.pyx", line 63, in uvloop.loop.Handle._run | File "/root/vllm/vllm/engine/async_llm_engine.py", line 38, in _raise_exception_on_finish | raise exc | File "/root/vllm/vllm/engine/async_llm_engine.py", line 33, in _raise_exception_on_finish | raise AsyncEngineDeadError( | vllm.engine.async_llm_engine.AsyncEngineDeadError: Task finished unexpectedly. This should never happen! Please open an issue on Github. See stack trace above for the actual cause. +------------------------------------ ``` vLLM: main branch Model: openbuddy-deepseek-67b-v18.1-4k-gptq (Marlin Kernel) GPU: 4 x RTX3090
[ { "content": "\"\"\"A block manager that manages token blocks.\"\"\"\nimport enum\nfrom itertools import count\nfrom os.path import commonprefix\nfrom typing import Dict, List, Optional, Set, Tuple\n\nfrom vllm.block import BlockTable, PhysicalTokenBlock\nfrom vllm.sequence import Sequence, SequenceGroup, Seque...
[ { "content": "\"\"\"A block manager that manages token blocks.\"\"\"\nimport enum\nfrom itertools import count, takewhile\nfrom os.path import commonprefix\nfrom typing import Dict, List, Optional, Set, Tuple\n\nfrom vllm.block import BlockTable, PhysicalTokenBlock\nfrom vllm.sequence import Sequence, SequenceG...
diff --git a/tests/engine/test_computed_prefix_blocks.py b/tests/engine/test_computed_prefix_blocks.py new file mode 100644 index 000000000000..ed35212cc3f1 --- /dev/null +++ b/tests/engine/test_computed_prefix_blocks.py @@ -0,0 +1,34 @@ +import pytest + +from vllm.engine.arg_utils import EngineArgs +from vllm.engine.llm_engine import LLMEngine +from vllm.sampling_params import SamplingParams + + +@pytest.mark.parametrize("model", ["facebook/opt-125m"]) +@pytest.mark.parametrize("block_size", [16]) +def test_computed_prefix_blocks(model: str, block_size: int): + # This test checks if we are able to run the engine to completion + # without triggering asserts. + # We are in a scenario where all blocks from the second request's prompt + # are full and already computed when the second request arrives. + prompt = ( + "You are a helpful assistant. How do I build a car from cardboard and " + "paper clips? Is there an easy to follow video tutorial available " + "online for free?") + prompt2 = ( + " Please recommend to me some resources where I can learn not only to " + "handle technical difficulties of building a car, but also " + "decoration.") + + engine_args = EngineArgs(model=model, + block_size=block_size, + enable_prefix_caching=True) + + engine = LLMEngine.from_engine_args(engine_args) + sampling_params = SamplingParams() + + engine.add_request("0", prompt + prompt2, sampling_params) + engine.step() + engine.add_request("1", prompt, sampling_params) + engine.step() diff --git a/vllm/core/block_manager.py b/vllm/core/block_manager.py index daf83827a7e5..52b120f227ed 100644 --- a/vllm/core/block_manager.py +++ b/vllm/core/block_manager.py @@ -1,6 +1,6 @@ """A block manager that manages token blocks.""" import enum -from itertools import count +from itertools import count, takewhile from os.path import commonprefix from typing import Dict, List, Optional, Set, Tuple @@ -426,23 +426,29 @@ def access_all_blocks_in_seq( for block in block_table: block.last_accessed = access_time - def compute_last_full_block_in_seq(self, seq: Sequence): + def compute_full_blocks_in_seq(self, seq: Sequence): if seq.seq_id not in self.block_tables: return max_full_block = seq.get_len() // self.block_size - 1 block_table = self.block_tables[seq.seq_id] if max_full_block == -1: return - block_table[max_full_block].computed = True + for i in reversed(range(max_full_block)): + if block_table[i].computed: + break + block_table[i].computed = True - def get_all_block_ids_till_computed(self, seq: Sequence) -> List[int]: + def get_all_computed_blocks(self, seq: Sequence) -> List[int]: if seq.seq_id not in self.block_tables: return [] block_table = self.block_tables[seq.seq_id] - for block_idx in reversed(range(len(block_table))): - if block_table[block_idx].computed: - return [b.block_number for b in block_table[:block_idx + 1]] - return [] + # NOTE We exclude the last block to avoid the case where the entire + # prompt is cached. This would cause erroneous behavior in model + # runner. + return [ + b.block_number + for b in takewhile(lambda b: b.computed, block_table[:-1]) + ] def get_common_computed_block_ids(self, seq_group: SequenceGroup) -> List[int]: @@ -451,14 +457,12 @@ def get_common_computed_block_ids(self, return [] ids_list = [ - self.get_all_block_ids_till_computed(seq) + self.get_all_computed_blocks(seq) for seq in iter(seq_group.seqs_dict.values()) ] return commonprefix([ids for ids in ids_list if ids != []]) def mark_blocks_as_computed(self, seq_group: SequenceGroup): - # NOTE: We only mark the last full block because with prefix caching, - # all blocks until the marked one are guaranteed to be computed. if self.enable_caching: for seq in seq_group.seqs_dict.values(): - self.compute_last_full_block_in_seq(seq) + self.compute_full_blocks_in_seq(seq) diff --git a/vllm/worker/model_runner.py b/vllm/worker/model_runner.py index aff8ebc90362..9516d4bdea94 100644 --- a/vllm/worker/model_runner.py +++ b/vllm/worker/model_runner.py @@ -209,6 +209,7 @@ def _prepare_prompt( slot_mapping[-1].append(slot) max_prompt_len = max(subquery_lens) + assert max_prompt_len > 0 input_tokens = _make_tensor_with_pad(input_tokens, max_prompt_len, pad=0,
vllm-project__vllm-4109
[Feature]: Update Outlines Integration from `FSM` to `Guide` ### 🚀 The feature, motivation and pitch Recently outlines updated their interface from FSM to Guide to support "acceleration"/"fast-forward" which will output next sets of tokens if they are directly available. For JSON schema, the cases are the keys, the `"`, and `}` etc. This is non-trivial but very useful to improve vLLM for. It should also help other framework like AICI #3714. ### Alternatives _No response_ ### Additional context _No response_
[ { "content": "import asyncio\nimport concurrent.futures\nfrom copy import copy\nfrom enum import Enum\nfrom functools import lru_cache\nfrom json import dumps as json_dumps\nfrom re import escape as regex_escape\nfrom typing import Tuple, Union\n\nfrom pydantic import BaseModel\nfrom transformers import PreTrai...
[ { "content": "import asyncio\nimport concurrent.futures\nfrom enum import Enum\nfrom json import dumps as json_dumps\nfrom re import escape as regex_escape\nfrom typing import Tuple, Union\n\nfrom pydantic import BaseModel\nfrom transformers import PreTrainedTokenizerBase\n\nfrom vllm.entrypoints.openai.protoco...
diff --git a/requirements-common.txt b/requirements-common.txt index f41873570aa6..bf9987e3af01 100644 --- a/requirements-common.txt +++ b/requirements-common.txt @@ -17,6 +17,6 @@ prometheus_client >= 0.18.0 prometheus-fastapi-instrumentator >= 7.0.0 tiktoken >= 0.6.0 # Required for DBRX tokenizer lm-format-enforcer == 0.10.1 -outlines == 0.0.34 # Requires torch >= 2.1.0 +outlines >= 0.0.43 # Requires torch >= 2.1.0 typing_extensions filelock >= 3.10.4 # filelock starts to support `mode` argument from 3.10.4 diff --git a/tests/entrypoints/test_guided_processors.py b/tests/entrypoints/test_guided_processors.py index 5d4163e96fd8..fb32a9d155bc 100644 --- a/tests/entrypoints/test_guided_processors.py +++ b/tests/entrypoints/test_guided_processors.py @@ -63,7 +63,6 @@ def test_guided_logits_processors(): tokenizer, whitespace_pattern=None) - regex_LP.init_state() token_ids = tokenizer.encode( f"Give an example IPv4 address with this regex: {TEST_REGEX}") tensor = torch.rand(32000) @@ -72,7 +71,6 @@ def test_guided_logits_processors(): assert tensor.shape == original_tensor.shape assert not torch.allclose(tensor, original_tensor) - json_LP.init_state() token_ids = tokenizer.encode( f"Give an employee profile that fits this schema: {TEST_SCHEMA}") tensor = torch.rand(32000) diff --git a/vllm/model_executor/guided_decoding/outlines_decoding.py b/vllm/model_executor/guided_decoding/outlines_decoding.py index 840360428690..721f7e0530cb 100644 --- a/vllm/model_executor/guided_decoding/outlines_decoding.py +++ b/vllm/model_executor/guided_decoding/outlines_decoding.py @@ -1,8 +1,6 @@ import asyncio import concurrent.futures -from copy import copy from enum import Enum -from functools import lru_cache from json import dumps as json_dumps from re import escape as regex_escape from typing import Tuple, Union @@ -54,8 +52,10 @@ class GuidedDecodingMode(Enum): async def get_outlines_guided_decoding_logits_processor( - request: Union[CompletionRequest, ChatCompletionRequest], - tokenizer) -> Union[JSONLogitsProcessor, RegexLogitsProcessor, None]: + request: Union[CompletionRequest, + ChatCompletionRequest], tokenizer: PreTrainedTokenizerBase +) -> Union[JSONLogitsProcessor, RegexLogitsProcessor, CFGLogitsProcessor, + None]: """ Given an OpenAI-compatible request, check for guided decoding parameters and get the necessary logits processor for the given guide. @@ -64,7 +64,7 @@ async def get_outlines_guided_decoding_logits_processor( """ global global_thread_pool guide, mode = _get_guide_and_mode(request) - if not guide: + if not guide or not mode: return None if global_thread_pool is None: @@ -72,15 +72,9 @@ async def get_outlines_guided_decoding_logits_processor( max_workers=2) loop = asyncio.get_running_loop() - result = await loop.run_in_executor(global_thread_pool, - _get_cached_logits_processor, guide, - tokenizer, mode, - request.guided_whitespace_pattern) - - logits_processor = copy(result) - # reset logits processor's internal state - logits_processor.init_state() - return logits_processor + return await loop.run_in_executor(global_thread_pool, + _get_logits_processor, guide, tokenizer, + mode, request.guided_whitespace_pattern) def _get_guide_and_mode( @@ -115,11 +109,10 @@ def _get_guide_and_mode( return None, None -@lru_cache(maxsize=32) -def _get_cached_logits_processor(guide: str, - tokenizer: PreTrainedTokenizerBase, - mode: GuidedDecodingMode, - whitespace_pattern: Union[str, None]): +def _get_logits_processor( + guide: str, tokenizer: PreTrainedTokenizerBase, mode: GuidedDecodingMode, + whitespace_pattern: Union[str, None] +) -> Union[JSONLogitsProcessor, RegexLogitsProcessor, CFGLogitsProcessor]: if mode == GuidedDecodingMode.JSON: return JSONLogitsProcessor(guide, tokenizer, whitespace_pattern) elif mode == GuidedDecodingMode.REGEX or mode == GuidedDecodingMode.CHOICE: diff --git a/vllm/model_executor/guided_decoding/outlines_logits_processors.py b/vllm/model_executor/guided_decoding/outlines_logits_processors.py index a131c6a1b92b..1618705ff298 100644 --- a/vllm/model_executor/guided_decoding/outlines_logits_processors.py +++ b/vllm/model_executor/guided_decoding/outlines_logits_processors.py @@ -21,7 +21,7 @@ from typing import Callable, DefaultDict, Dict, List, Union import torch -from outlines.fsm.fsm import CFGFSM, FSM, RegexFSM +from outlines.fsm.guide import CFGGuide, Generate, Guide, RegexGuide, Write from outlines.fsm.json_schema import build_regex_from_schema from pydantic import BaseModel from transformers import PreTrainedTokenizerBase @@ -29,28 +29,32 @@ class BaseLogitsProcessor: - def __init__(self): - # Child class should use initialize in their init. - self.fsm: FSM - - def init_state(self): - """Initialize the FSM states.""" - self.fsm_state: DefaultDict[int, int] = defaultdict(int) + def __init__(self, guide: Guide): + self._guide: Guide = guide + self._fsm_state: DefaultDict[int, int] = defaultdict(int) def __call__(self, input_ids: List[int], scores: torch.Tensor) -> torch.Tensor: """Use the FSM to bias the logits before sampling the next token.""" seq_id = hash(tuple(input_ids)) - if len(input_ids) == 0: - self.init_state() - else: + if len(input_ids) > 0: last_token = input_ids[-1] last_seq_id = hash(tuple(input_ids[:-1])) - self.fsm_state[seq_id] = self.fsm.next_state( - self.fsm_state[last_seq_id], last_token) + self._fsm_state[seq_id] = self._guide.get_next_state( + state=self._fsm_state[last_seq_id], token_id=last_token) + + instruction = self._guide.get_next_instruction( + state=self._fsm_state[seq_id]) - allowed_tokens = self.fsm.allowed_token_ids(self.fsm_state[seq_id]) + if type(instruction) == Generate: + allowed_tokens = instruction.tokens + elif type(instruction) == Write: + # TODO: support fast forward tokens + allowed_tokens = [instruction.tokens[0]] + else: + raise TypeError( + f"Unsupported instruction type {type(instruction)}") mask = torch.full((scores.shape[-1], ), -math.inf, @@ -62,6 +66,13 @@ def __call__(self, input_ids: List[int], class RegexLogitsProcessor(BaseLogitsProcessor): + @classmethod + @lru_cache(maxsize=32) + def _get_guide(cls, regex_string: str, + tokenizer: PreTrainedTokenizerBase) -> Guide: + tokenizer = _adapt_tokenizer(tokenizer) + return RegexGuide(regex_string, tokenizer) + def __init__(self, regex_string: str, tokenizer: PreTrainedTokenizerBase): """Compile the FSM that drives the regex-structured generation. @@ -73,9 +84,8 @@ def __init__(self, regex_string: str, tokenizer: PreTrainedTokenizerBase): The model's tokenizer """ - tokenizer = _adapt_tokenizer(tokenizer) - fsm = RegexFSM(regex_string, tokenizer) - self.fsm = fsm + super().__init__( + RegexLogitsProcessor._get_guide(regex_string, tokenizer)) class JSONLogitsProcessor(RegexLogitsProcessor): @@ -115,6 +125,12 @@ def __init__(self, schema: Union[str, Dict, BaseModel], class CFGLogitsProcessor(BaseLogitsProcessor): + @classmethod + @lru_cache(maxsize=32) + def _get_guide(cls, cfg: str, tokenizer: PreTrainedTokenizerBase) -> Guide: + tokenizer = _adapt_tokenizer(tokenizer) + return CFGGuide(cfg, tokenizer) + def __init__(self, cfg: str, tokenizer: PreTrainedTokenizerBase): """Compile the FSM that drives the context free grammar generation. @@ -126,17 +142,11 @@ def __init__(self, cfg: str, tokenizer: PreTrainedTokenizerBase): The model's tokenizer """ - tokenizer = _adapt_tokenizer(tokenizer) - fsm = CFGFSM(cfg, tokenizer) - self.fsm = fsm - - def init_state(self): - """Initialize state with a CFGFSM copy.""" - super().init_state() - self.fsm = self.fsm.copy() + super().__init__(CFGLogitsProcessor._get_guide(cfg, tokenizer)) + self._guide = self._guide.copy() -@lru_cache +@lru_cache(maxsize=32) def _adapt_tokenizer(tokenizer: PreTrainedTokenizerBase): """Adapt vLLM's tokenizer to use to compile the FSM.
vllm-project__vllm-4128
[Bug][Chunked prefill]: head size has to be power of two ### 🐛 Describe the bug The chunked prefill doesn't support head sizes that are not powers of two. For example, phi2 has head size of 80 (which is supported by flash attn, but the _flash_fwd triton kernel doesn't support it). Fix PR is coming. ```python from vllm import LLM, SamplingParams sampling_params = SamplingParams(temperature=0.8) llm = LLM(model="microsoft/phi-2", enable_chunked_prefill=True) print(llm.generate("Hello, ", sampling_params)) ``` ``` Traceback (most recent call last): File "/workspaces/aici/py/vllm/test.py", line 7, in <module> print(llm.generate("Hello, ", sampling_params)) File "/workspaces/aici/py/vllm/vllm/entrypoints/llm.py", line 190, in generate return self._run_engine(use_tqdm) File "/workspaces/aici/py/vllm/vllm/entrypoints/llm.py", line 218, in _run_engine step_outputs = self.llm_engine.step() File "/workspaces/aici/py/vllm/vllm/engine/llm_engine.py", line 735, in step output = self.model_executor.execute_model( File "/workspaces/aici/py/vllm/vllm/executor/gpu_executor.py", line 91, in execute_model output = self.driver_worker.execute_model( File "/usr/local/lib/python3.10/dist-packages/torch/utils/_contextlib.py", line 115, in decorate_context return func(*args, **kwargs) File "/workspaces/aici/py/vllm/vllm/worker/worker.py", line 235, in execute_model output = self.model_runner.execute_model(seq_group_metadata_list, File "/usr/local/lib/python3.10/dist-packages/torch/utils/_contextlib.py", line 115, in decorate_context return func(*args, **kwargs) File "/workspaces/aici/py/vllm/vllm/worker/model_runner.py", line 834, in execute_model hidden_states = model_executable(**execute_model_kwargs) File "/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py", line 1511, in _wrapped_call_impl return self._call_impl(*args, **kwargs) File "/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py", line 1520, in _call_impl return forward_call(*args, **kwargs) File "/workspaces/aici/py/vllm/vllm/model_executor/models/phi.py", line 249, in forward hidden_states = self.model(input_ids, positions, kv_caches, File "/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py", line 1511, in _wrapped_call_impl return self._call_impl(*args, **kwargs) File "/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py", line 1520, in _call_impl return forward_call(*args, **kwargs) File "/workspaces/aici/py/vllm/vllm/model_executor/models/phi.py", line 213, in forward hidden_states = layer( File "/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py", line 1511, in _wrapped_call_impl return self._call_impl(*args, **kwargs) File "/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py", line 1520, in _call_impl return forward_call(*args, **kwargs) File "/workspaces/aici/py/vllm/vllm/model_executor/models/phi.py", line 175, in forward attn_outputs = self.self_attn( File "/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py", line 1511, in _wrapped_call_impl return self._call_impl(*args, **kwargs) File "/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py", line 1520, in _call_impl return forward_call(*args, **kwargs) File "/workspaces/aici/py/vllm/vllm/model_executor/models/phi.py", line 120, in forward attn_output = self.attn(q, k, v, kv_cache, attn_metadata) File "/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py", line 1511, in _wrapped_call_impl return self._call_impl(*args, **kwargs) File "/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py", line 1520, in _call_impl return forward_call(*args, **kwargs) File "/workspaces/aici/py/vllm/vllm/attention/layer.py", line 48, in forward return self.impl.forward(query, key, value, kv_cache, attn_metadata, File "/workspaces/aici/py/vllm/vllm/attention/backends/flash_attn.py", line 240, in forward output[:num_prefill_tokens] = PagedAttention.forward_prefix( File "/workspaces/aici/py/vllm/vllm/attention/ops/paged_attn.py", line 177, in forward_prefix context_attention_fwd( File "/usr/local/lib/python3.10/dist-packages/torch/utils/_contextlib.py", line 115, in decorate_context return func(*args, **kwargs) File "/workspaces/aici/py/vllm/vllm/attention/ops/prefix_prefill.py", line 639, in context_attention_fwd assert Lk in {16, 32, 64, 128} AssertionError ``` ### Your current environment ```text Collecting environment information... PyTorch version: 2.2.1+cu121 Is debug build: False CUDA used to build PyTorch: 12.1 ROCM used to build PyTorch: N/A OS: Ubuntu 22.04.3 LTS (x86_64) GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0 Clang version: 14.0.0-1ubuntu1.1 CMake version: version 3.27.6 Libc version: glibc-2.35 Python version: 3.10.12 (main, Jun 11 2023, 05:26:28) [GCC 11.4.0] (64-bit runtime) Python platform: Linux-5.15.0-1060-azure-x86_64-with-glibc2.35 Is CUDA available: True CUDA runtime version: 12.2.140 CUDA_MODULE_LOADING set to: LAZY GPU models and configuration: GPU 0: NVIDIA A100 80GB PCIe Nvidia driver version: 470.239.06 cuDNN version: Probably one of the following: /usr/lib/x86_64-linux-gnu/libcudnn.so.8.9.5 /usr/lib/x86_64-linux-gnu/libcudnn_adv_infer.so.8.9.5 /usr/lib/x86_64-linux-gnu/libcudnn_adv_train.so.8.9.5 /usr/lib/x86_64-linux-gnu/libcudnn_cnn_infer.so.8.9.5 /usr/lib/x86_64-linux-gnu/libcudnn_cnn_train.so.8.9.5 /usr/lib/x86_64-linux-gnu/libcudnn_ops_infer.so.8.9.5 /usr/lib/x86_64-linux-gnu/libcudnn_ops_train.so.8.9.5 HIP runtime version: N/A MIOpen runtime version: N/A Is XNNPACK available: True CPU: Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Address sizes: 48 bits physical, 48 bits virtual Byte Order: Little Endian CPU(s): 24 On-line CPU(s) list: 0-23 Vendor ID: AuthenticAMD Model name: AMD EPYC 7V13 64-Core Processor CPU family: 25 Model: 1 Thread(s) per core: 1 Core(s) per socket: 24 Socket(s): 1 Stepping: 1 BogoMIPS: 4890.87 Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nopl tsc_reliable nonstop_tsc cpuid extd_apicid aperfmperf pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 movbe popcnt aes xsave avx f16c rdrand hypervisor lahf_lm cmp_legacy cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw topoext perfctr_core invpcid_single vmmcall fsgsbase bmi1 avx2 smep bmi2 erms invpcid rdseed adx smap clflushopt clwb sha_ni xsaveopt xsavec xgetbv1 xsaves clzero xsaveerptr rdpru arat umip vaes vpclmulqdq rdpid fsrm Hypervisor vendor: Microsoft Virtualization type: full L1d cache: 768 KiB (24 instances) L1i cache: 768 KiB (24 instances) L2 cache: 12 MiB (24 instances) L3 cache: 96 MiB (3 instances) NUMA node(s): 1 NUMA node0 CPU(s): 0-23 Vulnerability Gather data sampling: Not affected Vulnerability Itlb multihit: Not affected Vulnerability L1tf: Not affected Vulnerability Mds: Not affected Vulnerability Meltdown: Not affected Vulnerability Mmio stale data: Not affected Vulnerability Retbleed: Not affected Vulnerability Spec rstack overflow: Mitigation; safe RET, no microcode Vulnerability Spec store bypass: Vulnerable Vulnerability Spectre v1: Mitigation; usercopy/swapgs barriers and __user pointer sanitization Vulnerability Spectre v2: Mitigation; Retpolines, STIBP disabled, RSB filling, PBRSB-eIBRS Not affected Vulnerability Srbds: Not affected Vulnerability Tsx async abort: Not affected Versions of relevant libraries: [pip3] mypy==0.991 [pip3] mypy-extensions==1.0.0 [pip3] numpy==1.22.2 [pip3] onnx==1.14.0 [pip3] pytorch-quantization==2.1.2 [pip3] torch==2.2.1 [pip3] torch-tensorrt==0.0.0 [pip3] torchdata==0.7.0a0 [pip3] torchtext==0.16.0a0 [pip3] torchvision==0.16.0a0 [pip3] triton==2.2.0 [conda] Could not collectROCM Version: Could not collect Neuron SDK Version: N/A vLLM Version: 0.4.0.post1 vLLM Build Flags: CUDA Archs: 8.0; ROCm: Disabled; Neuron: Disabled GPU Topology: GPU0 CPU Affinity NUMA Affinity GPU0 X 0-23 N/A Legend: X = Self SYS = Connection traversing PCIe as well as the SMP interconnect between NUMA nodes (e.g., QPI/UPI) NODE = Connection traversing PCIe as well as the interconnect between PCIe Host Bridges within a NUMA node PHB = Connection traversing PCIe as well as a PCIe Host Bridge (typically the CPU) PXB = Connection traversing multiple PCIe bridges (without traversing the PCIe Host Bridge) PIX = Connection traversing at most a single PCIe bridge NV# = Connection traversing a bonded set of # NVLinks ```
[ { "content": "# The kernels in this file are adapted from LightLLM's context_attention_fwd:\n# https://github.com/ModelTC/lightllm/blob/main/lightllm/models/llama/triton_kernel/context_flashattention_nopad.py\n\nimport torch\nimport triton\nimport triton.language as tl\n\nif triton.__version__ >= \"2.1.0\":\n\n...
[ { "content": "# The kernels in this file are adapted from LightLLM's context_attention_fwd:\n# https://github.com/ModelTC/lightllm/blob/main/lightllm/models/llama/triton_kernel/context_flashattention_nopad.py\n\nimport torch\nimport triton\nimport triton.language as tl\n\nif triton.__version__ >= \"2.1.0\":\n\n...
diff --git a/tests/kernels/test_prefix_prefill.py b/tests/kernels/test_prefix_prefill.py index 6494fb34af98..ad31b0a7c2a1 100644 --- a/tests/kernels/test_prefix_prefill.py +++ b/tests/kernels/test_prefix_prefill.py @@ -10,7 +10,7 @@ NUM_HEADS = [64] NUM_QUERIES_PER_KV = [1, 8, 64] -HEAD_SIZES = [128] +HEAD_SIZES = [128, 96] DTYPES = [torch.float16] CUDA_DEVICES = [ f"cuda:{i}" for i in range(1 if torch.cuda.device_count() == 1 else 2) diff --git a/vllm/attention/ops/prefix_prefill.py b/vllm/attention/ops/prefix_prefill.py index 70f09224f1cf..4896cf3909c6 100644 --- a/vllm/attention/ops/prefix_prefill.py +++ b/vllm/attention/ops/prefix_prefill.py @@ -47,7 +47,8 @@ def _fwd_kernel( stride_v_cache_bl, num_queries_per_kv: int, BLOCK_M: tl.constexpr, - BLOCK_DMODEL: tl.constexpr, + BLOCK_DMODEL: tl.constexpr, # head size + BLOCK_DMODEL_PADDED: tl.constexpr, # head size padded to a power of 2 BLOCK_N: tl.constexpr, ): cur_batch = tl.program_id(0) @@ -59,26 +60,30 @@ def _fwd_kernel( cur_batch_ctx_len = tl.load(B_Ctxlen + cur_batch) cur_batch_seq_len = tl.load(B_Seqlen + cur_batch) cur_batch_in_all_start_index = tl.load(B_Start_Loc + cur_batch) + cur_batch_query_len = cur_batch_seq_len - cur_batch_ctx_len block_start_loc = BLOCK_M * start_m # initialize offsets offs_n = tl.arange(0, BLOCK_N) - offs_d = tl.arange(0, BLOCK_DMODEL) + offs_d = tl.arange(0, BLOCK_DMODEL_PADDED) offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M) off_q = ( (cur_batch_in_all_start_index + offs_m[:, None]) * stride_qbs + cur_head * stride_qh + offs_d[None, :] * stride_qd) - q = tl.load( - Q + off_q, - mask=offs_m[:, None] < cur_batch_seq_len - cur_batch_ctx_len, - other=0.0) + dim_mask = tl.where( + tl.arange(0, BLOCK_DMODEL_PADDED) < BLOCK_DMODEL, 1, 0).to(tl.int1) + + q = tl.load(Q + off_q, + mask=dim_mask[None, :] & + (offs_m[:, None] < cur_batch_query_len), + other=0.0) # # initialize pointer to m and l m_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float("inf") l_i = tl.zeros([BLOCK_M], dtype=tl.float32) - acc = tl.zeros([BLOCK_M, BLOCK_DMODEL], dtype=tl.float32) + acc = tl.zeros([BLOCK_M, BLOCK_DMODEL_PADDED], dtype=tl.float32) for start_n in range(0, cur_batch_ctx_len, BLOCK_N): start_n = tl.multiple_of(start_n, BLOCK_N) @@ -99,7 +104,8 @@ def _fwd_kernel( offs_d[None, :] * stride_v_cache_d + (start_n + offs_n[:, None]) % block_size * stride_v_cache_bl) k = tl.load(K_cache + off_k, - mask=(start_n + offs_n[None, :]) < cur_batch_ctx_len, + mask=dim_mask[:, None] & + ((start_n + offs_n[None, :]) < cur_batch_ctx_len), other=0.0) qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32) @@ -126,7 +132,8 @@ def _fwd_kernel( acc = acc * acc_scale[:, None] # update acc v = tl.load(V_cache + off_v, - mask=(start_n + offs_n[:, None]) < cur_batch_ctx_len, + mask=dim_mask[None, :] & + ((start_n + offs_n[:, None]) < cur_batch_ctx_len), other=0.0) p = p.to(v.dtype) @@ -142,16 +149,15 @@ def _fwd_kernel( k_ptrs = K + off_k v_ptrs = V + off_v - block_mask = tl.where( - block_start_loc < cur_batch_seq_len - cur_batch_ctx_len, 1, 0) + block_mask = tl.where(block_start_loc < cur_batch_query_len, 1, 0) for start_n in range(0, block_mask * (start_m + 1) * BLOCK_M, BLOCK_N): start_n = tl.multiple_of(start_n, BLOCK_N) # -- compute qk ---- k = tl.load(k_ptrs + (cur_batch_in_all_start_index + start_n) * stride_kbs, - mask=(start_n + offs_n[None, :]) < - cur_batch_seq_len - cur_batch_ctx_len, + mask=dim_mask[:, None] & + ((start_n + offs_n[None, :]) < cur_batch_query_len), other=0.0) qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32) @@ -179,8 +185,8 @@ def _fwd_kernel( # update acc v = tl.load(v_ptrs + (cur_batch_in_all_start_index + start_n) * stride_vbs, - mask=(start_n + offs_n[:, None]) < - cur_batch_seq_len - cur_batch_ctx_len, + mask=dim_mask[None, :] & + ((start_n + offs_n[:, None]) < cur_batch_query_len), other=0.0) p = p.to(v.dtype) @@ -195,7 +201,8 @@ def _fwd_kernel( out_ptrs = Out + off_o tl.store(out_ptrs, acc, - mask=offs_m[:, None] < cur_batch_seq_len - cur_batch_ctx_len) + mask=dim_mask[None, :] & + (offs_m[:, None] < cur_batch_query_len)) return @triton.jit @@ -636,7 +643,8 @@ def context_attention_fwd(q, # shape constraints Lq, Lk, Lv = q.shape[-1], k.shape[-1], v.shape[-1] assert Lq == Lk and Lk == Lv - assert Lk in {16, 32, 64, 128} + # round up Lk to a power of 2 - this is required for Triton block size + Lk_padded = 2**((Lk - 1).bit_length()) sm_scale = 1.0 / (Lq**0.5) batch, head = b_seq_len.shape[0], q.shape[1] @@ -646,6 +654,7 @@ def context_attention_fwd(q, num_warps = 8 if Lk <= 64 else 8 if alibi_slopes is not None: + assert Lk == Lk_padded _fwd_kernel_alibi[grid]( q, k, @@ -738,6 +747,7 @@ def context_attention_fwd(q, num_queries_per_kv=num_queries_per_kv, BLOCK_M=BLOCK, BLOCK_DMODEL=Lk, + BLOCK_DMODEL_PADDED=Lk_padded, BLOCK_N=BLOCK, num_warps=num_warps, num_stages=1,
vllm-project__vllm-4219
[Doc]: Engine arguments of lora are not shown in VLLM docs on homepage ### 📚 The doc issue The lora arguments are not shown on this page. https://docs.vllm.ai/en/latest/models/engine_args.html ### Suggest a potential alternative/fix Add latest documentation from source code
[ { "content": "# Configuration file for the Sphinx documentation builder.\n#\n# This file only contains a selection of the most common options. For a full\n# list see the documentation:\n# https://www.sphinx-doc.org/en/master/usage/configuration.html\n\n# -- Path setup -------------------------------------------...
[ { "content": "# Configuration file for the Sphinx documentation builder.\n#\n# This file only contains a selection of the most common options. For a full\n# list see the documentation:\n# https://www.sphinx-doc.org/en/master/usage/configuration.html\n\n# -- Path setup -------------------------------------------...
diff --git a/docs/source/conf.py b/docs/source/conf.py index 19cc8557a754..cfa956b143ba 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -11,12 +11,14 @@ # documentation root, use os.path.abspath to make it absolute, like shown here. import logging +import os import sys from typing import List from sphinx.ext import autodoc logger = logging.getLogger(__name__) +sys.path.append(os.path.abspath("../..")) # -- Project information ----------------------------------------------------- diff --git a/docs/source/models/engine_args.rst b/docs/source/models/engine_args.rst index 235cb4e128c9..92bc7e0e843e 100644 --- a/docs/source/models/engine_args.rst +++ b/docs/source/models/engine_args.rst @@ -5,133 +5,17 @@ Engine Arguments Below, you can find an explanation of every engine argument for vLLM: -.. option:: --model <model_name_or_path> - - Name or path of the huggingface model to use. - -.. option:: --tokenizer <tokenizer_name_or_path> - - Name or path of the huggingface tokenizer to use. - -.. option:: --revision <revision> - - The specific model version to use. It can be a branch name, a tag name, or a commit id. If unspecified, will use the default version. - -.. option:: --tokenizer-revision <revision> - - The specific tokenizer version to use. It can be a branch name, a tag name, or a commit id. If unspecified, will use the default version. - -.. option:: --tokenizer-mode {auto,slow} - - The tokenizer mode. - - * "auto" will use the fast tokenizer if available. - * "slow" will always use the slow tokenizer. - -.. option:: --trust-remote-code - - Trust remote code from huggingface. - -.. option:: --download-dir <directory> - - Directory to download and load the weights, default to the default cache dir of huggingface. - -.. option:: --load-format {auto,pt,safetensors,npcache,dummy,tensorizer} - - The format of the model weights to load. - - * "auto" will try to load the weights in the safetensors format and fall back to the pytorch bin format if safetensors format is not available. - * "pt" will load the weights in the pytorch bin format. - * "safetensors" will load the weights in the safetensors format. - * "npcache" will load the weights in pytorch format and store a numpy cache to speed up the loading. - * "dummy" will initialize the weights with random values, mainly for profiling. - * "tensorizer" will load serialized weights using `CoreWeave's Tensorizer model deserializer. <https://github.com/coreweave/tensorizer>`_ See `examples/tensorize_vllm_model.py <https://github.com/vllm-project/vllm/blob/main/examples/tensorize_vllm_model.py>`_ to serialize a vLLM model, and for more information. - -.. option:: --dtype {auto,half,float16,bfloat16,float,float32} - - Data type for model weights and activations. - - * "auto" will use FP16 precision for FP32 and FP16 models, and BF16 precision for BF16 models. - * "half" for FP16. Recommended for AWQ quantization. - * "float16" is the same as "half". - * "bfloat16" for a balance between precision and range. - * "float" is shorthand for FP32 precision. - * "float32" for FP32 precision. - -.. option:: --max-model-len <length> - - Model context length. If unspecified, will be automatically derived from the model config. - -.. option:: --worker-use-ray - - Use Ray for distributed serving, will be automatically set when using more than 1 GPU. - -.. option:: --pipeline-parallel-size (-pp) <size> - - Number of pipeline stages. - -.. option:: --tensor-parallel-size (-tp) <size> - - Number of tensor parallel replicas. - -.. option:: --max-parallel-loading-workers <workers> - - Load model sequentially in multiple batches, to avoid RAM OOM when using tensor parallel and large models. - -.. option:: --block-size {8,16,32} - - Token block size for contiguous chunks of tokens. - -.. option:: --enable-prefix-caching - - Enables automatic prefix caching - -.. option:: --seed <seed> - - Random seed for operations. - -.. option:: --swap-space <size> - - CPU swap space size (GiB) per GPU. - -.. option:: --gpu-memory-utilization <fraction> - - The fraction of GPU memory to be used for the model executor, which can range from 0 to 1. - For example, a value of 0.5 would imply 50% GPU memory utilization. - If unspecified, will use the default value of 0.9. - -.. option:: --max-num-batched-tokens <tokens> - - Maximum number of batched tokens per iteration. - -.. option:: --max-num-seqs <sequences> - - Maximum number of sequences per iteration. - -.. option:: --max-paddings <paddings> - - Maximum number of paddings in a batch. - -.. option:: --disable-log-stats - - Disable logging statistics. - -.. option:: --quantization (-q) {awq,squeezellm,None} - - Method used to quantize the weights. +.. argparse:: + :module: vllm.engine.arg_utils + :func: _engine_args_parser + :prog: -m vllm.entrypoints.openai.api_server Async Engine Arguments ---------------------- -Below are the additional arguments related to the asynchronous engine: - -.. option:: --engine-use-ray - Use Ray to start the LLM engine in a separate process as the server process. - -.. option:: --disable-log-requests - - Disable logging requests. - -.. option:: --max-log-len +Below are the additional arguments related to the asynchronous engine: - Max number of prompt characters or prompt ID numbers being printed in log. Defaults to unlimited. \ No newline at end of file +.. argparse:: + :module: vllm.engine.arg_utils + :func: _async_engine_args_parser + :prog: -m vllm.entrypoints.openai.api_server \ No newline at end of file diff --git a/vllm/engine/arg_utils.py b/vllm/engine/arg_utils.py index 2999ab0a7e72..53f129598270 100644 --- a/vllm/engine/arg_utils.py +++ b/vllm/engine/arg_utils.py @@ -82,57 +82,55 @@ def add_cli_args( parser: argparse.ArgumentParser) -> argparse.ArgumentParser: """Shared CLI arguments for vLLM engine.""" - # NOTE: If you update any of the arguments below, please also - # make sure to update docs/source/models/engine_args.rst - # Model arguments parser.add_argument( '--model', type=str, default='facebook/opt-125m', - help='name or path of the huggingface model to use') + help='Name or path of the huggingface model to use.') parser.add_argument( '--tokenizer', type=str, default=EngineArgs.tokenizer, - help='name or path of the huggingface tokenizer to use') + help='Name or path of the huggingface tokenizer to use.') parser.add_argument( '--revision', type=str, default=None, - help='the specific model version to use. It can be a branch ' + help='The specific model version to use. It can be a branch ' 'name, a tag name, or a commit id. If unspecified, will use ' 'the default version.') parser.add_argument( '--code-revision', type=str, default=None, - help='the specific revision to use for the model code on ' + help='The specific revision to use for the model code on ' 'Hugging Face Hub. It can be a branch name, a tag name, or a ' 'commit id. If unspecified, will use the default version.') parser.add_argument( '--tokenizer-revision', type=str, default=None, - help='the specific tokenizer version to use. It can be a branch ' + help='The specific tokenizer version to use. It can be a branch ' 'name, a tag name, or a commit id. If unspecified, will use ' 'the default version.') - parser.add_argument('--tokenizer-mode', - type=str, - default=EngineArgs.tokenizer_mode, - choices=['auto', 'slow'], - help='tokenizer mode. "auto" will use the fast ' - 'tokenizer if available, and "slow" will ' - 'always use the slow tokenizer.') + parser.add_argument( + '--tokenizer-mode', + type=str, + default=EngineArgs.tokenizer_mode, + choices=['auto', 'slow'], + help='The tokenizer mode.\n\n* "auto" will use the ' + 'fast tokenizer if available.\n* "slow" will ' + 'always use the slow tokenizer.') parser.add_argument('--trust-remote-code', action='store_true', - help='trust remote code from huggingface') + help='Trust remote code from huggingface.') parser.add_argument('--download-dir', type=str, default=EngineArgs.download_dir, - help='directory to download and load the weights, ' + help='Directory to download and load the weights, ' 'default to the default cache dir of ' - 'huggingface') + 'huggingface.') parser.add_argument( '--load-format', type=str, @@ -140,19 +138,19 @@ def add_cli_args( choices=[ 'auto', 'pt', 'safetensors', 'npcache', 'dummy', 'tensorizer' ], - help='The format of the model weights to load. ' - '"auto" will try to load the weights in the safetensors format ' + help='The format of the model weights to load.\n\n' + '* "auto" will try to load the weights in the safetensors format ' 'and fall back to the pytorch bin format if safetensors format ' - 'is not available. ' - '"pt" will load the weights in the pytorch bin format. ' - '"safetensors" will load the weights in the safetensors format. ' - '"npcache" will load the weights in pytorch format and store ' - 'a numpy cache to speed up the loading. ' - '"dummy" will initialize the weights with random values, ' - 'which is mainly for profiling.' - '"tensorizer" will load the weights using tensorizer from CoreWeave' - 'which assumes tensorizer_uri is set to the location of the ' - 'serialized weights.') + 'is not available.\n' + '* "pt" will load the weights in the pytorch bin format.\n' + '* "safetensors" will load the weights in the safetensors format.\n' + '* "npcache" will load the weights in pytorch format and store ' + 'a numpy cache to speed up the loading.\n' + '* "dummy" will initialize the weights with random values, ' + 'which is mainly for profiling.\n' + '* "tensorizer" will load the weights using tensorizer from ' + 'CoreWeave which assumes tensorizer_uri is set to the location of ' + 'the serialized weights.') parser.add_argument( '--dtype', type=str, @@ -160,10 +158,14 @@ def add_cli_args( choices=[ 'auto', 'half', 'float16', 'bfloat16', 'float', 'float32' ], - help='data type for model weights and activations. ' - 'The "auto" option will use FP16 precision ' - 'for FP32 and FP16 models, and BF16 precision ' - 'for BF16 models.') + help='Data type for model weights and activations.\n\n' + '* "auto" will use FP16 precision for FP32 and FP16 models, and ' + 'BF16 precision for BF16 models.\n' + '* "half" for FP16. Recommended for AWQ quantization.\n' + '* "float16" is the same as "half".\n' + '* "bfloat16" for a balance between precision and range.\n' + '* "float" is shorthand for FP32 precision.\n' + '* "float32" for FP32 precision.') parser.add_argument( '--kv-cache-dtype', type=str, @@ -172,7 +174,7 @@ def add_cli_args( help='Data type for kv cache storage. If "auto", will use model ' 'data type. FP8_E5M2 (without scaling) is only supported on cuda ' 'version greater than 11.8. On ROCm (AMD GPU), FP8_E4M3 is instead ' - 'supported for common inference criteria. ') + 'supported for common inference criteria.') parser.add_argument( '--quantization-param-path', type=str, @@ -183,58 +185,59 @@ def add_cli_args( 'default to 1.0, which may cause accuracy issues. ' 'FP8_E5M2 (without scaling) is only supported on cuda version' 'greater than 11.8. On ROCm (AMD GPU), FP8_E4M3 is instead ' - 'supported for common inference criteria. ') + 'supported for common inference criteria.') parser.add_argument('--max-model-len', type=int, default=EngineArgs.max_model_len, - help='model context length. If unspecified, ' - 'will be automatically derived from the model.') + help='Model context length. If unspecified, will ' + 'be automatically derived from the model config.') parser.add_argument( '--guided-decoding-backend', type=str, default='outlines', choices=['outlines', 'lm-format-enforcer'], help='Which engine will be used for guided decoding' - ' (JSON schema / regex etc)') + ' (JSON schema / regex etc).') # Parallel arguments parser.add_argument('--worker-use-ray', action='store_true', - help='use Ray for distributed serving, will be ' - 'automatically set when using more than 1 GPU') + help='Use Ray for distributed serving, will be ' + 'automatically set when using more than 1 GPU.') parser.add_argument('--pipeline-parallel-size', '-pp', type=int, default=EngineArgs.pipeline_parallel_size, - help='number of pipeline stages') + help='Number of pipeline stages.') parser.add_argument('--tensor-parallel-size', '-tp', type=int, default=EngineArgs.tensor_parallel_size, - help='number of tensor parallel replicas') + help='Number of tensor parallel replicas.') parser.add_argument( '--max-parallel-loading-workers', type=int, default=EngineArgs.max_parallel_loading_workers, - help='load model sequentially in multiple batches, ' + help='Load model sequentially in multiple batches, ' 'to avoid RAM OOM when using tensor ' - 'parallel and large models') + 'parallel and large models.') parser.add_argument( '--ray-workers-use-nsight', action='store_true', - help='If specified, use nsight to profile ray workers') + help='If specified, use nsight to profile Ray workers.') # KV cache arguments parser.add_argument('--block-size', type=int, default=EngineArgs.block_size, choices=[8, 16, 32, 128], - help='token block size') + help='Token block size for contiguous chunks of ' + 'tokens.') parser.add_argument('--enable-prefix-caching', action='store_true', - help='Enables automatic prefix caching') + help='Enables automatic prefix caching.') parser.add_argument('--use-v2-block-manager', action='store_true', - help='Use BlockSpaceMangerV2') + help='Use BlockSpaceMangerV2.') parser.add_argument( '--num-lookahead-slots', type=int, @@ -247,18 +250,19 @@ def add_cli_args( parser.add_argument('--seed', type=int, default=EngineArgs.seed, - help='random seed') + help='Random seed for operations.') parser.add_argument('--swap-space', type=int, default=EngineArgs.swap_space, - help='CPU swap space size (GiB) per GPU') + help='CPU swap space size (GiB) per GPU.') parser.add_argument( '--gpu-memory-utilization', type=float, default=EngineArgs.gpu_memory_utilization, - help='the fraction of GPU memory to be used for ' - 'the model executor, which can range from 0 to 1.' - 'If unspecified, will use the default value of 0.9.') + help='The fraction of GPU memory to be used for the model ' + 'executor, which can range from 0 to 1. For example, a value of ' + '0.5 would imply 50%% GPU memory utilization. If unspecified, ' + 'will use the default value of 0.9.') parser.add_argument( '--num-gpu-blocks-override', type=int, @@ -268,21 +272,21 @@ def add_cli_args( parser.add_argument('--max-num-batched-tokens', type=int, default=EngineArgs.max_num_batched_tokens, - help='maximum number of batched tokens per ' - 'iteration') + help='Maximum number of batched tokens per ' + 'iteration.') parser.add_argument('--max-num-seqs', type=int, default=EngineArgs.max_num_seqs, - help='maximum number of sequences per iteration') + help='Maximum number of sequences per iteration.') parser.add_argument( '--max-logprobs', type=int, default=EngineArgs.max_logprobs, - help=('max number of log probs to return logprobs is specified in' - ' SamplingParams')) + help=('Max number of log probs to return logprobs is specified in' + ' SamplingParams.')) parser.add_argument('--disable-log-stats', action='store_true', - help='disable logging statistics') + help='Disable logging statistics.') # Quantization settings. parser.add_argument('--quantization', '-q', @@ -303,13 +307,13 @@ def add_cli_args( parser.add_argument('--max-context-len-to-capture', type=int, default=EngineArgs.max_context_len_to_capture, - help='maximum context length covered by CUDA ' + help='Maximum context length covered by CUDA ' 'graphs. When a sequence has context length ' 'larger than this, we fall back to eager mode.') parser.add_argument('--disable-custom-all-reduce', action='store_true', default=EngineArgs.disable_custom_all_reduce, - help='See ParallelConfig') + help='See ParallelConfig.') parser.add_argument('--tokenizer-pool-size', type=int, default=EngineArgs.tokenizer_pool_size, @@ -402,7 +406,7 @@ def add_cli_args( '--enable-chunked-prefill', action='store_true', help='If set, the prefill requests can be chunked based on the ' - 'max_num_batched_tokens') + 'max_num_batched_tokens.') parser.add_argument( '--speculative-model', @@ -416,7 +420,7 @@ def add_cli_args( type=int, default=None, help='The number of speculative tokens to sample from ' - 'the draft model in speculative decoding') + 'the draft model in speculative decoding.') parser.add_argument('--model-loader-extra-config', type=str, @@ -534,20 +538,31 @@ class AsyncEngineArgs(EngineArgs): max_log_len: Optional[int] = None @staticmethod - def add_cli_args( - parser: argparse.ArgumentParser) -> argparse.ArgumentParser: - parser = EngineArgs.add_cli_args(parser) + def add_cli_args(parser: argparse.ArgumentParser, + async_args_only: bool = False) -> argparse.ArgumentParser: + if not async_args_only: + parser = EngineArgs.add_cli_args(parser) parser.add_argument('--engine-use-ray', action='store_true', - help='use Ray to start the LLM engine in a ' + help='Use Ray to start the LLM engine in a ' 'separate process as the server process.') parser.add_argument('--disable-log-requests', action='store_true', - help='disable logging requests') + help='Disable logging requests.') parser.add_argument('--max-log-len', type=int, default=None, - help='max number of prompt characters or prompt ' - 'ID numbers being printed in log. ' - 'Default: unlimited.') + help='Max number of prompt characters or prompt ' + 'ID numbers being printed in log.' + '\n\nDefault: Unlimited') return parser + + +# These functions are used by sphinx to build the documentation +def _engine_args_parser(): + return EngineArgs.add_cli_args(argparse.ArgumentParser()) + + +def _async_engine_args_parser(): + return AsyncEngineArgs.add_cli_args(argparse.ArgumentParser(), + async_args_only=True)
vllm-project__vllm-5319
[Feature]: support `stream_options` option ### 🚀 The feature, motivation and pitch According to openAI doc: https://platform.openai.com/docs/api-reference/chat/create#chat-create-stream_options. The API provide the stream_options which can get token usage info for stream request. ### Alternatives _No response_ ### Additional context _No response_
[ { "content": "import time\nfrom typing import (AsyncGenerator, AsyncIterator, Callable, Dict, List,\n Optional)\nfrom typing import Sequence as GenericSequence\nfrom typing import Tuple\n\nfrom fastapi import Request\n\nfrom vllm.config import ModelConfig\nfrom vllm.engine.async_llm_engine im...
[ { "content": "import time\nfrom typing import (AsyncGenerator, AsyncIterator, Callable, Dict, List,\n Optional)\nfrom typing import Sequence as GenericSequence\nfrom typing import Tuple\n\nfrom fastapi import Request\n\nfrom vllm.config import ModelConfig\nfrom vllm.engine.async_llm_engine im...
diff --git a/tests/entrypoints/test_openai_server.py b/tests/entrypoints/test_openai_server.py index b7d0946ba724..d0fe08ae0ddd 100644 --- a/tests/entrypoints/test_openai_server.py +++ b/tests/entrypoints/test_openai_server.py @@ -478,8 +478,6 @@ async def test_completion_streaming(server, client: openai.AsyncOpenAI, temperature=0.0, ) single_output = single_completion.choices[0].text - single_usage = single_completion.usage - stream = await client.completions.create(model=model_name, prompt=prompt, max_tokens=5, @@ -495,7 +493,6 @@ async def test_completion_streaming(server, client: openai.AsyncOpenAI, assert finish_reason_count == 1 assert chunk.choices[0].finish_reason == "length" assert chunk.choices[0].text - assert chunk.usage == single_usage assert "".join(chunks) == single_output @@ -550,6 +547,138 @@ async def test_chat_streaming(server, client: openai.AsyncOpenAI, assert "".join(chunks) == output +@pytest.mark.asyncio +@pytest.mark.parametrize( + "model_name", + ["HuggingFaceH4/zephyr-7b-beta", "zephyr-lora"], +) +async def test_chat_completion_stream_options(server, + client: openai.AsyncOpenAI, + model_name: str): + messages = [{ + "role": "system", + "content": "You are a helpful assistant." + }, { + "role": "user", + "content": "What is the capital of France?" + }] + + # Test stream=True, stream_options={"include_usage": False} + stream = await client.chat.completions.create( + model=model_name, + messages=messages, + max_tokens=10, + temperature=0.0, + stream=True, + stream_options={"include_usage": False}) + async for chunk in stream: + assert chunk.usage is None + + # Test stream=True, stream_options={"include_usage": True} + stream = await client.chat.completions.create( + model=model_name, + messages=messages, + max_tokens=10, + temperature=0.0, + stream=True, + stream_options={"include_usage": True}) + + async for chunk in stream: + if chunk.choices[0].finish_reason is None: + assert chunk.usage is None + else: + assert chunk.usage is None + final_chunk = await stream.__anext__() + assert final_chunk.usage is not None + assert final_chunk.usage.prompt_tokens > 0 + assert final_chunk.usage.completion_tokens > 0 + assert final_chunk.usage.total_tokens == ( + final_chunk.usage.prompt_tokens + + final_chunk.usage.completion_tokens) + assert final_chunk.choices == [] + + # Test stream=False, stream_options={"include_usage": None} + with pytest.raises(BadRequestError): + await client.chat.completions.create( + model=model_name, + messages=messages, + max_tokens=10, + temperature=0.0, + stream=False, + stream_options={"include_usage": None}) + + # Test stream=False, stream_options={"include_usage": True} + with pytest.raises(BadRequestError): + await client.chat.completions.create( + model=model_name, + messages=messages, + max_tokens=10, + temperature=0.0, + stream=False, + stream_options={"include_usage": True}) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "model_name", + ["HuggingFaceH4/zephyr-7b-beta", "zephyr-lora"], +) +async def test_completion_stream_options(server, client: openai.AsyncOpenAI, + model_name: str): + prompt = "What is the capital of France?" + + # Test stream=True, stream_options={"include_usage": False} + stream = await client.completions.create( + model=model_name, + prompt=prompt, + max_tokens=5, + temperature=0.0, + stream=True, + stream_options={"include_usage": False}) + async for chunk in stream: + assert chunk.usage is None + + # Test stream=True, stream_options={"include_usage": True} + stream = await client.completions.create( + model=model_name, + prompt=prompt, + max_tokens=5, + temperature=0.0, + stream=True, + stream_options={"include_usage": True}) + async for chunk in stream: + if chunk.choices[0].finish_reason is None: + assert chunk.usage is None + else: + assert chunk.usage is None + final_chunk = await stream.__anext__() + assert final_chunk.usage is not None + assert final_chunk.usage.prompt_tokens > 0 + assert final_chunk.usage.completion_tokens > 0 + assert final_chunk.usage.total_tokens == ( + final_chunk.usage.prompt_tokens + + final_chunk.usage.completion_tokens) + assert final_chunk.choices == [] + + # Test stream=False, stream_options={"include_usage": None} + with pytest.raises(BadRequestError): + await client.completions.create(model=model_name, + prompt=prompt, + max_tokens=5, + temperature=0.0, + stream=False, + stream_options={"include_usage": None}) + + # Test stream=False, stream_options={"include_usage": True} + with pytest.raises(BadRequestError): + await client.completions.create(model=model_name, + prompt=prompt, + max_tokens=5, + temperature=0.0, + stream=False, + stream_options={"include_usage": True}) + + @pytest.mark.asyncio @pytest.mark.parametrize( # just test 1 lora hereafter @@ -1343,106 +1472,5 @@ async def test_batch_embedding(embedding_server, client: openai.AsyncOpenAI, assert embeddings.usage.total_tokens == 17 -@pytest.mark.parametrize( - "model_name", - [MODEL_NAME], -) -async def test_stream_options(server, client: openai.AsyncOpenAI, - model_name: str): - prompt = "What is the capital of France?" - - # Test stream=True, stream_options=None - stream = await client.completions.create( - model=model_name, - prompt=prompt, - max_tokens=5, - temperature=0.0, - stream=True, - stream_options=None, - ) - chunks = [] - async for chunk in stream: - chunks.append(chunk.choices[0].text) - assert len(chunks) > 0 - assert "usage" not in chunk - - # Test stream=True, stream_options={"include_usage": False} - stream = await client.completions.create( - model=model_name, - prompt=prompt, - max_tokens=5, - temperature=0.0, - stream=True, - stream_options={"include_usage": False}, - ) - chunks = [] - async for chunk in stream: - chunks.append(chunk.choices[0].text) - assert len(chunks) > 0 - assert "usage" not in chunk - - # Test stream=True, stream_options={"include_usage": True} - stream = await client.completions.create( - model=model_name, - prompt=prompt, - max_tokens=5, - temperature=0.0, - stream=True, - stream_options={"include_usage": True}, - ) - chunks = [] - finish_reason_count = 0 - async for chunk in stream: - if chunk.choices[0].finish_reason is None: - assert chunk.usage is None - chunks.append(chunk.choices[0].text) - else: - assert chunk.usage is None - finish_reason_count += 1 - - # The last message should have usage and no choices - last_message = await stream.__anext__() - assert last_message.usage is not None - assert last_message.usage.prompt_tokens > 0 - assert last_message.usage.completion_tokens > 0 - assert last_message.usage.total_tokens == ( - last_message.usage.prompt_tokens + - last_message.usage.completion_tokens) - assert last_message.choices == [] - - # Test stream=False, stream_options={"include_usage": None} - with pytest.raises(BadRequestError): - await client.completions.create( - model=model_name, - prompt=prompt, - max_tokens=5, - temperature=0.0, - stream=False, - stream_options={"include_usage": None}, - ) - - # Test stream=False, stream_options={"include_usage": False} - with pytest.raises(BadRequestError): - await client.completions.create( - model=model_name, - prompt=prompt, - max_tokens=5, - temperature=0.0, - stream=False, - stream_options={"include_usage": False}, - ) - - # Test stream=False, stream_options={"include_usage": True} - with pytest.raises(BadRequestError): - await client.completions.create( - model=model_name, - prompt=prompt, - max_tokens=5, - temperature=0.0, - stream=False, - stream_options={"include_usage": True}, - ) - - if __name__ == "__main__": pytest.main([__file__]) diff --git a/vllm/entrypoints/openai/protocol.py b/vllm/entrypoints/openai/protocol.py index fa33318786b9..9424ccc959d1 100644 --- a/vllm/entrypoints/openai/protocol.py +++ b/vllm/entrypoints/openai/protocol.py @@ -346,6 +346,7 @@ class CompletionRequest(OpenAIBaseModel): le=torch.iinfo(torch.long).max) stop: Optional[Union[str, List[str]]] = Field(default_factory=list) stream: Optional[bool] = False + stream_options: Optional[StreamOptions] = None suffix: Optional[str] = None temperature: Optional[float] = 1.0 top_p: Optional[float] = 1.0 @@ -482,6 +483,14 @@ def check_logprobs(cls, data): " in the interval [0, 5].")) return data + @model_validator(mode="before") + @classmethod + def validate_stream_options(cls, data): + if data.get("stream_options") and not data.get("stream"): + raise ValueError( + "Stream options can only be defined when stream is True.") + return data + class EmbeddingRequest(BaseModel): # Ordered by official OpenAI API documentation diff --git a/vllm/entrypoints/openai/serving_chat.py b/vllm/entrypoints/openai/serving_chat.py index c025e7e96826..dae60e4ec99f 100644 --- a/vllm/entrypoints/openai/serving_chat.py +++ b/vllm/entrypoints/openai/serving_chat.py @@ -441,25 +441,24 @@ async def chat_completion_stream_generator( yield f"data: {data}\n\n" finish_reason_sent[i] = True - if (request.stream_options - and request.stream_options.include_usage): - final_usage = UsageInfo( - prompt_tokens=prompt_tokens, - completion_tokens=previous_num_tokens[i], - total_tokens=prompt_tokens + - previous_num_tokens[i], - ) + if (request.stream_options + and request.stream_options.include_usage): + final_usage = UsageInfo( + prompt_tokens=prompt_tokens, + completion_tokens=previous_num_tokens[i], + total_tokens=prompt_tokens + previous_num_tokens[i], + ) - final_usage_chunk = ChatCompletionStreamResponse( - id=request_id, - object=chunk_object_type, - created=created_time, - choices=[], - model=model_name, - usage=final_usage) - final_usage_data = (final_usage_chunk.model_dump_json( - exclude_unset=True, exclude_none=True)) - yield f"data: {final_usage_data}\n\n" + final_usage_chunk = ChatCompletionStreamResponse( + id=request_id, + object=chunk_object_type, + created=created_time, + choices=[], + model=model_name, + usage=final_usage) + final_usage_data = (final_usage_chunk.model_dump_json( + exclude_unset=True, exclude_none=True)) + yield f"data: {final_usage_data}\n\n" except ValueError as e: # TODO: Use a vllm-specific Validation Error diff --git a/vllm/entrypoints/openai/serving_completion.py b/vllm/entrypoints/openai/serving_completion.py index 572878b5527d..c3c40f2b97d1 100644 --- a/vllm/entrypoints/openai/serving_completion.py +++ b/vllm/entrypoints/openai/serving_completion.py @@ -264,7 +264,8 @@ async def completion_stream_generator( ) else: final_usage = None - response_json = CompletionStreamResponse( + + chunk = CompletionStreamResponse( id=request_id, created=created_time, model=model_name, @@ -276,10 +277,27 @@ async def completion_stream_generator( finish_reason=finish_reason, stop_reason=stop_reason, ) - ], - usage=final_usage, - ).model_dump_json(exclude_unset=True) + ]) + if (request.stream_options + and request.stream_options.include_usage): + chunk.usage = None + + response_json = chunk.model_dump_json(exclude_unset=True) yield f"data: {response_json}\n\n" + + if (request.stream_options + and request.stream_options.include_usage): + final_usage_chunk = CompletionStreamResponse( + id=request_id, + created=created_time, + model=model_name, + choices=[], + usage=final_usage, + ) + final_usage_data = (final_usage_chunk.model_dump_json( + exclude_unset=True, exclude_none=True)) + yield f"data: {final_usage_data}\n\n" + except ValueError as e: # TODO: Use a vllm-specific Validation Error data = self.create_streaming_error_response(str(e))
pyro-ppl__numpyro-747
Port autoguide AutoNormal from Pyro I am trying to fit a bnn in #743 with ELBO loss but couldn't optimize it with stochastic KL. It might work if I use AutoNormal with TraceMeanField_ELBO, so I would like to add this feature to try that option.
[ { "content": "# Copyright Contributors to the Pyro project.\n# SPDX-License-Identifier: Apache-2.0\nfrom collections import namedtuple\nfrom functools import update_wrapper\nimport math\n\nfrom jax import jit, lax, random, vmap\nfrom jax.dtypes import canonicalize_dtype\nfrom jax.lib import xla_bridge\nimport j...
[ { "content": "# Copyright Contributors to the Pyro project.\n# SPDX-License-Identifier: Apache-2.0\nfrom collections import namedtuple\nfrom functools import update_wrapper\nimport math\n\nfrom jax import jit, lax, random, vmap\nfrom jax.dtypes import canonicalize_dtype\nfrom jax.lib import xla_bridge\nimport j...
diff --git a/docs/source/autoguide.rst b/docs/source/autoguide.rst index 37e45dba4..bec58cfcb 100644 --- a/docs/source/autoguide.rst +++ b/docs/source/autoguide.rst @@ -58,3 +58,11 @@ AutoLowRankMultivariateNormal :undoc-members: :show-inheritance: :member-order: bysource + +AutoNormal +---------- +.. autoclass:: numpyro.infer.autoguide.AutoNormal + :members: + :undoc-members: + :show-inheritance: + :member-order: bysource diff --git a/numpyro/distributions/util.py b/numpyro/distributions/util.py index 0e329d8bd..7a0dc505b 100644 --- a/numpyro/distributions/util.py +++ b/numpyro/distributions/util.py @@ -428,6 +428,23 @@ def body_fn(*args): return jnp.sign(u) * jnp.arccos(w) +# TODO: use funsor implementation +def periodic_repeat(x, size, dim): + """ + Repeat a ``period``-sized array up to given ``size``. + """ + assert isinstance(size, int) and size >= 0 + assert isinstance(dim, int) + if dim >= 0: + dim -= jnp.ndim(x) + + period = jnp.shape(x)[dim] + repeats = (size + period - 1) // period + result = jnp.repeat(x, repeats, axis=dim) + result = result[(Ellipsis, slice(None, size)) + (slice(None),) * (-1 - dim)] + return result + + # The is sourced from: torch.distributions.util.py # # Copyright (c) 2016- Facebook, Inc (Adam Paszke) diff --git a/numpyro/infer/autoguide.py b/numpyro/infer/autoguide.py index 5b745481a..dad4d4cec 100644 --- a/numpyro/infer/autoguide.py +++ b/numpyro/infer/autoguide.py @@ -3,6 +3,7 @@ # Adapted from pyro.infer.autoguide from abc import ABC, abstractmethod +from contextlib import ExitStack import warnings from jax import hessian, lax, random, tree_map @@ -23,7 +24,7 @@ UnpackTransform, biject_to ) -from numpyro.distributions.util import cholesky_of_inverse, sum_rightmost +from numpyro.distributions.util import cholesky_of_inverse, periodic_repeat, sum_rightmost from numpyro.infer.elbo import ELBO from numpyro.infer.util import init_to_uniform, initialize_model from numpyro.nn.auto_reg_nn import AutoregressiveNN @@ -36,6 +37,7 @@ 'AutoDiagonalNormal', 'AutoLaplaceApproximation', 'AutoLowRankMultivariateNormal', + 'AutoNormal', 'AutoMultivariateNormal', 'AutoBNAFNormal', 'AutoIAFNormal', @@ -50,13 +52,39 @@ class AutoGuide(ABC): :param callable model: a pyro model :param str prefix: a prefix that will be prefixed to all param internal sites + :param callable init_strategy: A per-site initialization function. + See :ref:`init_strategy` section for available functions. + :param callable create_plates: An optional function inputing the same + ``*args,**kwargs`` as ``model()`` and returning a :class:`numpyro.plate` + or iterable of plates. Plates not returned will be created + automatically as usual. This is useful for data subsampling. """ - def __init__(self, model, prefix='auto'): - assert isinstance(prefix, str) + def __init__(self, model, *, prefix="auto", init_strategy=init_to_uniform, create_plates=None): self.model = model self.prefix = prefix + self.init_strategy = init_strategy + self.create_plates = create_plates self.prototype_trace = None + self._prototype_frames = {} + self._prototype_frame_full_sizes = {} + + def _create_plates(self, *args, **kwargs): + if self.create_plates is None: + self.plates = {} + else: + plates = self.create_plates(*args, **kwargs) + if isinstance(plates, numpyro.plate): + plates = [plates] + assert all(isinstance(p, numpyro.plate) for p in plates), \ + "create_plates() returned a non-plate" + self.plates = {p.name: p for p in plates} + for name, frame in sorted(self._prototype_frames.items()): + if name not in self.plates: + full_size = self._prototype_frame_full_sizes[name] + self.plates[name] = numpyro.plate(name, full_size, dim=frame.dim, + subsample_size=frame.size) + return self.plates @abstractmethod def __call__(self, *args, **kwargs): @@ -81,19 +109,155 @@ def sample_posterior(self, rng_key, params, *args, **kwargs): """ raise NotImplementedError - @abstractmethod - def _sample_latent(self, *args, **kwargs): + def _setup_prototype(self, *args, **kwargs): + rng_key = numpyro.sample("_{}_rng_key_setup".format(self.prefix), dist.PRNGIdentity()) + with handlers.block(): + init_params, _, self._postprocess_fn, self.prototype_trace = initialize_model( + rng_key, self.model, + init_strategy=self.init_strategy, + dynamic_args=False, + model_args=args, + model_kwargs=kwargs) + self._init_locs = init_params[0] + + self._prototype_frames = {} + self._prototype_plate_sizes = {} + for name, site in self.prototype_trace.items(): + if site["type"] == "sample": + for frame in site["cond_indep_stack"]: + self._prototype_frames[frame.name] = frame + elif site["type"] == "plate": + self._prototype_frame_full_sizes[name] = site["args"][0] + + +class AutoNormal(AutoGuide): + """ + This implementation of :class:`AutoGuide` uses Normal distributions + to construct a guide over the entire latent space. The guide does not + depend on the model's ``*args, **kwargs``. + + This should be equivalent to :class: `AutoDiagonalNormal` , but with + more convenient site names and with better support for mean field ELBO. + + Usage:: + + guide = AutoNormal(model) + svi = SVI(model, guide, ...) + + :param callable model: A NumPyro model. + :param str prefix: a prefix that will be prefixed to all param internal sites. + :param callable init_strategy: A per-site initialization function. + See :ref:`init_strategy` section for available functions. + :param float init_scale: Initial scale for the standard deviation of each + (unconstrained transformed) latent variable. + :param callable create_plates: An optional function inputing the same + ``*args,**kwargs`` as ``model()`` and returning a :class:`numpyro.plate` + or iterable of plates. Plates not returned will be created + automatically as usual. This is useful for data subsampling. + """ + def __init__(self, model, *, prefix="auto", init_strategy=init_to_uniform, init_scale=0.1, + create_plates=None): + # TODO: rename `init_strategy` to `init_loc_fn` to be consistent with Pyro + self._init_scale = init_scale + self._event_dims = {} + super().__init__(model, prefix=prefix, init_strategy=init_strategy, create_plates=create_plates) + + def _setup_prototype(self, *args, **kwargs): + super()._setup_prototype(*args, **kwargs) + + for name, site in self.prototype_trace.items(): + if site["type"] != "sample" or isinstance(site["fn"], dist.PRNGIdentity) or site["is_observed"]: + continue + + event_dim = site["fn"].event_dim + jnp.ndim(self._init_locs[name]) - jnp.ndim(site["value"]) + self._event_dims[name] = event_dim + + # If subsampling, repeat init_value to full size. + for frame in site["cond_indep_stack"]: + full_size = self._prototype_frame_full_sizes[frame.name] + if full_size != frame.size: + dim = frame.dim - event_dim + self._init_locs[name] = periodic_repeat(self._init_locs[name], full_size, dim) + + def __call__(self, *args, **kwargs): """ - Samples an encoded latent given the same ``*args, **kwargs`` as the - base ``model``. + An automatic guide with the same ``*args, **kwargs`` as the base ``model``. + + :return: A dict mapping sample site name to sampled value. + :rtype: dict """ - raise NotImplementedError + if self.prototype_trace is None: + # run model to inspect the model structure + self._setup_prototype(*args, **kwargs) - def _setup_prototype(self, *args, **kwargs): - # run the model so we can inspect its structure - rng_key = numpyro.sample("_{}_rng_key_setup".format(self.prefix), dist.PRNGIdentity()) - model = handlers.seed(self.model, rng_key) - self.prototype_trace = handlers.block(handlers.trace(model).get_trace)(*args, **kwargs) + plates = self._create_plates(*args, **kwargs) + result = {} + for name, site in self.prototype_trace.items(): + if site["type"] != "sample" or isinstance(site["fn"], dist.PRNGIdentity) or site["is_observed"]: + continue + + event_dim = self._event_dims[name] + init_loc = self._init_locs[name] + with ExitStack() as stack: + for frame in site["cond_indep_stack"]: + stack.enter_context(plates[frame.name]) + + site_loc = numpyro.param("{}_{}_loc".format(name, self.prefix), init_loc, + event_dim=event_dim) + site_scale = numpyro.param("{}_{}_scale".format(name, self.prefix), + jnp.full(jnp.shape(init_loc), self._init_scale), + constraint=constraints.positive, + event_dim=event_dim) + + site_fn = dist.Normal(site_loc, site_scale).to_event(event_dim) + if site["fn"].support in [constraints.real, constraints.real_vector]: + result[name] = numpyro.sample(name, site_fn) + else: + unconstrained_value = numpyro.sample("{}_unconstrained".format(name), site_fn, + infer={"is_auxiliary": True}) + + transform = biject_to(site['fn'].support) + value = transform(unconstrained_value) + log_density = - transform.log_abs_det_jacobian(unconstrained_value, value) + log_density = sum_rightmost(log_density, + jnp.ndim(log_density) - jnp.ndim(value) + site["fn"].event_dim) + delta_dist = dist.Delta(value, log_density=log_density, event_dim=site["fn"].event_dim) + result[name] = numpyro.sample(name, delta_dist) + + return result + + def _constrain(self, latent_samples): + name = list(latent_samples)[0] + sample_shape = jnp.shape(latent_samples[name])[ + :jnp.ndim(latent_samples[name]) - jnp.ndim(self._init_locs[name])] + if sample_shape: + flatten_samples = tree_map(lambda x: jnp.reshape(x, (-1,) + jnp.shape(x)[len(sample_shape):]), + latent_samples) + contrained_samples = lax.map(self._postprocess_fn, flatten_samples) + return tree_map(lambda x: jnp.reshape(x, sample_shape + jnp.shape(x)[1:]), + contrained_samples) + else: + return self._postprocess_fn(latent_samples) + + def sample_posterior(self, rng_key, params, sample_shape=()): + locs = {k: params["{}_{}_loc".format(k, self.prefix)] for k in self._init_locs} + scales = {k: params["{}_{}_scale".format(k, self.prefix)] for k in locs} + with handlers.seed(rng_seed=rng_key): + latent_samples = {} + for k in locs: + latent_samples[k] = numpyro.sample(k, dist.Normal(locs[k], scales[k]).expand_by(sample_shape)) + return self._constrain(latent_samples) + + def median(self, params): + locs = {k: params["{}_{}_loc".format(k, self.prefix)] for k, v in self._init_locs.items()} + return self._constrain(locs) + + def quantiles(self, params, quantiles): + quantiles = jnp.array(quantiles)[..., None] + locs = {k: params["{}_{}_loc".format(k, self.prefix)] for k in self._init_locs} + scales = {k: params["{}_{}_scale".format(k, self.prefix)] for k in locs} + latent = {k: dist.Normal(locs[k], scales[k]).icdf(quantiles) for k in locs} + return self._constrain(latent) class AutoContinuous(AutoGuide): @@ -117,21 +281,9 @@ class AutoContinuous(AutoGuide): :param callable init_strategy: A per-site initialization function. See :ref:`init_strategy` section for available functions. """ - def __init__(self, model, prefix="auto", init_strategy=init_to_uniform): - self.init_strategy = init_strategy - super(AutoContinuous, self).__init__(model, prefix=prefix) - def _setup_prototype(self, *args, **kwargs): - rng_key = numpyro.sample("_{}_rng_key_setup".format(self.prefix), dist.PRNGIdentity()) - with handlers.block(): - init_params, _, self._postprocess_fn, self.prototype_trace = initialize_model( - rng_key, self.model, - init_strategy=self.init_strategy, - dynamic_args=False, - model_args=args, - model_kwargs=kwargs) - - self._init_latent, unpack_latent = ravel_pytree(init_params[0]) + super()._setup_prototype(*args, **kwargs) + self._init_latent, unpack_latent = ravel_pytree(self._init_locs) # this is to match the behavior of Pyro, where we can apply # unpack_latent for a batch of samples self._unpack_latent = UnpackTransform(unpack_latent) @@ -147,7 +299,8 @@ def _get_posterior(self): def _sample_latent(self, *args, **kwargs): sample_shape = kwargs.pop('sample_shape', ()) posterior = self._get_posterior() - return numpyro.sample("_{}_latent".format(self.prefix), posterior, sample_shape=sample_shape) + return numpyro.sample("_{}_latent".format(self.prefix), posterior.expand_by(sample_shape), + infer={"is_auxiliary": True}) def __call__(self, *args, **kwargs): """ @@ -181,6 +334,7 @@ def __call__(self, *args, **kwargs): def _unpack_and_constrain(self, latent_sample, params): def unpack_single_latent(latent): unpacked_samples = self._unpack_latent(latent) + # TODO: this seems to be a legacy behavior? why we need to add param here? # add param sites in model unpacked_samples.update({k: v for k, v in params.items() if k in self.prototype_trace and self.prototype_trace[k]['type'] == 'param'}) @@ -289,11 +443,11 @@ class AutoDiagonalNormal(AutoContinuous): guide = AutoDiagonalNormal(model, ...) svi = SVI(model, guide, ...) """ - def __init__(self, model, prefix="auto", init_strategy=init_to_uniform, init_scale=0.1): + def __init__(self, model, *, prefix="auto", init_strategy=init_to_uniform, init_scale=0.1): if init_scale <= 0: raise ValueError("Expected init_scale > 0. but got {}".format(init_scale)) self._init_scale = init_scale - super().__init__(model, prefix, init_strategy) + super().__init__(model, prefix=prefix, init_strategy=init_strategy) def _get_posterior(self): loc = numpyro.param('{}_loc'.format(self.prefix), self._init_latent) @@ -338,11 +492,11 @@ class AutoMultivariateNormal(AutoContinuous): guide = AutoMultivariateNormal(model, ...) svi = SVI(model, guide, ...) """ - def __init__(self, model, prefix="auto", init_strategy=init_to_uniform, init_scale=0.1): + def __init__(self, model, *, prefix="auto", init_strategy=init_to_uniform, init_scale=0.1): if init_scale <= 0: raise ValueError("Expected init_scale > 0. but got {}".format(init_scale)) self._init_scale = init_scale - super().__init__(model, prefix, init_strategy) + super().__init__(model, prefix=prefix, init_strategy=init_strategy) def _get_posterior(self): loc = numpyro.param('{}_loc'.format(self.prefix), self._init_latent) @@ -388,7 +542,7 @@ class AutoLowRankMultivariateNormal(AutoContinuous): guide = AutoLowRankMultivariateNormal(model, rank=2, ...) svi = SVI(model, guide, ...) """ - def __init__(self, model, prefix="auto", init_strategy=init_to_uniform, init_scale=0.1, rank=None): + def __init__(self, model, *, prefix="auto", init_strategy=init_to_uniform, init_scale=0.1, rank=None): if init_scale <= 0: raise ValueError("Expected init_scale > 0. but got {}".format(init_scale)) self._init_scale = init_scale @@ -530,7 +684,7 @@ class AutoIAFNormal(AutoContinuous): :param callable nonlinearity: the nonlinearity to use in the feedforward network. Defaults to :func:`jax.experimental.stax.Elu`. """ - def __init__(self, model, prefix="auto", init_strategy=init_to_uniform, + def __init__(self, model, *, prefix="auto", init_strategy=init_to_uniform, num_flows=3, hidden_dims=None, skip_connections=False, nonlinearity=stax.Elu): self.num_flows = num_flows # 2-layer, stax.Elu, skip_connections=False by default following the experiments in @@ -587,7 +741,7 @@ class AutoBNAFNormal(AutoContinuous): input dimension. This corresponds to both :math:`a` and :math:`b` in reference [1]. The elements of hidden_factors must be integers. """ - def __init__(self, model, prefix="auto", init_strategy=init_to_uniform, num_flows=1, + def __init__(self, model, *, prefix="auto", init_strategy=init_to_uniform, num_flows=1, hidden_factors=[8, 8]): self.num_flows = num_flows self._hidden_factors = hidden_factors diff --git a/test/test_autoguide.py b/test/test_autoguide.py index 53b21a4d6..932a35e13 100644 --- a/test/test_autoguide.py +++ b/test/test_autoguide.py @@ -6,12 +6,13 @@ from numpy.testing import assert_allclose import pytest -from jax import lax, random +from jax import jit, lax, random import jax.numpy as jnp from jax.test_util import check_eq import numpyro -from numpyro import optim +from numpyro import handlers, optim +from numpyro.contrib.control_flow import scan import numpyro.distributions as dist from numpyro.distributions import constraints, transforms from numpyro.distributions.flows import InverseAutoregressiveTransform @@ -23,7 +24,8 @@ AutoIAFNormal, AutoLaplaceApproximation, AutoLowRankMultivariateNormal, - AutoMultivariateNormal + AutoMultivariateNormal, + AutoNormal ) from numpyro.infer.initialization import init_to_median from numpyro.infer.reparam import TransformReparam @@ -40,6 +42,7 @@ AutoMultivariateNormal, AutoLaplaceApproximation, AutoLowRankMultivariateNormal, + AutoNormal, ]) def test_beta_bernoulli(auto_class): data = jnp.array([[1.0] * 8 + [0.0] * 2, @@ -73,6 +76,7 @@ def body_fn(i, val): AutoMultivariateNormal, AutoLaplaceApproximation, AutoLowRankMultivariateNormal, + AutoNormal, ]) def test_logistic_regression(auto_class): N, dim = 3000, 3 @@ -300,3 +304,49 @@ def model(y): svi = SVI(model, guide, optim.Adam(0.003), ELBO(), y=y) svi_state = svi.init(random.PRNGKey(2)) lax.scan(lambda state, i: svi.update(state), svi_state, jnp.zeros(10000)) + + +@pytest.mark.parametrize("auto_class", [AutoNormal]) +def test_subsample_guide(auto_class): + + # The model adapted from tutorial/source/easyguide.ipynb + def model(batch, subsample, full_size): + drift = numpyro.sample("drift", dist.LogNormal(-1, 0.5)) + with handlers.substitute(data={"data": subsample}): + plate = numpyro.plate("data", full_size, subsample_size=len(subsample)) + assert plate.size == 50 + + def transition_fn(z_prev, y_curr): + with plate: + z_curr = numpyro.sample("state", dist.Normal(z_prev, drift)) + y_curr = numpyro.sample("obs", dist.Bernoulli(logits=z_curr), obs=y_curr) + return z_curr, y_curr + + _, result = scan(transition_fn, jnp.zeros(len(subsample)), batch, length=num_time_steps) + return result + + def create_plates(batch, subsample, full_size): + with handlers.substitute(data={"data": subsample}): + return numpyro.plate("data", full_size, subsample_size=subsample.shape[0]) + + guide = auto_class(model, create_plates=create_plates) + + full_size = 50 + batch_size = 20 + num_time_steps = 8 + with handlers.seed(rng_seed=0): + data = model(None, jnp.arange(full_size), full_size) + assert data.shape == (num_time_steps, full_size) + + svi = SVI(model, guide, optim.Adam(0.02), ELBO()) + svi_state = svi.init(random.PRNGKey(0), data[:, :batch_size], + jnp.arange(batch_size), full_size=full_size) + update_fn = jit(svi.update, static_argnums=(3,)) + for epoch in range(2): + beg = 0 + while beg < full_size: + end = min(full_size, beg + batch_size) + subsample = jnp.arange(beg, end) + batch = data[:, beg:end] + beg = end + svi_state, loss = update_fn(svi_state, batch, subsample, full_size)
pyro-ppl__numpyro-1581
inf's with TruncatedNormal I've seen the discussion in #1184 and #1185, but I'm still seeing this issue with numpyro v0.10.1. Here's a MWE, comparing to scipy's `scipy.stats.truncnorm` implementation: ```python import numpyro numpyro.enable_x64() import numpyro.distributions as dist import jax.numpy as jnp from scipy.stats import truncnorm loc = 1.35 scale = jnp.geomspace(0.01, 1, 10) low, high = (-20, -1.0) a, b = (low - loc) / scale, (high - loc) / scale x = -15. scipy_val = truncnorm.logpdf(x, loc=loc, scale=scale, a=a, b=b) numpyro_val = dist.TruncatedNormal(loc, scale, low=low, high=high).log_prob(x) ``` (arbitrary values chosen to get into the tail) Comparing the output values: ```python >>> scipy_val array([-1.30898994e+06, -4.70421167e+05, -1.69055833e+05, -6.07514028e+04, -2.18294637e+04, -7.84229794e+03, -2.81622225e+03, -1.01058785e+03, -3.62302368e+02, -1.29911728e+02]) >>> numpyro_val DeviceArray([ inf, inf, inf, inf, -21829.46367826, -7842.29793866, -2816.22224529, -1010.58784742, -362.30236837, -129.91172764], dtype=float64) ``` It's possible to avoid this by special-casing the truncated normal distribution, as I [recently implemented in Jax](https://github.com/google/jax/pull/12646) -- it would be great to have this in numpyro as well. ```python from jax.scipy.stats import truncnorm as jax_truncnorm jax_val = jax_truncnorm.logpdf(x, loc=loc, scale=scale, a=a, b=b) print(jax_val) DeviceArray([-1.30898994e+06, -4.70421167e+05, -1.69055833e+05, -6.07514028e+04, -2.18294637e+04, -7.84229794e+03, -2.81622225e+03, -1.01058785e+03, -3.62302368e+02, -1.29911728e+02], dtype=float64) ``` Would you consider a PR to special-case `TruncatedNormal`? I'm not familiar with the numpyro codebase but have just started using it and am loving it - thanks for the work and maintenance on this project!
[ { "content": "# Copyright Contributors to the Pyro project.\n# SPDX-License-Identifier: Apache-2.0\n\n# The implementation largely follows the design in PyTorch's `torch.distributions`\n#\n# Copyright (c) 2016- Facebook, Inc (Adam Paszke)\n# Copyright (c) 2014- Facebook, Inc (Soumi...
[ { "content": "# Copyright Contributors to the Pyro project.\n# SPDX-License-Identifier: Apache-2.0\n\n# The implementation largely follows the design in PyTorch's `torch.distributions`\n#\n# Copyright (c) 2016- Facebook, Inc (Adam Paszke)\n# Copyright (c) 2014- Facebook, Inc (Soumi...
diff --git a/numpyro/distributions/continuous.py b/numpyro/distributions/continuous.py index 15d9ac412..c7e20c97a 100644 --- a/numpyro/distributions/continuous.py +++ b/numpyro/distributions/continuous.py @@ -47,6 +47,7 @@ xlog1py, xlogy, ) +from jax.scipy.stats import norm as jax_norm from numpyro.distributions import constraints from numpyro.distributions.discrete import _to_logits_bernoulli @@ -2077,6 +2078,9 @@ def cdf(self, value): scaled = (value - self.loc) / self.scale return ndtr(scaled) + def log_cdf(self, value): + return jax_norm.logcdf(value, loc=self.loc, scale=self.scale) + def icdf(self, q): return self.loc + self.scale * ndtri(q) diff --git a/numpyro/distributions/truncated.py b/numpyro/distributions/truncated.py index 098512718..fc78b2d22 100644 --- a/numpyro/distributions/truncated.py +++ b/numpyro/distributions/truncated.py @@ -18,6 +18,7 @@ ) from numpyro.distributions.distribution import Distribution from numpyro.distributions.util import ( + clamp_probs, is_prng_key, lazy_property, promote_shapes, @@ -249,6 +250,23 @@ def _tail_prob_at_high(self): sign = jnp.where(loc >= self.low, 1.0, -1.0) return self.base_dist.cdf(loc - sign * (loc - self.high)) + @lazy_property + def _log_diff_tail_probs(self): + # use log_cdf method, if available, to avoid inf's in log_prob + # fall back to cdf, if log_cdf not available + log_cdf = getattr(self.base_dist, "log_cdf", None) + if callable(log_cdf): + return logsumexp( + a=jnp.stack([log_cdf(self.high), log_cdf(self.low)], axis=-1), + axis=-1, + b=jnp.array([1, -1]), # subtract low from high + ) + + else: + loc = self.base_dist.loc + sign = jnp.where(loc >= self.low, 1.0, -1.0) + return jnp.log(sign * (self._tail_prob_at_high - self._tail_prob_at_low)) + def sample(self, key, sample_shape=()): assert is_prng_key(key) dtype = jnp.result_type(float) @@ -266,7 +284,7 @@ def sample(self, key, sample_shape=()): loc = self.base_dist.loc sign = jnp.where(loc >= self.low, 1.0, -1.0) return (1 - sign) * loc + sign * self.base_dist.icdf( - (1 - u) * self._tail_prob_at_low + u * self._tail_prob_at_high + clamp_probs((1 - u) * self._tail_prob_at_low + u * self._tail_prob_at_high) ) @validate_sample @@ -276,10 +294,7 @@ def log_prob(self, value): # cdf(high) - cdf(low) = as-is # if low > loc # cdf(high) - cdf(low) = cdf(2 * loc - low) - cdf(2 * loc - high) - sign = jnp.where(self.base_dist.loc >= self.low, 1.0, -1.0) - return self.base_dist.log_prob(value) - jnp.log( - sign * (self._tail_prob_at_high - self._tail_prob_at_low) - ) + return self.base_dist.log_prob(value) - self._log_diff_tail_probs def tree_flatten(self): base_flatten, base_aux = self.base_dist.tree_flatten() diff --git a/test/test_distributions.py b/test/test_distributions.py index 6a87ef4f0..fcfe5e284 100644 --- a/test/test_distributions.py +++ b/test/test_distributions.py @@ -19,6 +19,7 @@ import jax.numpy as jnp import jax.random as random from jax.scipy.special import expit, logsumexp +from jax.scipy.stats import norm as jax_norm, truncnorm as jax_truncnorm from jax.tree_util import tree_map import numpyro.distributions as dist @@ -2758,3 +2759,46 @@ def f(x): x = dist.Multinomial(10, probs).sample(key) y = jax.jit(f)(x) assert_allclose(x, y, rtol=1e-6) + + +def test_normal_log_cdf(): + # test if log_cdf method agrees with jax.scipy.stats.norm.logcdf + # and if exp(log_cdf) agrees with cdf + loc = jnp.array([[0.0, -10.0, 20.0]]) + scale = jnp.array([[1, 5, 7]]) + values = jnp.linspace(-5, 5, 100).reshape(-1, 1) + numpyro_log_cdf = dist.Normal(loc=loc, scale=scale).log_cdf(values) + numpyro_cdf = dist.Normal(loc=loc, scale=scale).cdf(values) + jax_log_cdf = jax_norm.logcdf(loc=loc, scale=scale, x=values) + assert_allclose(numpyro_log_cdf, jax_log_cdf) + assert_allclose(jnp.exp(numpyro_log_cdf), numpyro_cdf, rtol=1e-6) + + +@pytest.mark.parametrize( + "value", + [ + -15.0, + jnp.array([[-15.0], [-10.0], [-5.0]]), + jnp.array([[[-15.0], [-10.0], [-5.0]], [[-14.0], [-9.0], [-4.0]]]), + ], +) +def test_truncated_normal_log_prob_in_tail(value): + # define set of distributions truncated in tail of distribution + loc = 1.35 + scale = jnp.geomspace(0.01, 1, 10) + low, high = (-20, -1.0) + a, b = (low - loc) / scale, (high - loc) / scale # rescale for jax input + + numpyro_log_prob = dist.TruncatedNormal(loc, scale, low=low, high=high).log_prob( + value + ) + jax_log_prob = jax_truncnorm.logpdf(value, loc=loc, scale=scale, a=a, b=b) + assert_allclose(numpyro_log_prob, jax_log_prob, rtol=1e-06) + + +def test_sample_truncated_normal_in_tail(): + # test, if samples from distributions truncated in + # tail of distribution returns any inf's + tail_dist = dist.TruncatedNormal(loc=0, scale=1, low=-16, high=-15) + samples = tail_dist.sample(random.PRNGKey(0), sample_shape=(10_000,)) + assert ~jnp.isinf(samples).any()
pyro-ppl__numpyro-984
Allow to set an additional max tree depth during warmup phase This could be useful (needs some experiments though) in cases NUTS trajectories are long and it is slow to collect samples to estimate mass matrix during warmup phase. The side effect can be warmup samples are more correlated, so the estimated mass matrix might be not good.
[ { "content": "# Copyright Contributors to the Pyro project.\n# SPDX-License-Identifier: Apache-2.0\n\nfrom collections import OrderedDict, namedtuple\n\nfrom jax import grad, jacfwd, random, value_and_grad, vmap\nfrom jax.flatten_util import ravel_pytree\nimport jax.numpy as jnp\nfrom jax.ops import index_updat...
[ { "content": "# Copyright Contributors to the Pyro project.\n# SPDX-License-Identifier: Apache-2.0\n\nfrom collections import OrderedDict, namedtuple\n\nfrom jax import grad, jacfwd, random, value_and_grad, vmap\nfrom jax.flatten_util import ravel_pytree\nimport jax.numpy as jnp\nfrom jax.ops import index_updat...
diff --git a/numpyro/infer/hmc.py b/numpyro/infer/hmc.py index 4f5ae2f65..a771d5059 100644 --- a/numpyro/infer/hmc.py +++ b/numpyro/infer/hmc.py @@ -247,7 +247,9 @@ def init_kernel( :param float trajectory_length: Length of a MCMC trajectory for HMC. Default value is :math:`2\\pi`. :param int max_tree_depth: Max depth of the binary tree created during the doubling - scheme of NUTS sampler. Defaults to 10. + scheme of NUTS sampler. Defaults to 10. This argument also accepts a tuple of + integers `(d1, d2)`, where `d1` is the max tree depth during warmup phase and + `d2` is the max tree depth during post warmup phase. :param bool find_heuristic_step_size: whether to a heuristic function to adjust the step size at the beginning of each adaptation window. Defaults to False. :param tuple model_args: Model arguments if `potential_fn_gen` is specified. @@ -263,7 +265,11 @@ def init_kernel( nonlocal wa_update, max_treedepth, vv_update, wa_steps, forward_mode_ad forward_mode_ad = forward_mode_differentiation wa_steps = num_warmup - max_treedepth = max_tree_depth + max_treedepth = ( + max_tree_depth + if isinstance(max_tree_depth, tuple) + else (max_tree_depth, max_tree_depth) + ) if isinstance(init_params, ParamInfo): z, pe, z_grad = init_params else: @@ -376,7 +382,7 @@ def _nuts_next( model_args, model_kwargs, rng_key, - trajectory_length, + max_treedepth_current, ): if potential_fn_gen: nonlocal vv_update, forward_mode_ad @@ -391,7 +397,7 @@ def _nuts_next( step_size, rng_key, max_delta_energy=max_delta_energy, - max_tree_depth=max_treedepth, + max_tree_depth=(max_treedepth_current, max(max_treedepth)), ) accept_prob = binary_tree.sum_accept_probs / binary_tree.num_proposals num_steps = binary_tree.num_proposals @@ -437,6 +443,12 @@ def sample_kernel(hmc_state, model_args=(), model_kwargs=None): vv_state = IntegratorState( hmc_state.z, r, hmc_state.potential_energy, hmc_state.z_grad ) + if algo == "HMC": + hmc_length_args = (hmc_state.trajectory_length,) + else: + hmc_length_args = ( + jnp.where(hmc_state.i < wa_steps, max_treedepth[0], max_treedepth[1]), + ) vv_state, energy, num_steps, accept_prob, diverging = _next( hmc_state.adapt_state.step_size, hmc_state.adapt_state.inverse_mass_matrix, @@ -444,7 +456,7 @@ def sample_kernel(hmc_state, model_args=(), model_kwargs=None): model_args, model_kwargs, rng_key_transition, - hmc_state.trajectory_length, + *hmc_length_args, ) # not update adapt_state after warmup phase adapt_state = cond( @@ -800,7 +812,9 @@ class NUTS(HMC): :param float trajectory_length: Length of a MCMC trajectory for HMC. This arg has no effect in NUTS sampler. :param int max_tree_depth: Max depth of the binary tree created during the doubling - scheme of NUTS sampler. Defaults to 10. + scheme of NUTS sampler. Defaults to 10. This argument also accepts a tuple of + integers `(d1, d2)`, where `d1` is the max tree depth during warmup phase and + `d2` is the max tree depth during post warmup phase. :param callable init_strategy: a per-site initialization function. See :ref:`init_strategy` section for available functions. :param bool find_heuristic_step_size: whether to a heuristic function to adjust the diff --git a/numpyro/infer/hmc_util.py b/numpyro/infer/hmc_util.py index 86f9f9764..c2ddaaa4b 100644 --- a/numpyro/infer/hmc_util.py +++ b/numpyro/infer/hmc_util.py @@ -1116,9 +1116,17 @@ def build_tree( randomness. :param float max_delta_energy: A threshold to decide if the new state diverges (based on the energy difference) too much from the initial integrator state. + :param int max_tree_depth: Max depth of the binary tree created during the doubling + scheme of NUTS sampler. Defaults to 10. This argument also accepts a tuple of + integers `(d1, d2)`, where `d1` is the max tree depth at the current MCMC + step and `d2` is the global max tree depth for all MCMC steps. :return: information of the tree. :rtype: :data:`TreeInfo` """ + if isinstance(max_tree_depth, tuple): + max_tree_depth_current, max_tree_depth = max_tree_depth + else: + max_tree_depth_current = max_tree_depth z, r, potential_energy, z_grad = verlet_state energy_current = potential_energy + kinetic_fn(inverse_mass_matrix, r) latent_size = jnp.size(ravel_pytree(r)[0]) @@ -1147,7 +1155,7 @@ def build_tree( def _cond_fn(state): tree, _ = state - return (tree.depth < max_tree_depth) & ~tree.turning & ~tree.diverging + return (tree.depth < max_tree_depth_current) & ~tree.turning & ~tree.diverging def _body_fn(state): tree, key = state diff --git a/test/infer/test_mcmc.py b/test/infer/test_mcmc.py index f7f59ce23..2abdabf90 100644 --- a/test/infer/test_mcmc.py +++ b/test/infer/test_mcmc.py @@ -156,7 +156,8 @@ def model(data): assert_allclose(jnp.mean(samples["loc"], 0), true_coef, atol=0.05) -def test_improper_normal(): +@pytest.mark.parametrize("max_tree_depth", [10, (5, 10)]) +def test_improper_normal(max_tree_depth): true_coef = 0.9 def model(data): @@ -171,7 +172,7 @@ def model(data): numpyro.sample("obs", dist.Normal(loc, 0.1), obs=data) data = true_coef + random.normal(random.PRNGKey(0), (1000,)) - kernel = NUTS(model=model) + kernel = NUTS(model=model, max_tree_depth=max_tree_depth) mcmc = MCMC(kernel, num_warmup=1000, num_samples=1000) mcmc.run(random.PRNGKey(0), data) samples = mcmc.get_samples()
pyro-ppl__numpyro-1547
The initial value of the run function is invalid. In the MCMC class, the folllowing initialization is succeed. It correctly starts from the initial value. ``` kernel = numpyro.infer.NUTS( model, max_tree_depth=max_tree_depth, init_strategy=init_to_value(values=init_params), target_accept_prob=target_accept_prob, ) ``` However, the initialization in the run function below does not reflect the initial value. (Each value of init_params are arrays of chain numbers.) ``` mcmc.run( jax.random.PRNGKey(1), y=obs, init_params=init_params, ) ```
[ { "content": "# Copyright Contributors to the Pyro project.\n# SPDX-License-Identifier: Apache-2.0\n\nfrom collections import OrderedDict, namedtuple\nfrom functools import partial\nimport math\nimport os\n\nfrom jax import device_put, lax, random, vmap\nfrom jax.flatten_util import ravel_pytree\nimport jax.num...
[ { "content": "# Copyright Contributors to the Pyro project.\n# SPDX-License-Identifier: Apache-2.0\n\nfrom collections import OrderedDict, namedtuple\nfrom functools import partial\nimport math\nimport os\n\nfrom jax import device_put, lax, random, vmap\nfrom jax.flatten_util import ravel_pytree\nimport jax.num...
diff --git a/numpyro/infer/hmc.py b/numpyro/infer/hmc.py index 2b5cf3350..aa1aae392 100644 --- a/numpyro/infer/hmc.py +++ b/numpyro/infer/hmc.py @@ -649,7 +649,12 @@ def __init__( def _init_state(self, rng_key, model_args, model_kwargs, init_params): if self._model is not None: - init_params, potential_fn, postprocess_fn, model_trace = initialize_model( + ( + new_init_params, + potential_fn, + postprocess_fn, + model_trace, + ) = initialize_model( rng_key, self._model, dynamic_args=True, @@ -658,6 +663,8 @@ def _init_state(self, rng_key, model_args, model_kwargs, init_params): model_kwargs=model_kwargs, forward_mode_differentiation=self._forward_mode_differentiation, ) + if init_params is None: + init_params = new_init_params if self._init_fn is None: self._init_fn, self._sample_fn = hmc( potential_fn_gen=potential_fn, diff --git a/numpyro/infer/mcmc.py b/numpyro/infer/mcmc.py index e9c8805c3..80020b1a0 100644 --- a/numpyro/infer/mcmc.py +++ b/numpyro/infer/mcmc.py @@ -515,7 +515,9 @@ def warmup( :param bool collect_warmup: Whether to collect samples from the warmup phase. Defaults to `False`. :param init_params: Initial parameters to begin sampling. The type must be consistent - with the input type to `potential_fn`. + with the input type to `potential_fn` provided to the kernel. If the kernel is + instantiated by a numpyro model, the initial parameters here correspond to latent + values in unconstrained space. :param kwargs: Keyword arguments to be provided to the :meth:`numpyro.infer.mcmc.MCMCKernel.init` method. These are typically the keyword arguments needed by the `model`. """ @@ -546,7 +548,9 @@ def run(self, rng_key, *args, extra_fields=(), init_params=None, **kwargs): `"adapt_state.step_size"` can be used to collect step sizes at each step. :type extra_fields: tuple or list of str :param init_params: Initial parameters to begin sampling. The type must be consistent - with the input type to `potential_fn`. + with the input type to `potential_fn` provided to the kernel. If the kernel is + instantiated by a numpyro model, the initial parameters here correspond to latent + values in unconstrained space. :param kwargs: Keyword arguments to be provided to the :meth:`numpyro.infer.mcmc.MCMCKernel.init` method. These are typically the keyword arguments needed by the `model`.
pyro-ppl__numpyro-733
Add a better error message for how to debug "Cannot find valid initial parameters" issue Recently, several users got this issue but it is not easy to diagnose the issue just by looking at the `model`. We should add a better error message, e.g. to mention about `numpyro.validation_enabled()` utility, which tells us at which latent site, we get invalid parameters/values.
[ { "content": "# Copyright Contributors to the Pyro project.\n# SPDX-License-Identifier: Apache-2.0\n\n# The implementation follows the design in PyTorch: torch.distributions.distribution.py\n#\n# Copyright (c) 2016- Facebook, Inc (Adam Paszke)\n# Copyright (c) 2014- Facebook, Inc (...
[ { "content": "# Copyright Contributors to the Pyro project.\n# SPDX-License-Identifier: Apache-2.0\n\n# The implementation follows the design in PyTorch: torch.distributions.distribution.py\n#\n# Copyright (c) 2016- Facebook, Inc (Adam Paszke)\n# Copyright (c) 2014- Facebook, Inc (...
diff --git a/numpyro/distributions/distribution.py b/numpyro/distributions/distribution.py index c245790c2..82a6c2b41 100644 --- a/numpyro/distributions/distribution.py +++ b/numpyro/distributions/distribution.py @@ -141,7 +141,8 @@ def __init__(self, batch_shape=(), event_shape=(), validate_args=None): is_valid = jnp.all(constraint(getattr(self, param))) if not_jax_tracer(is_valid): if not is_valid: - raise ValueError("The parameter {} has invalid values".format(param)) + raise ValueError("{} distribution got invalid {} parameter.".format( + self.__class__.__name__, param)) super(Distribution, self).__init__() @property diff --git a/numpyro/infer/util.py b/numpyro/infer/util.py index 199b0a110..023377555 100644 --- a/numpyro/infer/util.py +++ b/numpyro/infer/util.py @@ -427,6 +427,21 @@ def initialize_model(rng_key, model, if not_jax_tracer(is_valid): if device_get(~jnp.all(is_valid)): + with numpyro.validation_enabled(), trace() as tr: + # validate parameters + substituted_model(*model_args, **model_kwargs) + # validate values + for site in tr.values(): + if site['type'] == 'sample': + with warnings.catch_warnings(record=True) as ws: + site['fn']._validate_sample(site['value']) + if len(ws) > 0: + for w in ws: + # at site information to the warning message + w.message.args = ("Site {}: {}".format(site["name"], w.message.args[0]),) \ + + w.message.args[1:] + warnings.showwarning(w.message, w.category, w.filename, w.lineno, + file=w.file, line=w.line) raise RuntimeError("Cannot find valid initial parameters. Please check your model again.") return ModelInfo(ParamInfo(init_params, pe, grad), potential_fn, postprocess_fn, model_trace)