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 obtain a copy of the License at\n\n# http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport json\nimport math\nfrom collections import defaultdict\nfrom typing import Union, DefaultDict, Dict, List, Optional\n\nimport torch\nfrom pydantic import BaseModel\nfrom outlines.fsm.fsm import RegexFSM\nfrom outlines.fsm.json_schema import build_regex_from_schema\n\n\nclass RegexLogitsProcessor:\n\n def __init__(self, regex_string: str, tokenizer):\n \"\"\"Compile the FSM that drives the regex-structured generation.\n\n Parameters\n ----------\n regex_string\n A string that represents a regular expression\n tokenizer\n The model's tokenizer\n\n \"\"\"\n tokenizer = self.adapt_tokenizer(tokenizer)\n fsm = RegexFSM(regex_string, tokenizer)\n self.fsm = fsm\n\n def init_state(self):\n \"\"\"Initialize the FSM states.\"\"\"\n self.fsm_state: DefaultDict[int, int] = defaultdict(int)\n\n def __call__(self, input_ids: List[int],\n scores: torch.Tensor) -> torch.Tensor:\n \"\"\"Use the FSM to bias the logits before sampling the next token.\"\"\"\n\n seq_id = hash(tuple(input_ids))\n\n if len(input_ids) == 0:\n self.init_state()\n else:\n last_token = input_ids[-1]\n last_seq_id = hash(tuple(input_ids[:-1]))\n self.fsm_state[seq_id] = self.fsm.next_state(\n self.fsm_state[last_seq_id], last_token)\n\n allowed_tokens = self.fsm.allowed_token_ids(self.fsm_state[seq_id])\n\n mask = torch.full((scores.shape[-1], ),\n -math.inf,\n device=scores.device)\n mask[allowed_tokens] = 0\n scores.add_(mask)\n\n return scores\n\n def adapt_tokenizer(self, tokenizer):\n \"\"\"Adapt vLLM's tokenizer to use to compile the FSM.\n\n The API of Outlines tokenizers is slightly different to that of\n `transformers`. In addition we need to handle the missing spaces to\n Llama's tokenizer to be able to compile FSMs for this model.\n\n \"\"\"\n tokenizer.vocabulary = tokenizer.get_vocab()\n tokenizer.special_tokens = set(tokenizer.all_special_tokens)\n\n def convert_token_to_string(token: str) -> str:\n from transformers.file_utils import SPIECE_UNDERLINE\n\n string = tokenizer.convert_tokens_to_string([token])\n\n # A hack to handle missing spaces to HF's Llama tokenizers\n if token.startswith(SPIECE_UNDERLINE) or token == \"<0x20>\":\n return \" \" + string\n\n return string\n\n tokenizer.convert_token_to_string = convert_token_to_string\n\n return tokenizer\n\n\nclass JSONLogitsProcessor(RegexLogitsProcessor):\n\n def __init__(self,\n schema: Union[str, Dict, BaseModel],\n tokenizer,\n whitespace_pattern: Optional[str] = None):\n \"\"\"Compile the FSM that drives the JSON-guided generation.\n\n Parameters\n ----------\n schema\n A JSON schema that encodes the structure we want the model to\n generate\n tokenizer\n The model's tokenizer\n whitespace_pattern\n Pattern to use for JSON syntactic whitespace (doesn't impact\n string literals)\n Example: allow only a single space or newline with\n `whitespace_pattern=r\"[\\n ]?\"`\n \"\"\"\n if isinstance(schema, type(BaseModel)):\n schema_str = json.dumps(schema.model_json_schema())\n elif isinstance(schema, Dict):\n schema_str = json.dumps(schema)\n elif isinstance(schema, str):\n schema_str = schema\n else:\n raise ValueError(\n f\"Cannot parse schema {schema}. The schema must be either \"\n f\"a Pydantic object, a dictionary or a string that contains \"\n f\"the JSON Schema specification\")\n regex_string = build_regex_from_schema(schema_str, whitespace_pattern)\n super().__init__(regex_string, tokenizer)\n", "path": "vllm/model_executor/guided_logits_processors.py" }, { "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 Union, Tuple\nfrom pydantic import BaseModel\n\nfrom vllm.entrypoints.openai.protocol import (CompletionRequest,\n ChatCompletionRequest)\nfrom vllm.model_executor.guided_logits_processors import (JSONLogitsProcessor,\n RegexLogitsProcessor)\n\n\nclass GuidedDecodingMode(Enum):\n JSON = \"json\"\n REGEX = \"regex\"\n CHOICE = \"choice\"\n\n\nglobal_thread_pool = None # used for generating logits processor fsm\n\n\nasync def get_guided_decoding_logits_processor(\n request: Union[CompletionRequest, ChatCompletionRequest],\n tokenizer) -> Union[JSONLogitsProcessor, RegexLogitsProcessor]:\n \"\"\"\n Given an OpenAI-compatible request, check for guided decoding parameters\n and get the necessary logits processor for the given guide.\n We cache logit processors by (guide, tokenizer), and on cache hit\n we make a shallow copy to reuse the same underlying FSM.\n \"\"\"\n global global_thread_pool\n guide, mode = _get_guide_and_mode(request)\n if not guide:\n return None\n\n if global_thread_pool is None:\n global_thread_pool = concurrent.futures.ThreadPoolExecutor(\n max_workers=2)\n loop = asyncio.get_running_loop()\n\n result = await loop.run_in_executor(global_thread_pool,\n _get_cached_logits_processor, guide,\n tokenizer, mode)\n\n logits_processor = copy(result)\n # reset logits processor's internal state\n logits_processor.init_state()\n return logits_processor\n\n\ndef _get_guide_and_mode(\n request: Union[CompletionRequest, ChatCompletionRequest]\n) -> Tuple[str, GuidedDecodingMode]:\n\n if request.guided_json:\n if not isinstance(request.guided_json, (str, dict, BaseModel)):\n raise TypeError(\"JSON schema must be str, dict, or BaseModel\")\n\n json = request.guided_json\n if isinstance(json, dict):\n # turn dict into hashable string\n json = json_dumps(json, sort_keys=True)\n elif isinstance(json, BaseModel):\n # use pydantic signature so that different model classes\n # with the same fields will get hashed the same\n json = str(json.__signature__)\n return json, GuidedDecodingMode.JSON\n\n elif request.guided_regex:\n if not isinstance(request.guided_regex, str):\n raise TypeError(\"Regex must be string\")\n return request.guided_regex, GuidedDecodingMode.REGEX\n\n elif request.guided_choice:\n if not isinstance(request.guided_choice, list):\n raise TypeError(\"Choices must be a list\")\n\n # choice just uses regex\n choices = [\n regex_escape(str(choice)) for choice in request.guided_choice\n ]\n choices_regex = \"(\" + \"|\".join(choices) + \")\"\n return choices_regex, GuidedDecodingMode.CHOICE\n\n else:\n return None, None\n\n\n@lru_cache(maxsize=32)\ndef _get_cached_logits_processor(guide: str, tokenizer,\n mode: GuidedDecodingMode):\n if mode == GuidedDecodingMode.JSON:\n return JSONLogitsProcessor(guide, tokenizer)\n elif mode == GuidedDecodingMode.REGEX or mode == GuidedDecodingMode.CHOICE:\n return RegexLogitsProcessor(guide, tokenizer)\n else:\n raise ValueError(f\"Unknown guided decoding mode {mode}\")\n", "path": "vllm/model_executor/guided_decoding.py" }, { "content": "# Adapted from\n# https://github.com/lm-sys/FastChat/blob/168ccc29d3f7edc50823016105c024fe2282732a/fastchat/protocol/openai_api_protocol.py\nimport time\nfrom typing import Dict, List, Literal, Optional, Union\n\nfrom pydantic import BaseModel, Field, model_validator\n\nfrom vllm.utils import random_uuid\nfrom vllm.sampling_params import SamplingParams\n\nimport torch\n\n\nclass ErrorResponse(BaseModel):\n object: str = \"error\"\n message: str\n type: str\n param: Optional[str] = None\n code: int\n\n\nclass ModelPermission(BaseModel):\n id: str = Field(default_factory=lambda: f\"modelperm-{random_uuid()}\")\n object: str = \"model_permission\"\n created: int = Field(default_factory=lambda: int(time.time()))\n allow_create_engine: bool = False\n allow_sampling: bool = True\n allow_logprobs: bool = True\n allow_search_indices: bool = False\n allow_view: bool = True\n allow_fine_tuning: bool = False\n organization: str = \"*\"\n group: Optional[str] = None\n is_blocking: str = False\n\n\nclass ModelCard(BaseModel):\n id: str\n object: str = \"model\"\n created: int = Field(default_factory=lambda: int(time.time()))\n owned_by: str = \"vllm\"\n root: Optional[str] = None\n parent: Optional[str] = None\n permission: List[ModelPermission] = Field(default_factory=list)\n\n\nclass ModelList(BaseModel):\n object: str = \"list\"\n data: List[ModelCard] = Field(default_factory=list)\n\n\nclass UsageInfo(BaseModel):\n prompt_tokens: int = 0\n total_tokens: int = 0\n completion_tokens: Optional[int] = 0\n\n\nclass ChatCompletionRequest(BaseModel):\n model: str\n messages: List[Dict[str, str]]\n temperature: Optional[float] = 0.7\n top_p: Optional[float] = 1.0\n n: Optional[int] = 1\n max_tokens: Optional[int] = None\n seed: Optional[int] = None\n stop: Optional[Union[str, List[str]]] = Field(default_factory=list)\n stream: Optional[bool] = False\n logprobs: Optional[bool] = False\n top_logprobs: Optional[int] = None\n presence_penalty: Optional[float] = 0.0\n frequency_penalty: Optional[float] = 0.0\n logit_bias: Optional[Dict[str, float]] = None\n user: Optional[str] = None\n # Additional parameters supported by vLLM\n best_of: Optional[int] = None\n top_k: Optional[int] = -1\n ignore_eos: Optional[bool] = False\n use_beam_search: Optional[bool] = False\n early_stopping: Optional[bool] = False\n stop_token_ids: Optional[List[int]] = Field(default_factory=list)\n skip_special_tokens: Optional[bool] = True\n spaces_between_special_tokens: Optional[bool] = True\n add_generation_prompt: Optional[bool] = True\n echo: Optional[bool] = False\n repetition_penalty: Optional[float] = 1.0\n min_p: Optional[float] = 0.0\n include_stop_str_in_output: Optional[bool] = False\n length_penalty: Optional[float] = 1.0\n guided_json: Optional[Union[str, dict, BaseModel]] = None\n guided_regex: Optional[str] = None\n guided_choice: Optional[List[str]] = None\n\n def to_sampling_params(self) -> SamplingParams:\n if self.logprobs and not self.top_logprobs:\n raise ValueError(\"Top logprobs must be set when logprobs is.\")\n\n logits_processors = None\n if self.logit_bias:\n\n def logit_bias_logits_processor(\n token_ids: List[int],\n logits: torch.Tensor) -> torch.Tensor:\n for token_id, bias in self.logit_bias.items():\n # Clamp the bias between -100 and 100 per OpenAI API spec\n bias = min(100, max(-100, bias))\n logits[int(token_id)] += bias\n return logits\n\n logits_processors = [logit_bias_logits_processor]\n\n return SamplingParams(\n n=self.n,\n presence_penalty=self.presence_penalty,\n frequency_penalty=self.frequency_penalty,\n repetition_penalty=self.repetition_penalty,\n temperature=self.temperature,\n top_p=self.top_p,\n min_p=self.min_p,\n seed=self.seed,\n stop=self.stop,\n stop_token_ids=self.stop_token_ids,\n max_tokens=self.max_tokens,\n logprobs=self.top_logprobs if self.logprobs else None,\n prompt_logprobs=self.top_logprobs if self.echo else None,\n best_of=self.best_of,\n top_k=self.top_k,\n ignore_eos=self.ignore_eos,\n use_beam_search=self.use_beam_search,\n early_stopping=self.early_stopping,\n skip_special_tokens=self.skip_special_tokens,\n spaces_between_special_tokens=self.spaces_between_special_tokens,\n include_stop_str_in_output=self.include_stop_str_in_output,\n length_penalty=self.length_penalty,\n logits_processors=logits_processors,\n )\n\n @model_validator(mode=\"before\")\n @classmethod\n def check_guided_decoding_count(cls, data):\n guide_count = sum([\n \"guided_json\" in data and data[\"guided_json\"] is not None,\n \"guided_regex\" in data and data[\"guided_regex\"] is not None,\n \"guided_choice\" in data and data[\"guided_choice\"] is not None\n ])\n if guide_count > 1:\n raise ValueError(\n \"You can only use one kind of guided decoding \"\n \"('guided_json', 'guided_regex' or 'guided_choice').\")\n return data\n\n\nclass CompletionRequest(BaseModel):\n model: str\n # a string, array of strings, array of tokens, or array of token arrays\n prompt: Union[List[int], List[List[int]], str, List[str]]\n suffix: Optional[str] = None\n max_tokens: Optional[int] = 16\n temperature: Optional[float] = 1.0\n top_p: Optional[float] = 1.0\n n: Optional[int] = 1\n stream: Optional[bool] = False\n logprobs: Optional[int] = None\n echo: Optional[bool] = False\n stop: Optional[Union[str, List[str]]] = Field(default_factory=list)\n seed: Optional[int] = None\n presence_penalty: Optional[float] = 0.0\n frequency_penalty: Optional[float] = 0.0\n best_of: Optional[int] = None\n logit_bias: Optional[Dict[str, float]] = None\n user: Optional[str] = None\n # Additional parameters supported by vLLM\n top_k: Optional[int] = -1\n ignore_eos: Optional[bool] = False\n use_beam_search: Optional[bool] = False\n early_stopping: Optional[bool] = False\n stop_token_ids: Optional[List[int]] = Field(default_factory=list)\n skip_special_tokens: Optional[bool] = True\n spaces_between_special_tokens: Optional[bool] = True\n repetition_penalty: Optional[float] = 1.0\n min_p: Optional[float] = 0.0\n include_stop_str_in_output: Optional[bool] = False\n length_penalty: Optional[float] = 1.0\n guided_json: Optional[Union[str, dict, BaseModel]] = None\n guided_regex: Optional[str] = None\n guided_choice: Optional[List[str]] = None\n\n def to_sampling_params(self):\n echo_without_generation = self.echo and self.max_tokens == 0\n\n logits_processors = None\n if self.logit_bias:\n\n def logit_bias_logits_processor(\n token_ids: List[int],\n logits: torch.Tensor) -> torch.Tensor:\n for token_id, bias in self.logit_bias.items():\n # Clamp the bias between -100 and 100 per OpenAI API spec\n bias = min(100, max(-100, bias))\n logits[int(token_id)] += bias\n return logits\n\n logits_processors = [logit_bias_logits_processor]\n\n return SamplingParams(\n n=self.n,\n best_of=self.best_of,\n presence_penalty=self.presence_penalty,\n frequency_penalty=self.frequency_penalty,\n repetition_penalty=self.repetition_penalty,\n temperature=self.temperature,\n top_p=self.top_p,\n top_k=self.top_k,\n min_p=self.min_p,\n seed=self.seed,\n stop=self.stop,\n stop_token_ids=self.stop_token_ids,\n ignore_eos=self.ignore_eos,\n max_tokens=self.max_tokens if not echo_without_generation else 1,\n logprobs=self.logprobs,\n use_beam_search=self.use_beam_search,\n early_stopping=self.early_stopping,\n prompt_logprobs=self.logprobs if self.echo else None,\n skip_special_tokens=self.skip_special_tokens,\n spaces_between_special_tokens=(self.spaces_between_special_tokens),\n include_stop_str_in_output=self.include_stop_str_in_output,\n length_penalty=self.length_penalty,\n logits_processors=logits_processors,\n )\n\n @model_validator(mode=\"before\")\n @classmethod\n def check_guided_decoding_count(cls, data):\n guide_count = sum([\n \"guided_json\" in data and data[\"guided_json\"] is not None,\n \"guided_regex\" in data and data[\"guided_regex\"] is not None,\n \"guided_choice\" in data and data[\"guided_choice\"] is not None\n ])\n if guide_count > 1:\n raise ValueError(\n \"You can only use one kind of guided decoding \"\n \"('guided_json', 'guided_regex' or 'guided_choice').\")\n return data\n\n\nclass LogProbs(BaseModel):\n text_offset: List[int] = Field(default_factory=list)\n token_logprobs: List[Optional[float]] = Field(default_factory=list)\n tokens: List[str] = Field(default_factory=list)\n top_logprobs: Optional[List[Optional[Dict[int, float]]]] = None\n\n\nclass CompletionResponseChoice(BaseModel):\n index: int\n text: str\n logprobs: Optional[LogProbs] = None\n finish_reason: Optional[Literal[\"stop\", \"length\"]] = None\n\n\nclass CompletionResponse(BaseModel):\n id: str = Field(default_factory=lambda: f\"cmpl-{random_uuid()}\")\n object: str = \"text_completion\"\n created: int = Field(default_factory=lambda: int(time.time()))\n model: str\n choices: List[CompletionResponseChoice]\n usage: UsageInfo\n\n\nclass CompletionResponseStreamChoice(BaseModel):\n index: int\n text: str\n logprobs: Optional[LogProbs] = None\n finish_reason: Optional[Literal[\"stop\", \"length\"]] = None\n\n\nclass CompletionStreamResponse(BaseModel):\n id: str = Field(default_factory=lambda: f\"cmpl-{random_uuid()}\")\n object: str = \"text_completion\"\n created: int = Field(default_factory=lambda: int(time.time()))\n model: str\n choices: List[CompletionResponseStreamChoice]\n usage: Optional[UsageInfo] = Field(default=None)\n\n\nclass ChatMessage(BaseModel):\n role: str\n content: str\n\n\nclass ChatCompletionResponseChoice(BaseModel):\n index: int\n message: ChatMessage\n logprobs: Optional[LogProbs] = None\n finish_reason: Optional[Literal[\"stop\", \"length\"]] = None\n\n\nclass ChatCompletionResponse(BaseModel):\n id: str = Field(default_factory=lambda: f\"chatcmpl-{random_uuid()}\")\n object: str = \"chat.completion\"\n created: int = Field(default_factory=lambda: int(time.time()))\n model: str\n choices: List[ChatCompletionResponseChoice]\n usage: UsageInfo\n\n\nclass DeltaMessage(BaseModel):\n role: Optional[str] = None\n content: Optional[str] = None\n\n\nclass ChatCompletionResponseStreamChoice(BaseModel):\n index: int\n delta: DeltaMessage\n logprobs: Optional[LogProbs] = None\n finish_reason: Optional[Literal[\"stop\", \"length\"]] = None\n\n\nclass ChatCompletionStreamResponse(BaseModel):\n id: str = Field(default_factory=lambda: f\"chatcmpl-{random_uuid()}\")\n object: str = \"chat.completion.chunk\"\n created: int = Field(default_factory=lambda: int(time.time()))\n model: str\n choices: List[ChatCompletionResponseStreamChoice]\n usage: Optional[UsageInfo] = Field(default=None)\n", "path": "vllm/entrypoints/openai/protocol.py" } ]
[ { "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 obtain a copy of the License at\n\n# http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport json\nimport math\nfrom collections import defaultdict\nfrom typing import Union, DefaultDict, Dict, List, Optional, Callable\n\nimport torch\nfrom pydantic import BaseModel\nfrom transformers import PreTrainedTokenizerBase\nfrom outlines.fsm.fsm import RegexFSM, CFGFSM\nfrom outlines.fsm.json_schema import build_regex_from_schema\n\n\nclass BaseLogitsProcessor:\n\n def adapt_tokenizer(self, tokenizer: PreTrainedTokenizerBase):\n \"\"\"Adapt vLLM's tokenizer to use to compile the FSM.\n\n The API of Outlines tokenizers is slightly different to that of\n `transformers`. The decoder of outlines, returns a list whereas\n the decode of vLLM returns an str. To sync the vLLM decoder with\n outlines internal api, the decoder should be adapted. In addition\n we need to handle the missing spaces to Llama's tokenizer to be\n able to compile FSMs for this model.\n\n \"\"\"\n if getattr(tokenizer, \"_outlines_adapted\", False):\n return tokenizer\n\n tokenizer.vocabulary = tokenizer.get_vocab()\n tokenizer.special_tokens = set(tokenizer.all_special_tokens)\n\n def convert_token_to_string(token: str) -> str:\n from transformers.file_utils import SPIECE_UNDERLINE\n\n string = tokenizer.convert_tokens_to_string([token])\n\n # A hack to handle missing spaces to HF's Llama tokenizers\n if token.startswith(SPIECE_UNDERLINE) or token == \"<0x20>\":\n return \" \" + string\n\n return string\n\n def change_decoder(\n decoder: Callable[[List[int]], str]\n ) -> Callable[[List[int]], List[str]]:\n \"\"\"Sync vLLM's decoder with the outlines by returning list.\"\"\"\n\n def new_decoder(inp_tokens: List[int]) -> List[str]:\n return [decoder(inp_tokens)]\n\n return new_decoder\n\n tokenizer.convert_token_to_string = convert_token_to_string\n tokenizer.decode = change_decoder(tokenizer.decode)\n setattr(tokenizer, \"_outlines_adapted\", True) # noqa: B010\n\n return tokenizer\n\n def init_state(self):\n \"\"\"Initialize the FSM states.\"\"\"\n self.fsm_state: DefaultDict[int, int] = defaultdict(int)\n\n def __call__(self, input_ids: List[int],\n scores: torch.Tensor) -> torch.Tensor:\n \"\"\"Use the FSM to bias the logits before sampling the next token.\"\"\"\n\n seq_id = hash(tuple(input_ids))\n\n if len(input_ids) == 0:\n self.init_state()\n else:\n last_token = input_ids[-1]\n last_seq_id = hash(tuple(input_ids[:-1]))\n self.fsm_state[seq_id] = self.fsm.next_state(\n self.fsm_state[last_seq_id], last_token)\n\n allowed_tokens = self.fsm.allowed_token_ids(self.fsm_state[seq_id])\n\n mask = torch.full((scores.shape[-1], ),\n -math.inf,\n device=scores.device)\n mask[allowed_tokens] = 0\n scores.add_(mask)\n\n return scores\n\n\nclass RegexLogitsProcessor(BaseLogitsProcessor):\n\n def __init__(self, regex_string: str, tokenizer: PreTrainedTokenizerBase):\n \"\"\"Compile the FSM that drives the regex-structured generation.\n\n Parameters\n ----------\n regex_string\n A string that represents a regular expression\n tokenizer\n The model's tokenizer\n\n \"\"\"\n tokenizer = self.adapt_tokenizer(tokenizer)\n fsm = RegexFSM(regex_string, tokenizer)\n self.fsm = fsm\n\n\nclass JSONLogitsProcessor(RegexLogitsProcessor):\n\n def __init__(self,\n schema: Union[str, Dict, BaseModel],\n tokenizer: PreTrainedTokenizerBase,\n whitespace_pattern: Optional[str] = None):\n \"\"\"Compile the FSM that drives the JSON-guided generation.\n\n Parameters\n ----------\n schema\n A JSON schema that encodes the structure we want the model to\n generate\n tokenizer\n The model's tokenizer\n whitespace_pattern\n Pattern to use for JSON syntactic whitespace (doesn't impact\n string literals)\n Example: allow only a single space or newline with\n `whitespace_pattern=r\"[\\n ]?\"`\n \"\"\"\n if isinstance(schema, type(BaseModel)):\n schema_str = json.dumps(schema.model_json_schema())\n elif isinstance(schema, Dict):\n schema_str = json.dumps(schema)\n elif isinstance(schema, str):\n schema_str = schema\n else:\n raise ValueError(\n f\"Cannot parse schema {schema}. The schema must be either \"\n f\"a Pydantic object, a dictionary or a string that contains \"\n f\"the JSON Schema specification\")\n regex_string = build_regex_from_schema(schema_str, whitespace_pattern)\n super().__init__(regex_string, tokenizer)\n\n\nclass CFGLogitsProcessor(BaseLogitsProcessor):\n\n def __init__(self, cfg: str, tokenizer: PreTrainedTokenizerBase):\n \"\"\"Compile the FSM that drives the context free grammar generation.\n\n Parameters\n ----------\n cfg\n A string that represents a context-free grammar\n tokenizer\n The model's tokenizer\n\n \"\"\"\n tokenizer = self.adapt_tokenizer(tokenizer)\n fsm = CFGFSM(cfg, tokenizer)\n self.fsm = fsm\n", "path": "vllm/model_executor/guided_logits_processors.py" }, { "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 Union, Tuple\n\nfrom pydantic import BaseModel\nfrom transformers import PreTrainedTokenizerBase\n\nfrom vllm.entrypoints.openai.protocol import (CompletionRequest,\n ChatCompletionRequest)\nfrom vllm.model_executor.guided_logits_processors import (JSONLogitsProcessor,\n RegexLogitsProcessor,\n CFGLogitsProcessor)\n\n\nclass GuidedDecodingMode(Enum):\n JSON = \"json\"\n REGEX = \"regex\"\n CHOICE = \"choice\"\n GRAMMAR = \"grammar\"\n\n\n# https://github.com/outlines-dev/outlines/blob/main/outlines/grammars/json.lark\n# the main difference is that we changed the start: value to\n# start: object | array, so we are denying scalar values as the root of the\n# JSON. Starting with scalars as the root seems to cause llama to generate\n# without stop.\nJSON_GRAMMAR = r\"\"\"\n?start: object | array\n\n?value: object\n| array\n| UNESCAPED_STRING\n| SIGNED_NUMBER -> number\n| \"true\" -> true\n| \"false\" -> false\n| \"null\" -> null\n\narray : \"[\" [value (\",\" value)*] \"]\"\nobject : \"{\" [pair (\",\" pair)*] \"}\"\npair : UNESCAPED_STRING \":\" value\n\n%import common.UNESCAPED_STRING\n%import common.SIGNED_NUMBER\n%import common.WS\n\n%ignore WS\n\"\"\"\n\nglobal_thread_pool = None # used for generating logits processor fsm\n\n\nasync def get_guided_decoding_logits_processor(\n request: Union[CompletionRequest, ChatCompletionRequest],\n tokenizer) -> Union[JSONLogitsProcessor, RegexLogitsProcessor]:\n \"\"\"\n Given an OpenAI-compatible request, check for guided decoding parameters\n and get the necessary logits processor for the given guide.\n We cache logit processors by (guide, tokenizer), and on cache hit\n we make a shallow copy to reuse the same underlying FSM.\n \"\"\"\n global global_thread_pool\n guide, mode = _get_guide_and_mode(request)\n if not guide:\n return None\n\n if global_thread_pool is None:\n global_thread_pool = concurrent.futures.ThreadPoolExecutor(\n max_workers=2)\n loop = asyncio.get_running_loop()\n\n result = await loop.run_in_executor(global_thread_pool,\n _get_cached_logits_processor, guide,\n tokenizer, mode)\n\n logits_processor = copy(result)\n # reset logits processor's internal state\n logits_processor.init_state()\n return logits_processor\n\n\ndef _get_guide_and_mode(\n request: Union[CompletionRequest, ChatCompletionRequest]\n) -> Tuple[str, GuidedDecodingMode]:\n\n if request.guided_json:\n json = request.guided_json\n if isinstance(json, dict):\n # turn dict into hashable string\n json = json_dumps(json, sort_keys=True)\n elif isinstance(json, BaseModel):\n # use pydantic signature so that different model classes\n # with the same fields will get hashed the same\n json = str(json.__signature__)\n return json, GuidedDecodingMode.JSON\n elif request.guided_regex:\n return request.guided_regex, GuidedDecodingMode.REGEX\n elif request.guided_choice:\n # choice just uses regex\n choices = [\n regex_escape(str(choice)) for choice in request.guided_choice\n ]\n choices_regex = \"(\" + \"|\".join(choices) + \")\"\n return choices_regex, GuidedDecodingMode.CHOICE\n elif request.guided_grammar:\n return request.guided_grammar, GuidedDecodingMode.GRAMMAR\n elif (request.response_format is not None\n and request.response_format.type == \"json_object\"):\n return JSON_GRAMMAR, GuidedDecodingMode.GRAMMAR\n else:\n return None, None\n\n\n@lru_cache(maxsize=32)\ndef _get_cached_logits_processor(guide: str,\n tokenizer: PreTrainedTokenizerBase,\n mode: GuidedDecodingMode):\n if mode == GuidedDecodingMode.JSON:\n return JSONLogitsProcessor(guide, tokenizer)\n elif mode == GuidedDecodingMode.REGEX or mode == GuidedDecodingMode.CHOICE:\n return RegexLogitsProcessor(guide, tokenizer)\n elif mode == GuidedDecodingMode.GRAMMAR:\n return CFGLogitsProcessor(guide, tokenizer)\n else:\n raise ValueError(f\"Unknown guided decoding mode {mode}\")\n", "path": "vllm/model_executor/guided_decoding.py" }, { "content": "# Adapted from\n# https://github.com/lm-sys/FastChat/blob/168ccc29d3f7edc50823016105c024fe2282732a/fastchat/protocol/openai_api_protocol.py\nimport time\nfrom typing import Dict, List, Literal, Optional, Union\n\nfrom pydantic import BaseModel, Field, model_validator\n\nfrom vllm.utils import random_uuid\nfrom vllm.sampling_params import SamplingParams\n\nimport torch\n\n\nclass ErrorResponse(BaseModel):\n object: str = \"error\"\n message: str\n type: str\n param: Optional[str] = None\n code: int\n\n\nclass ModelPermission(BaseModel):\n id: str = Field(default_factory=lambda: f\"modelperm-{random_uuid()}\")\n object: str = \"model_permission\"\n created: int = Field(default_factory=lambda: int(time.time()))\n allow_create_engine: bool = False\n allow_sampling: bool = True\n allow_logprobs: bool = True\n allow_search_indices: bool = False\n allow_view: bool = True\n allow_fine_tuning: bool = False\n organization: str = \"*\"\n group: Optional[str] = None\n is_blocking: str = False\n\n\nclass ModelCard(BaseModel):\n id: str\n object: str = \"model\"\n created: int = Field(default_factory=lambda: int(time.time()))\n owned_by: str = \"vllm\"\n root: Optional[str] = None\n parent: Optional[str] = None\n permission: List[ModelPermission] = Field(default_factory=list)\n\n\nclass ModelList(BaseModel):\n object: str = \"list\"\n data: List[ModelCard] = Field(default_factory=list)\n\n\nclass UsageInfo(BaseModel):\n prompt_tokens: int = 0\n total_tokens: int = 0\n completion_tokens: Optional[int] = 0\n\n\nclass ResponseFormat(BaseModel):\n # type must be \"json_object\" or \"text\"\n type: str = Literal[\"text\", \"json_object\"]\n\n\nclass ChatCompletionRequest(BaseModel):\n model: str\n messages: List[Dict[str, str]]\n temperature: Optional[float] = 0.7\n top_p: Optional[float] = 1.0\n n: Optional[int] = 1\n max_tokens: Optional[int] = None\n seed: Optional[int] = None\n stop: Optional[Union[str, List[str]]] = Field(default_factory=list)\n stream: Optional[bool] = False\n logprobs: Optional[bool] = False\n top_logprobs: Optional[int] = None\n presence_penalty: Optional[float] = 0.0\n frequency_penalty: Optional[float] = 0.0\n logit_bias: Optional[Dict[str, float]] = None\n user: Optional[str] = None\n # Additional parameters supported by vLLM\n best_of: Optional[int] = None\n top_k: Optional[int] = -1\n ignore_eos: Optional[bool] = False\n use_beam_search: Optional[bool] = False\n early_stopping: Optional[bool] = False\n stop_token_ids: Optional[List[int]] = Field(default_factory=list)\n skip_special_tokens: Optional[bool] = True\n spaces_between_special_tokens: Optional[bool] = True\n add_generation_prompt: Optional[bool] = True\n echo: Optional[bool] = False\n repetition_penalty: Optional[float] = 1.0\n min_p: Optional[float] = 0.0\n include_stop_str_in_output: Optional[bool] = False\n length_penalty: Optional[float] = 1.0\n guided_json: Optional[Union[str, dict, BaseModel]] = None\n guided_regex: Optional[str] = None\n guided_choice: Optional[List[str]] = None\n guided_grammar: Optional[str] = None\n response_format: Optional[ResponseFormat] = None\n\n def to_sampling_params(self) -> SamplingParams:\n if self.logprobs and not self.top_logprobs:\n raise ValueError(\"Top logprobs must be set when logprobs is.\")\n\n logits_processors = None\n if self.logit_bias:\n\n def logit_bias_logits_processor(\n token_ids: List[int],\n logits: torch.Tensor) -> torch.Tensor:\n for token_id, bias in self.logit_bias.items():\n # Clamp the bias between -100 and 100 per OpenAI API spec\n bias = min(100, max(-100, bias))\n logits[int(token_id)] += bias\n return logits\n\n logits_processors = [logit_bias_logits_processor]\n\n return SamplingParams(\n n=self.n,\n presence_penalty=self.presence_penalty,\n frequency_penalty=self.frequency_penalty,\n repetition_penalty=self.repetition_penalty,\n temperature=self.temperature,\n top_p=self.top_p,\n min_p=self.min_p,\n seed=self.seed,\n stop=self.stop,\n stop_token_ids=self.stop_token_ids,\n max_tokens=self.max_tokens,\n logprobs=self.top_logprobs if self.logprobs else None,\n prompt_logprobs=self.top_logprobs if self.echo else None,\n best_of=self.best_of,\n top_k=self.top_k,\n ignore_eos=self.ignore_eos,\n use_beam_search=self.use_beam_search,\n early_stopping=self.early_stopping,\n skip_special_tokens=self.skip_special_tokens,\n spaces_between_special_tokens=self.spaces_between_special_tokens,\n include_stop_str_in_output=self.include_stop_str_in_output,\n length_penalty=self.length_penalty,\n logits_processors=logits_processors,\n )\n\n @model_validator(mode=\"before\")\n @classmethod\n def check_guided_decoding_count(cls, data):\n guide_count = sum([\n \"guided_json\" in data and data[\"guided_json\"] is not None,\n \"guided_regex\" in data and data[\"guided_regex\"] is not None,\n \"guided_choice\" in data and data[\"guided_choice\"] is not None\n ])\n if guide_count > 1:\n raise ValueError(\n \"You can only use one kind of guided decoding \"\n \"('guided_json', 'guided_regex' or 'guided_choice').\")\n return data\n\n\nclass CompletionRequest(BaseModel):\n model: str\n # a string, array of strings, array of tokens, or array of token arrays\n prompt: Union[List[int], List[List[int]], str, List[str]]\n suffix: Optional[str] = None\n max_tokens: Optional[int] = 16\n temperature: Optional[float] = 1.0\n top_p: Optional[float] = 1.0\n n: Optional[int] = 1\n stream: Optional[bool] = False\n logprobs: Optional[int] = None\n echo: Optional[bool] = False\n stop: Optional[Union[str, List[str]]] = Field(default_factory=list)\n seed: Optional[int] = None\n presence_penalty: Optional[float] = 0.0\n frequency_penalty: Optional[float] = 0.0\n best_of: Optional[int] = None\n logit_bias: Optional[Dict[str, float]] = None\n user: Optional[str] = None\n # Additional parameters supported by vLLM\n top_k: Optional[int] = -1\n ignore_eos: Optional[bool] = False\n use_beam_search: Optional[bool] = False\n early_stopping: Optional[bool] = False\n stop_token_ids: Optional[List[int]] = Field(default_factory=list)\n skip_special_tokens: Optional[bool] = True\n spaces_between_special_tokens: Optional[bool] = True\n repetition_penalty: Optional[float] = 1.0\n min_p: Optional[float] = 0.0\n include_stop_str_in_output: Optional[bool] = False\n length_penalty: Optional[float] = 1.0\n guided_json: Optional[Union[str, dict, BaseModel]] = None\n guided_regex: Optional[str] = None\n guided_choice: Optional[List[str]] = None\n guided_grammar: Optional[str] = None\n response_format: Optional[ResponseFormat] = None\n\n def to_sampling_params(self):\n echo_without_generation = self.echo and self.max_tokens == 0\n\n logits_processors = None\n if self.logit_bias:\n\n def logit_bias_logits_processor(\n token_ids: List[int],\n logits: torch.Tensor) -> torch.Tensor:\n for token_id, bias in self.logit_bias.items():\n # Clamp the bias between -100 and 100 per OpenAI API spec\n bias = min(100, max(-100, bias))\n logits[int(token_id)] += bias\n return logits\n\n logits_processors = [logit_bias_logits_processor]\n\n return SamplingParams(\n n=self.n,\n best_of=self.best_of,\n presence_penalty=self.presence_penalty,\n frequency_penalty=self.frequency_penalty,\n repetition_penalty=self.repetition_penalty,\n temperature=self.temperature,\n top_p=self.top_p,\n top_k=self.top_k,\n min_p=self.min_p,\n seed=self.seed,\n stop=self.stop,\n stop_token_ids=self.stop_token_ids,\n ignore_eos=self.ignore_eos,\n max_tokens=self.max_tokens if not echo_without_generation else 1,\n logprobs=self.logprobs,\n use_beam_search=self.use_beam_search,\n early_stopping=self.early_stopping,\n prompt_logprobs=self.logprobs if self.echo else None,\n skip_special_tokens=self.skip_special_tokens,\n spaces_between_special_tokens=(self.spaces_between_special_tokens),\n include_stop_str_in_output=self.include_stop_str_in_output,\n length_penalty=self.length_penalty,\n logits_processors=logits_processors,\n )\n\n @model_validator(mode=\"before\")\n @classmethod\n def check_guided_decoding_count(cls, data):\n guide_count = sum([\n \"guided_json\" in data and data[\"guided_json\"] is not None,\n \"guided_regex\" in data and data[\"guided_regex\"] is not None,\n \"guided_choice\" in data and data[\"guided_choice\"] is not None\n ])\n if guide_count > 1:\n raise ValueError(\n \"You can only use one kind of guided decoding \"\n \"('guided_json', 'guided_regex' or 'guided_choice').\")\n return data\n\n\nclass LogProbs(BaseModel):\n text_offset: List[int] = Field(default_factory=list)\n token_logprobs: List[Optional[float]] = Field(default_factory=list)\n tokens: List[str] = Field(default_factory=list)\n top_logprobs: Optional[List[Optional[Dict[int, float]]]] = None\n\n\nclass CompletionResponseChoice(BaseModel):\n index: int\n text: str\n logprobs: Optional[LogProbs] = None\n finish_reason: Optional[Literal[\"stop\", \"length\"]] = None\n\n\nclass CompletionResponse(BaseModel):\n id: str = Field(default_factory=lambda: f\"cmpl-{random_uuid()}\")\n object: str = \"text_completion\"\n created: int = Field(default_factory=lambda: int(time.time()))\n model: str\n choices: List[CompletionResponseChoice]\n usage: UsageInfo\n\n\nclass CompletionResponseStreamChoice(BaseModel):\n index: int\n text: str\n logprobs: Optional[LogProbs] = None\n finish_reason: Optional[Literal[\"stop\", \"length\"]] = None\n\n\nclass CompletionStreamResponse(BaseModel):\n id: str = Field(default_factory=lambda: f\"cmpl-{random_uuid()}\")\n object: str = \"text_completion\"\n created: int = Field(default_factory=lambda: int(time.time()))\n model: str\n choices: List[CompletionResponseStreamChoice]\n usage: Optional[UsageInfo] = Field(default=None)\n\n\nclass ChatMessage(BaseModel):\n role: str\n content: str\n\n\nclass ChatCompletionResponseChoice(BaseModel):\n index: int\n message: ChatMessage\n logprobs: Optional[LogProbs] = None\n finish_reason: Optional[Literal[\"stop\", \"length\"]] = None\n\n\nclass ChatCompletionResponse(BaseModel):\n id: str = Field(default_factory=lambda: f\"chatcmpl-{random_uuid()}\")\n object: str = \"chat.completion\"\n created: int = Field(default_factory=lambda: int(time.time()))\n model: str\n choices: List[ChatCompletionResponseChoice]\n usage: UsageInfo\n\n\nclass DeltaMessage(BaseModel):\n role: Optional[str] = None\n content: Optional[str] = None\n\n\nclass ChatCompletionResponseStreamChoice(BaseModel):\n index: int\n delta: DeltaMessage\n logprobs: Optional[LogProbs] = None\n finish_reason: Optional[Literal[\"stop\", \"length\"]] = None\n\n\nclass ChatCompletionStreamResponse(BaseModel):\n id: str = Field(default_factory=lambda: f\"chatcmpl-{random_uuid()}\")\n object: str = \"chat.completion.chunk\"\n created: int = Field(default_factory=lambda: int(time.time()))\n model: str\n choices: List[ChatCompletionResponseStreamChoice]\n usage: Optional[UsageInfo] = Field(default=None)\n", "path": "vllm/entrypoints/openai/protocol.py" } ]
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, SequenceStatus\nfrom vllm.utils import Device\nfrom vllm.core.evictor import Evictor, EvictionPolicy, make_evictor\n\n\nclass BlockAllocator:\n \"\"\"Manages free physical token blocks for a device.\n\n The allocator maintains a list of free blocks and allocates a block when\n requested. When a block is freed, its reference count is decremented. If\n the reference count becomes zero, the block is added back to the free list.\n \"\"\"\n\n def __init__(self,\n device: Device,\n block_size: int,\n num_blocks: int,\n eviction_policy: EvictionPolicy = EvictionPolicy.LRU,\n enable_caching: bool = False) -> None:\n self.device = device\n self.block_size = block_size\n self.num_blocks = num_blocks\n self.enable_caching = enable_caching\n\n self.current_num_blocks = 0\n self.cached_blocks: Dict[int, PhysicalTokenBlock] = {}\n\n # Switch over to FIFO eviction when caching is disabled\n if not self.enable_caching:\n eviction_policy = EvictionPolicy.FIFO\n self.evictor: Evictor = make_evictor(eviction_policy)\n\n self.default_hash_ctr = count()\n\n def allocate_block(self, block_hash: int,\n num_hashed_tokens: int) -> PhysicalTokenBlock:\n if self.current_num_blocks == self.num_blocks:\n block = self.evictor.evict()\n block.block_hash = block_hash\n block.num_hashed_tokens = num_hashed_tokens\n return block\n block = PhysicalTokenBlock(device=self.device,\n block_number=self.current_num_blocks,\n block_size=self.block_size,\n block_hash=block_hash,\n num_hashed_tokens=num_hashed_tokens)\n self.current_num_blocks += 1\n return block\n\n def allocate(self,\n block_hash: Optional[int] = None,\n num_hashed_tokens: int = 0) -> PhysicalTokenBlock:\n # If caching is disabled, just allocate a new block and return it\n if not self.enable_caching:\n block = self.allocate_block(next(self.default_hash_ctr),\n num_hashed_tokens)\n block.ref_count += 1\n return block\n\n if block_hash is None:\n block_hash = next(self.default_hash_ctr)\n if block_hash in self.evictor:\n assert block_hash not in self.cached_blocks\n block = self.evictor.remove(block_hash)\n assert block.ref_count == 0\n self.cached_blocks[block_hash] = block\n block.ref_count += 1\n assert block.block_hash == block_hash\n return block\n if block_hash not in self.cached_blocks:\n self.cached_blocks[block_hash] = self.allocate_block(\n block_hash, num_hashed_tokens)\n block = self.cached_blocks[block_hash]\n assert block.block_hash == block_hash\n block.ref_count += 1\n return block\n\n def free(self, block: PhysicalTokenBlock) -> None:\n if block.ref_count == 0:\n raise ValueError(f\"Double free! {block} is already freed.\")\n block.ref_count -= 1\n if block.ref_count == 0:\n assert block.block_hash not in self.evictor\n self.evictor.add(block)\n\n # If caching is enabled, remove the block from the cached_blocks\n if self.enable_caching:\n del self.cached_blocks[block.block_hash]\n\n def get_num_free_blocks(self) -> int:\n return self.num_blocks - self.current_num_blocks + self.evictor.num_blocks\n\n def contains_block(self, block_hash: int) -> bool:\n return block_hash in self.cached_blocks or block_hash in self.evictor\n\n def update_hash(self, block_hash: int, block: PhysicalTokenBlock):\n # If caching is enabled, update the hash of block and the cached_blocks dictionary.\n if self.enable_caching:\n assert not self.contains_block(block_hash)\n old_hash = block.block_hash\n block.block_hash = block_hash\n del self.cached_blocks[old_hash]\n self.cached_blocks[block_hash] = block\n\n\nclass AllocStatus(enum.Enum):\n \"\"\"Result for BlockSpaceManager.can_allocate\n\n 1. Ok: seq_group can be allocated now.\n 2. Later: seq_group cannot be allocated.\n The capacity of allocator is larger than seq_group required.\n 3. Never: seq_group can never be allocated.\n The seq_group is too large to allocated in GPU.\n \"\"\"\n OK = enum.auto()\n LATER = enum.auto()\n NEVER = enum.auto()\n\n\nclass BlockSpaceManager:\n \"\"\"Manages the mapping between logical and physical token blocks.\"\"\"\n\n def __init__(\n self,\n block_size: int,\n num_gpu_blocks: int,\n num_cpu_blocks: int,\n watermark: float = 0.01,\n sliding_window: Optional[int] = None,\n enable_caching: bool = False,\n ) -> None:\n self.block_size = block_size\n self.num_total_gpu_blocks = num_gpu_blocks\n self.num_total_cpu_blocks = num_cpu_blocks\n\n self.block_sliding_window = None\n if sliding_window is not None:\n assert sliding_window % block_size == 0, (sliding_window,\n block_size)\n self.block_sliding_window = sliding_window // block_size\n\n self.watermark = watermark\n assert watermark >= 0.0\n\n self.enable_caching = enable_caching\n\n self.watermark_blocks = int(watermark * num_gpu_blocks)\n self.gpu_allocator = BlockAllocator(Device.GPU,\n block_size,\n num_gpu_blocks,\n enable_caching=enable_caching)\n self.cpu_allocator = BlockAllocator(Device.CPU,\n block_size,\n num_cpu_blocks,\n enable_caching=enable_caching)\n # Mapping: seq_id -> BlockTable.\n self.block_tables: Dict[int, BlockTable] = {}\n\n def can_allocate(self, seq_group: SequenceGroup) -> AllocStatus:\n # FIXME(woosuk): Here we assume that all sequences in the group share\n # the same prompt. This may not be true for preempted sequences.\n seq = seq_group.get_seqs(status=SequenceStatus.WAITING)[0]\n num_required_blocks = len(seq.logical_token_blocks)\n\n if self.block_sliding_window is not None:\n num_required_blocks = min(num_required_blocks,\n self.block_sliding_window)\n num_free_gpu_blocks = self.gpu_allocator.get_num_free_blocks()\n\n # Use watermark to avoid frequent cache eviction.\n if (self.num_total_gpu_blocks - num_required_blocks <\n self.watermark_blocks):\n return AllocStatus.NEVER\n if num_free_gpu_blocks - num_required_blocks >= self.watermark_blocks:\n return AllocStatus.OK\n else:\n return AllocStatus.LATER\n\n def allocate(self, seq_group: SequenceGroup) -> None:\n # NOTE: Here we assume that all sequences in the group have the same\n # prompt.\n seq = seq_group.get_seqs(status=SequenceStatus.WAITING)[0]\n\n # Allocate new physical token blocks that will store the prompt tokens.\n num_prompt_blocks = len(seq.logical_token_blocks)\n\n block_table: BlockTable = []\n for logical_idx in range(num_prompt_blocks):\n if (self.block_sliding_window is not None\n and logical_idx >= self.block_sliding_window):\n block = block_table[logical_idx % self.block_sliding_window]\n else:\n block = self.gpu_allocator.allocate(\n seq.hash_of_block(logical_idx),\n seq.num_hashed_tokens_of_block(logical_idx))\n block_table.append(block)\n\n # Assign the block table for each sequence.\n for seq in seq_group.get_seqs(status=SequenceStatus.WAITING):\n self.block_tables[seq.seq_id] = block_table.copy()\n\n def can_append_slot(self, seq_group: SequenceGroup) -> bool:\n # Simple heuristic: If there is at least one free block\n # for each sequence, we can append.\n num_free_gpu_blocks = self.gpu_allocator.get_num_free_blocks()\n num_seqs = seq_group.num_seqs(status=SequenceStatus.RUNNING)\n return num_seqs <= num_free_gpu_blocks\n\n def _promote_last_block(\n self,\n seq: Sequence,\n last_block: PhysicalTokenBlock,\n ) -> PhysicalTokenBlock:\n # Compute a new hash for the block so that it can be shared by other Sequences\n new_hash = seq.hash_of_block(len(seq.logical_token_blocks) - 1)\n\n # if new_hash is already in the cached table, then free last_block and return the cached version\n if self.gpu_allocator.contains_block(new_hash):\n self.gpu_allocator.free(last_block)\n return self.gpu_allocator.allocate(new_hash)\n else:\n self.gpu_allocator.update_hash(new_hash, last_block)\n return last_block\n\n def _is_last_block_full(\n self,\n seq: Sequence,\n ) -> bool:\n token_ids_len = len(seq.data.get_token_ids())\n return token_ids_len > 0 and token_ids_len % seq.block_size == 0\n\n def _maybe_promote_last_block(\n self,\n seq: Sequence,\n last_block: PhysicalTokenBlock,\n ) -> PhysicalTokenBlock:\n if self._is_last_block_full(seq):\n return self._promote_last_block(seq, last_block)\n else:\n return last_block\n\n def _allocate_last_physical_block(\n self,\n seq: Sequence,\n ) -> PhysicalTokenBlock:\n block_hash: Optional[int] = None\n if (self._is_last_block_full(seq)):\n block_hash = seq.hash_of_block(len(seq.logical_token_blocks) - 1)\n num_hashed_tokens = seq.num_hashed_tokens_of_block(\n len(seq.logical_token_blocks) - 1)\n new_block = self.gpu_allocator.allocate(block_hash, num_hashed_tokens)\n if block_hash is None:\n assert new_block.ref_count == 1\n return new_block\n\n def append_slot(\n self,\n seq: Sequence,\n ) -> Optional[Tuple[int, int]]:\n \"\"\"Allocate a physical slot for a new token.\"\"\"\n logical_blocks = seq.logical_token_blocks\n block_table = self.block_tables[seq.seq_id]\n # If we need to allocate a new physical block\n if len(block_table) < len(logical_blocks):\n # Currently this code only supports adding one physical block\n assert len(block_table) == len(logical_blocks) - 1\n\n if (self.block_sliding_window\n and len(block_table) >= self.block_sliding_window):\n # reuse a block\n block_table.append(block_table[len(block_table) %\n self.block_sliding_window])\n else:\n # The sequence has a new logical block.\n # Allocate a new physical block.\n new_block = self._allocate_last_physical_block(seq)\n block_table.append(new_block)\n return None\n\n # We want to append the token to the last physical block.\n last_block = block_table[-1]\n assert last_block.device == Device.GPU\n if last_block.ref_count == 1:\n # Not shared with other sequences. Appendable.\n # If the last block is now complete, promote it to a full block so that it can be shared\n new_block = self._maybe_promote_last_block(seq, last_block)\n block_table[-1] = new_block\n return None\n else:\n # The last block is shared with other sequences.\n # Copy on Write: Allocate a new block and copy the tokens.\n new_block = self._allocate_last_physical_block(seq)\n\n block_table[-1] = new_block\n self.gpu_allocator.free(last_block)\n return last_block.block_number, new_block.block_number\n\n def fork(self, parent_seq: Sequence, child_seq: Sequence) -> None:\n # NOTE: fork does not allocate a new physical block.\n # Thus, it is always safe from OOM.\n src_block_table = self.block_tables[parent_seq.seq_id]\n self.block_tables[child_seq.seq_id] = src_block_table.copy()\n for block in src_block_table:\n block.ref_count += 1\n\n def _get_physical_blocks(\n self, seq_group: SequenceGroup) -> List[PhysicalTokenBlock]:\n # NOTE: Here, we assume that the physical blocks are only shared by\n # the sequences in the same group.\n blocks: Set[PhysicalTokenBlock] = set()\n for seq in seq_group.get_seqs():\n if seq.is_finished():\n continue\n blocks.update(self.block_tables[seq.seq_id])\n return list(blocks)\n\n def can_swap_in(self, seq_group: SequenceGroup) -> bool:\n blocks = self._get_physical_blocks(seq_group)\n num_swapped_seqs = seq_group.num_seqs(status=SequenceStatus.SWAPPED)\n num_free_blocks = self.gpu_allocator.get_num_free_blocks()\n # NOTE: Conservatively, we assume that every sequence will allocate\n # at least one free block right after the swap-in.\n # NOTE: This should match the logic in can_append_slot().\n num_required_blocks = len(blocks) + num_swapped_seqs\n return num_free_blocks - num_required_blocks >= self.watermark_blocks\n\n def swap_in(self, seq_group: SequenceGroup) -> Dict[int, int]:\n # CPU block -> GPU block.\n mapping: Dict[PhysicalTokenBlock, PhysicalTokenBlock] = {}\n for seq in seq_group.get_seqs(status=SequenceStatus.SWAPPED):\n new_block_table: BlockTable = []\n block_table = self.block_tables[seq.seq_id]\n\n for cpu_block in block_table:\n if cpu_block in mapping:\n gpu_block = mapping[cpu_block]\n gpu_block.ref_count += 1\n else:\n gpu_block = self.gpu_allocator.allocate(\n cpu_block.block_hash, cpu_block.num_hashed_tokens)\n mapping[cpu_block] = gpu_block\n new_block_table.append(gpu_block)\n # Free the CPU block swapped in to GPU.\n self.cpu_allocator.free(cpu_block)\n self.block_tables[seq.seq_id] = new_block_table\n\n block_number_mapping = {\n cpu_block.block_number: gpu_block.block_number\n for cpu_block, gpu_block in mapping.items()\n }\n return block_number_mapping\n\n def can_swap_out(self, seq_group: SequenceGroup) -> bool:\n blocks = self._get_physical_blocks(seq_group)\n return len(blocks) <= self.cpu_allocator.get_num_free_blocks()\n\n def swap_out(self, seq_group: SequenceGroup) -> Dict[int, int]:\n # GPU block -> CPU block.\n mapping: Dict[PhysicalTokenBlock, PhysicalTokenBlock] = {}\n for seq in seq_group.get_seqs(status=SequenceStatus.RUNNING):\n new_block_table: BlockTable = []\n block_table = self.block_tables[seq.seq_id]\n\n for gpu_block in block_table:\n if gpu_block in mapping:\n cpu_block = mapping[gpu_block]\n cpu_block.ref_count += 1\n else:\n cpu_block = self.cpu_allocator.allocate(\n gpu_block.block_hash, gpu_block.num_hashed_tokens)\n mapping[gpu_block] = cpu_block\n new_block_table.append(cpu_block)\n # Free the GPU block swapped out to CPU.\n self.gpu_allocator.free(gpu_block)\n self.block_tables[seq.seq_id] = new_block_table\n\n block_number_mapping = {\n gpu_block.block_number: cpu_block.block_number\n for gpu_block, cpu_block in mapping.items()\n }\n return block_number_mapping\n\n def _free_block_table(self, block_table: BlockTable) -> None:\n for block in set(block_table):\n if block.device == Device.GPU:\n self.gpu_allocator.free(block)\n else:\n self.cpu_allocator.free(block)\n\n def free(self, seq: Sequence) -> None:\n if seq.seq_id not in self.block_tables:\n # Already freed or haven't been scheduled yet.\n return\n block_table = self.block_tables[seq.seq_id]\n self._free_block_table(block_table)\n del self.block_tables[seq.seq_id]\n\n def reset(self) -> None:\n for block_table in self.block_tables.values():\n self._free_block_table(block_table)\n self.block_tables.clear()\n\n def get_block_table(self, seq: Sequence) -> List[int]:\n block_table = self.block_tables[seq.seq_id]\n return [block.block_number for block in block_table]\n\n def get_num_free_gpu_blocks(self) -> int:\n return self.gpu_allocator.get_num_free_blocks()\n\n def get_num_free_cpu_blocks(self) -> int:\n return self.cpu_allocator.get_num_free_blocks()\n\n def access_all_blocks_in_seq(\n self,\n seq: Sequence,\n access_time: float,\n ) -> None:\n block_table = self.block_tables[seq.seq_id]\n for block in block_table:\n block.last_accessed = access_time\n\n def compute_last_full_block_in_seq(self, seq: Sequence):\n if seq.seq_id not in self.block_tables:\n return\n max_full_block = seq.get_len() // self.block_size - 1\n block_table = self.block_tables[seq.seq_id]\n if max_full_block == -1:\n return\n block_table[max_full_block].computed = True\n\n def get_all_block_ids_till_computed(self, seq: Sequence) -> List[int]:\n if seq.seq_id not in self.block_tables:\n return []\n block_table = self.block_tables[seq.seq_id]\n for block_idx in reversed(range(len(block_table))):\n if block_table[block_idx].computed:\n return [b.block_number for b in block_table[:block_idx + 1]]\n return []\n\n def get_common_computed_block_ids(self,\n seq_group: SequenceGroup) -> List[int]:\n # Can return non-empty result only with prefix caching enabled.\n if not self.enable_caching:\n return []\n\n ids_list = [\n self.get_all_block_ids_till_computed(seq)\n for seq in iter(seq_group.seqs_dict.values())\n ]\n return commonprefix([ids for ids in ids_list if ids != []])\n\n def mark_blocks_as_computed(self, seq_group: SequenceGroup):\n # NOTE: We only mark the last full block because with prefix caching,\n # all blocks until the marked one are guaranteed to be computed.\n if self.enable_caching:\n for seq in seq_group.seqs_dict.values():\n self.compute_last_full_block_in_seq(seq)\n", "path": "vllm/core/block_manager.py" }, { "content": "import contextlib\nimport time\nfrom typing import Dict, List, Optional, Tuple, Set, Union\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\n\nfrom vllm.config import (DeviceConfig, ModelConfig, LoRAConfig, ParallelConfig,\n SchedulerConfig)\nfrom vllm.logger import init_logger\nfrom vllm.model_executor import get_model, InputMetadata, SamplingMetadata\nfrom vllm.model_executor.parallel_utils import cupy_utils\nfrom vllm.model_executor.parallel_utils.communication_op import (\n broadcast_tensor_dict)\nfrom vllm.model_executor.parallel_utils.parallel_state import (\n with_cupy_nccl_for_all_reduce)\nfrom vllm.model_executor.parallel_utils import custom_all_reduce\nfrom vllm.sampling_params import SamplingParams, SamplingType\nfrom vllm.sequence import SamplerOutput, SequenceData, SequenceGroupMetadata\nfrom vllm.lora.worker_manager import LRUCacheWorkerLoRAManager\nfrom vllm.lora.layers import LoRAMapping\nfrom vllm.lora.request import LoRARequest\nfrom vllm.utils import in_wsl\n\nlogger = init_logger(__name__)\n\nKVCache = Tuple[torch.Tensor, torch.Tensor]\n_PAD_SLOT_ID = -1\nLORA_WARMUP_RANK = 8\n# Capture graphs for batch size 1, 2, 4, 8, 16, 24, 32, 40, ..., 256.\n# NOTE: _get_graph_batch_size needs to be updated if this list is changed.\n_BATCH_SIZES_TO_CAPTURE = [1, 2, 4] + [8 * i for i in range(1, 33)]\n\n\nclass ModelRunner:\n\n def __init__(\n self,\n model_config: ModelConfig,\n parallel_config: ParallelConfig,\n scheduler_config: SchedulerConfig,\n device_config: DeviceConfig,\n lora_config: Optional[LoRAConfig],\n kv_cache_dtype: Optional[str] = \"auto\",\n is_driver_worker: bool = False,\n ):\n self.model_config = model_config\n self.parallel_config = parallel_config\n self.scheduler_config = scheduler_config\n self.lora_config = lora_config\n self.is_driver_worker = is_driver_worker\n\n # model_config can be None in tests/samplers/test_sampler.py.\n # FIXME(woosuk): This is a hack to make the tests work. Refactor this.\n self.sliding_window = (model_config.get_sliding_window()\n if model_config is not None else None)\n self.device_config = (device_config\n if device_config is not None else DeviceConfig())\n self.device = self.device_config.device\n\n self.model = None\n self.block_size = None # Set after initial profiling.\n self.lora_manager = None\n\n self.graph_runners: Dict[int, CUDAGraphRunner] = {}\n self.graph_memory_pool = None # Set during graph capture.\n\n self.max_context_len_to_capture = (\n self.model_config.max_context_len_to_capture\n if self.model_config is not None else 0)\n # When using CUDA graph, the input block tables must be padded to\n # max_context_len_to_capture. However, creating the block table in\n # Python can be expensive. To optimize this, we cache the block table\n # in numpy and only copy the actual input content at every iteration.\n # The shape of the cached block table will be\n # (max batch size to capture, max context len to capture / block size).\n self.graph_block_tables = None # Set after initial profiling.\n # cache in_wsl result\n self.in_wsl = in_wsl()\n self.kv_cache_dtype = kv_cache_dtype\n\n # Set enforce_eager to True for Neuron backend, to avoid capturing graph\n if self.device_config.is_neuron:\n self.model_config.enforce_eager = True\n\n def load_model(self) -> None:\n self.model = get_model(self.model_config,\n self.device_config,\n lora_config=self.lora_config,\n parallel_config=self.parallel_config,\n scheduler_config=self.scheduler_config)\n\n vocab_size = self.model.config.vocab_size\n\n if self.lora_config:\n assert hasattr(\n self.model, \"supported_lora_modules\"\n ) and self.model.supported_lora_modules, \"Model does not support LoRA\"\n assert hasattr(\n self.model,\n \"embedding_modules\"), \"Model does not have embedding_modules\"\n assert hasattr(self.model, \"embedding_padding_modules\"\n ), \"Model does not have embedding_padding_modules\"\n self.lora_manager = LRUCacheWorkerLoRAManager(\n self.scheduler_config.max_num_seqs,\n self.scheduler_config.max_num_batched_tokens +\n self.scheduler_config.max_paddings, vocab_size,\n self.lora_config, self.device, self.model.embedding_modules,\n self.model.embedding_padding_modules)\n self.model = self.lora_manager.create_lora_manager(self.model)\n\n def set_block_size(self, block_size: int) -> None:\n self.block_size = block_size\n\n max_num_blocks = (self.max_context_len_to_capture + block_size -\n 1) // block_size\n self.graph_block_tables = np.zeros(\n (max(_BATCH_SIZES_TO_CAPTURE), max_num_blocks), dtype=np.int32)\n\n def _prepare_prompt(\n self,\n seq_group_metadata_list: List[SequenceGroupMetadata],\n ) -> Tuple[torch.Tensor, torch.Tensor, InputMetadata, List[int], List[int],\n List[int], List[int], Set[LoRARequest]]:\n assert len(seq_group_metadata_list) > 0\n input_tokens: List[List[int]] = []\n input_positions: List[List[int]] = []\n slot_mapping: List[List[int]] = []\n lora_index_mapping: List[int] = []\n lora_prompt_mapping: List[int] = []\n lora_requests: Set[LoRARequest] = set()\n\n prompt_lens: List[int] = []\n context_lens: List[int] = []\n subquery_lens: List[int] = []\n prefix_block_tables: List[List[int]] = []\n for seq_group_metadata in seq_group_metadata_list:\n assert seq_group_metadata.is_prompt\n seq_ids = list(seq_group_metadata.seq_data.keys())\n assert len(seq_ids) == 1\n seq_id = seq_ids[0]\n\n seq_data = seq_group_metadata.seq_data[seq_id]\n prompt_tokens = seq_data.get_token_ids()\n prompt_len = len(prompt_tokens)\n prompt_lens.append(prompt_len)\n computed_len = 0\n\n # NOTE: This only works for oooooooxxx style attention.\n computed_block_nums = seq_group_metadata.computed_block_nums\n if computed_block_nums is not None and len(\n computed_block_nums) > 0 and self.sliding_window is None:\n # Prefix is not supported with sliding_window\n computed_len = len(computed_block_nums) * self.block_size\n prompt_tokens = prompt_tokens[computed_len:]\n prefix_block_tables.append(computed_block_nums)\n else:\n prefix_block_tables.append([])\n # actual prompt lens\n context_lens.append(computed_len)\n subquery_lens.append(prompt_len - computed_len)\n\n input_tokens.append(prompt_tokens)\n # NOTE(woosuk): Here we assume that the first token in the prompt\n # is always the first token in the sequence.\n input_positions.append(\n list(range(computed_len, computed_len + len(prompt_tokens))))\n\n lora_id = seq_group_metadata.lora_int_id\n\n if lora_id > 0:\n lora_requests.add(seq_group_metadata.lora_request)\n\n lora_index_mapping.append([lora_id] * (prompt_len - computed_len))\n lora_prompt_mapping.extend(\n [lora_id] *\n (prompt_len - computed_len\n if seq_group_metadata.sampling_params.prompt_logprobs else 1))\n\n if seq_group_metadata.block_tables is None:\n # During memory profiling, the block tables are not initialized\n # yet. In this case, we just use a dummy slot mapping.\n slot_mapping.append([_PAD_SLOT_ID] * prompt_len)\n continue\n\n # Compute the slot mapping.\n slot_mapping.append([])\n block_table = seq_group_metadata.block_tables[seq_id]\n # Mask the [0, start_idx) tokens of the prompt with _PAD_SLOT_ID,\n # where start_idx is max(0, prompt_len - sliding_window).\n # For example, if the prompt len is 10, sliding window is 8, and\n # block size is 4, the first two tokens are masked and the slot\n # mapping will be [-1, -1, 2, 3, 4, 5, 6, 7, 0, 1].\n start_idx = 0\n if self.sliding_window is not None:\n assert computed_len == 0, (\n \"Prefix caching is currently not supported with \"\n \"sliding window attention\")\n start_idx = max(0, prompt_len - self.sliding_window)\n for i in range(computed_len, prompt_len):\n if i < start_idx:\n slot_mapping[-1].append(_PAD_SLOT_ID)\n continue\n\n block_number = block_table[i // self.block_size]\n block_offset = i % self.block_size\n slot = block_number * self.block_size + block_offset\n slot_mapping[-1].append(slot)\n\n max_prompt_len = max(subquery_lens)\n input_tokens = _make_tensor_with_pad(input_tokens,\n max_prompt_len,\n pad=0,\n dtype=torch.long,\n device=self.device)\n input_positions = _make_tensor_with_pad(input_positions,\n max_prompt_len,\n pad=0,\n dtype=torch.long,\n device=self.device)\n slot_mapping = _make_tensor_with_pad(slot_mapping,\n max_prompt_len,\n pad=_PAD_SLOT_ID,\n dtype=torch.long,\n device=self.device)\n lora_index_mapping = [\n _pad_to_max(mapping, max_prompt_len, pad=0)\n for mapping in lora_index_mapping\n ]\n context_lens_tensor = torch.tensor(context_lens,\n dtype=torch.int,\n device=self.device)\n # Prepare prefix block tables\n max_prompt_block_table_len = max(len(t) for t in prefix_block_tables)\n block_tables = _make_tensor_with_pad(\n prefix_block_tables,\n max_len=max_prompt_block_table_len,\n pad=0,\n dtype=torch.int,\n device=self.device,\n )\n start_loc_tensor = torch.arange(0,\n len(prompt_lens) * max_prompt_len,\n max_prompt_len,\n dtype=torch.long,\n device=self.device)\n prompt_lens_tensor = torch.tensor(prompt_lens,\n dtype=torch.long,\n device=self.device)\n\n input_metadata = InputMetadata(\n is_prompt=True,\n slot_mapping=slot_mapping,\n prompt_lens=prompt_lens_tensor,\n max_seq_len=max_prompt_len,\n start_loc=start_loc_tensor,\n max_context_len=None,\n context_lens=context_lens_tensor,\n block_tables=block_tables,\n use_cuda_graph=False,\n kv_cache_dtype=self.kv_cache_dtype,\n )\n return (input_tokens, input_positions, input_metadata, prompt_lens,\n subquery_lens, lora_index_mapping, lora_prompt_mapping,\n lora_requests)\n\n def _prepare_decode(\n self,\n seq_group_metadata_list: List[SequenceGroupMetadata],\n ) -> Tuple[torch.Tensor, torch.Tensor, InputMetadata, List[int], List[int],\n Set[LoRARequest]]:\n assert len(seq_group_metadata_list) > 0\n input_tokens: List[List[int]] = []\n input_positions: List[List[int]] = []\n slot_mapping: List[List[int]] = []\n context_lens: List[int] = []\n block_tables: List[List[int]] = []\n lora_index_mapping: List[int] = []\n lora_prompt_mapping: List[int] = []\n lora_requests: Set[LoRARequest] = set()\n\n for seq_group_metadata in seq_group_metadata_list:\n assert not seq_group_metadata.is_prompt\n\n seq_ids = list(seq_group_metadata.seq_data.keys())\n lora_id = seq_group_metadata.lora_int_id\n\n if lora_id > 0:\n lora_requests.add(seq_group_metadata.lora_request)\n\n for seq_id in seq_ids:\n seq_data = seq_group_metadata.seq_data[seq_id]\n generation_token = seq_data.get_last_token_id()\n input_tokens.append([generation_token])\n\n seq_len = seq_data.get_len()\n position = seq_len - 1\n input_positions.append([position])\n\n context_len = seq_len if self.sliding_window is None else min(\n seq_len, self.sliding_window)\n context_lens.append(context_len)\n\n block_table = seq_group_metadata.block_tables[seq_id]\n block_number = block_table[position // self.block_size]\n block_offset = position % self.block_size\n slot = block_number * self.block_size + block_offset\n slot_mapping.append([slot])\n lora_index_mapping.append([lora_id])\n lora_prompt_mapping.append(lora_id)\n\n if self.sliding_window is not None:\n sliding_window_blocks = (self.sliding_window //\n self.block_size)\n block_table = block_table[-sliding_window_blocks:]\n block_tables.append(block_table)\n\n batch_size = len(input_tokens)\n max_context_len = max(context_lens)\n use_captured_graph = (\n not self.model_config.enforce_eager\n and batch_size <= _BATCH_SIZES_TO_CAPTURE[-1]\n and max_context_len <= self.max_context_len_to_capture)\n if use_captured_graph:\n # Pad the input tokens, positions, and slot mapping to match the\n # batch size of the captured graph.\n graph_batch_size = _get_graph_batch_size(batch_size)\n assert graph_batch_size >= batch_size\n for _ in range(graph_batch_size - batch_size):\n input_tokens.append([])\n input_positions.append([])\n slot_mapping.append([])\n context_lens.append(1)\n block_tables.append([])\n batch_size = graph_batch_size\n\n input_tokens = _make_tensor_with_pad(input_tokens,\n max_len=1,\n pad=0,\n dtype=torch.long,\n device=self.device)\n input_positions = _make_tensor_with_pad(input_positions,\n max_len=1,\n pad=0,\n dtype=torch.long,\n device=self.device)\n slot_mapping = _make_tensor_with_pad(slot_mapping,\n max_len=1,\n pad=_PAD_SLOT_ID,\n dtype=torch.long,\n device=self.device)\n context_lens = torch.tensor(context_lens,\n dtype=torch.int,\n device=self.device)\n\n if use_captured_graph:\n # The shape of graph_block_tables is\n # [max batch size, max context len // block size].\n input_block_tables = self.graph_block_tables[:batch_size]\n for i, block_table in enumerate(block_tables):\n if block_table:\n input_block_tables[i, :len(block_table)] = block_table\n block_tables = torch.tensor(input_block_tables, device=self.device)\n else:\n max_block_table_len = max(\n len(block_table) for block_table in block_tables)\n block_tables = _make_tensor_with_pad(\n block_tables,\n max_len=max_block_table_len,\n pad=0,\n dtype=torch.int,\n device=self.device,\n )\n\n lora_index_mapping = [\n _pad_to_max(mapping, 1, pad=0) for mapping in lora_index_mapping\n ]\n\n input_metadata = InputMetadata(\n is_prompt=False,\n slot_mapping=slot_mapping,\n prompt_lens=None,\n max_seq_len=None,\n start_loc=None,\n max_context_len=max_context_len,\n context_lens=context_lens,\n block_tables=block_tables,\n use_cuda_graph=use_captured_graph,\n kv_cache_dtype=self.kv_cache_dtype,\n )\n return (input_tokens, input_positions, input_metadata,\n lora_index_mapping, lora_prompt_mapping, lora_requests)\n\n def _prepare_sample(\n self,\n seq_group_metadata_list: List[SequenceGroupMetadata],\n prompt_lens: List[int],\n subquery_lens: Optional[List[int]],\n ) -> SamplingMetadata:\n seq_groups: List[Tuple[List[int], SamplingParams]] = []\n selected_token_indices: List[int] = []\n generators: List[torch.Generator] = []\n selected_token_start_idx = 0\n categorized_sample_indices = {t: [] for t in SamplingType}\n categorized_sample_indices_start_idx = 0\n pin_memory = not self.in_wsl and not self.device_config.is_neuron\n\n max_subquery_len = max(subquery_lens) if subquery_lens else 1\n for i, seq_group_metadata in enumerate(seq_group_metadata_list):\n seq_ids = list(seq_group_metadata.seq_data.keys())\n sampling_params = seq_group_metadata.sampling_params\n seq_groups.append((seq_ids, sampling_params))\n\n if seq_group_metadata.is_prompt:\n assert len(seq_ids) == 1\n assert subquery_lens is not None\n subquery_len = subquery_lens[i]\n if sampling_params.prompt_logprobs is not None:\n # NOTE: prompt token positions do not need sample, skip\n categorized_sample_indices_start_idx += subquery_len - 1\n\n categorized_sample_indices[\n sampling_params.sampling_type].append(\n categorized_sample_indices_start_idx)\n categorized_sample_indices_start_idx += 1\n\n if sampling_params.prompt_logprobs is not None:\n selected_token_indices.extend(\n range(selected_token_start_idx,\n selected_token_start_idx + subquery_len - 1))\n selected_token_indices.append(selected_token_start_idx +\n subquery_len - 1)\n selected_token_start_idx += max_subquery_len\n\n if sampling_params.seed is not None:\n seq_group_metadata.state.generator = torch.Generator(\n device=\"cuda\").manual_seed(sampling_params.seed)\n else:\n num_seqs = len(seq_ids)\n selected_token_indices.extend(\n range(selected_token_start_idx,\n selected_token_start_idx + num_seqs))\n selected_token_start_idx += num_seqs\n\n categorized_sample_indices[\n sampling_params.sampling_type].extend(\n range(categorized_sample_indices_start_idx,\n categorized_sample_indices_start_idx + num_seqs))\n categorized_sample_indices_start_idx += num_seqs\n\n if sampling_params.seed is not None:\n generators.append(seq_group_metadata.state.generator)\n\n selected_token_indices = _async_h2d(selected_token_indices,\n dtype=torch.long,\n target_device=self.device,\n pin_memory=pin_memory)\n categorized_sample_indices = {\n t: _async_h2d(seq_ids,\n dtype=torch.int,\n target_device=self.device,\n pin_memory=pin_memory)\n for t, seq_ids in categorized_sample_indices.items()\n }\n\n seq_data: Dict[int, SequenceData] = {}\n for seq_group_metadata in seq_group_metadata_list:\n seq_data.update(seq_group_metadata.seq_data)\n\n sampling_metadata = SamplingMetadata(\n seq_groups=seq_groups,\n seq_data=seq_data,\n prompt_lens=prompt_lens,\n selected_token_indices=selected_token_indices,\n categorized_sample_indices=categorized_sample_indices,\n generators=generators,\n )\n return sampling_metadata\n\n def prepare_input_tensors(\n self,\n seq_group_metadata_list: Optional[List[SequenceGroupMetadata]],\n ) -> Tuple[torch.Tensor, torch.Tensor, InputMetadata, SamplingMetadata,\n Set[int], LoRAMapping]:\n if self.is_driver_worker:\n # NOTE: We assume that all sequences in the group are all prompts or\n # all decodes.\n is_prompt = seq_group_metadata_list[0].is_prompt\n # Prepare input tensors.\n if is_prompt:\n (input_tokens, input_positions, input_metadata, prompt_lens,\n subquery_lens, lora_index_mapping, lora_prompt_mapping,\n lora_requests) = self._prepare_prompt(seq_group_metadata_list)\n else:\n (input_tokens, input_positions, input_metadata,\n lora_index_mapping, lora_prompt_mapping,\n lora_requests) = self._prepare_decode(seq_group_metadata_list)\n prompt_lens = []\n subquery_lens = None\n sampling_metadata = self._prepare_sample(seq_group_metadata_list,\n prompt_lens,\n subquery_lens)\n\n if self.lora_config:\n flat_lora_index_mapping = [\n item for sublist in lora_index_mapping for item in sublist\n ]\n lora_mapping = LoRAMapping(\n flat_lora_index_mapping,\n lora_prompt_mapping,\n )\n else:\n lora_mapping = None\n\n # Broadcast the metadata.\n metadata_dict = {\n \"input_tokens\": input_tokens,\n \"input_positions\": input_positions,\n \"is_prompt\": input_metadata.is_prompt,\n \"slot_mapping\": input_metadata.slot_mapping,\n \"prompt_lens\": input_metadata.prompt_lens,\n \"max_seq_len\": input_metadata.max_seq_len,\n \"start_loc\": input_metadata.start_loc,\n \"max_context_len\": input_metadata.max_context_len,\n \"context_lens\": input_metadata.context_lens,\n \"block_tables\": input_metadata.block_tables,\n \"use_cuda_graph\": input_metadata.use_cuda_graph,\n \"kv_cache_dtype\": input_metadata.kv_cache_dtype,\n \"selected_token_indices\":\n sampling_metadata.selected_token_indices,\n \"lora_requests\": lora_requests,\n \"lora_mapping\": lora_mapping,\n }\n broadcast_tensor_dict(metadata_dict, src=0)\n else:\n metadata_dict = broadcast_tensor_dict(src=0)\n input_tokens = metadata_dict[\"input_tokens\"]\n input_positions = metadata_dict[\"input_positions\"]\n lora_mapping = metadata_dict[\"lora_mapping\"]\n lora_requests = metadata_dict[\"lora_requests\"]\n input_metadata = InputMetadata(\n is_prompt=metadata_dict[\"is_prompt\"],\n slot_mapping=metadata_dict[\"slot_mapping\"],\n prompt_lens=metadata_dict[\"prompt_lens\"],\n max_seq_len=metadata_dict[\"max_seq_len\"],\n start_loc=metadata_dict[\"start_loc\"],\n max_context_len=metadata_dict[\"max_context_len\"],\n context_lens=metadata_dict[\"context_lens\"],\n block_tables=metadata_dict[\"block_tables\"],\n use_cuda_graph=metadata_dict[\"use_cuda_graph\"],\n kv_cache_dtype=metadata_dict[\"kv_cache_dtype\"],\n )\n sampling_metadata = SamplingMetadata(\n seq_groups=None,\n seq_data=None,\n prompt_lens=None,\n selected_token_indices=metadata_dict[\"selected_token_indices\"],\n categorized_sample_indices=None,\n generators=None,\n perform_sampling=False,\n )\n\n return (input_tokens, input_positions, input_metadata,\n sampling_metadata, lora_requests, lora_mapping)\n\n @torch.inference_mode()\n def execute_model(\n self,\n seq_group_metadata_list: Optional[List[SequenceGroupMetadata]],\n kv_caches: List[Tuple[torch.Tensor, torch.Tensor]],\n ) -> Optional[SamplerOutput]:\n (input_tokens, input_positions, input_metadata, sampling_metadata,\n lora_requests,\n lora_mapping) = self.prepare_input_tensors(seq_group_metadata_list)\n\n if self.lora_config:\n self.set_active_loras(lora_requests, lora_mapping)\n\n # Execute the model.\n if input_metadata.use_cuda_graph:\n graph_batch_size = input_tokens.shape[0]\n model_executable = self.graph_runners[graph_batch_size]\n else:\n model_executable = self.model\n hidden_states = model_executable(\n input_ids=input_tokens,\n positions=input_positions,\n kv_caches=kv_caches,\n input_metadata=input_metadata,\n )\n\n # Sample the next token.\n output = self.model.sample(\n hidden_states=hidden_states,\n sampling_metadata=sampling_metadata,\n )\n return output\n\n @torch.inference_mode()\n def profile_run(self) -> None:\n # Enable top-k sampling to reflect the accurate memory usage.\n vocab_size = self.model_config.get_vocab_size()\n sampling_params = SamplingParams(top_p=0.99, top_k=vocab_size - 1)\n max_num_batched_tokens = self.scheduler_config.max_num_batched_tokens\n max_num_seqs = self.scheduler_config.max_num_seqs\n\n # This represents the maximum number of different requests\n # that will have unique loras, an therefore the max amount of memory\n # consumption create dummy lora request copies from the lora request\n # passed in, which contains a lora from the lora warmup path.\n dummy_lora_requests = []\n dummy_lora_requests_per_seq = []\n if self.lora_config:\n for idx in range(self.lora_config.max_loras):\n lora_id = idx + 1\n dummy_lora_request = LoRARequest(\n lora_name=f\"warmup_{lora_id}\",\n lora_int_id=lora_id,\n lora_local_path=\"/not/a/real/path\",\n )\n self.lora_manager.add_dummy_lora(dummy_lora_request,\n rank=LORA_WARMUP_RANK)\n dummy_lora_requests.append(dummy_lora_request)\n dummy_lora_requests_per_seq = [\n dummy_lora_requests[idx % len(dummy_lora_requests)]\n for idx in range(max_num_seqs)\n ]\n\n # Profile memory usage with max_num_sequences sequences and the total\n # number of tokens equal to max_num_batched_tokens.\n seqs: List[SequenceGroupMetadata] = []\n for group_id in range(max_num_seqs):\n seq_len = (max_num_batched_tokens // max_num_seqs +\n (group_id < max_num_batched_tokens % max_num_seqs))\n seq_data = SequenceData([0] * seq_len)\n seq = SequenceGroupMetadata(\n request_id=str(group_id),\n is_prompt=True,\n seq_data={group_id: seq_data},\n sampling_params=sampling_params,\n block_tables=None,\n lora_request=dummy_lora_requests_per_seq[group_id]\n if dummy_lora_requests_per_seq else None,\n )\n seqs.append(seq)\n\n # Run the model with the dummy inputs.\n num_layers = self.model_config.get_num_layers(self.parallel_config)\n kv_caches = [(None, None)] * num_layers\n self.execute_model(seqs, kv_caches)\n torch.cuda.synchronize()\n return\n\n def remove_all_loras(self) -> bool:\n if not self.lora_manager:\n raise RuntimeError(\"LoRA is not enabled.\")\n return self.lora_manager.remove_all_loras()\n\n def set_active_loras(self, lora_requests: List[LoRARequest],\n lora_mapping: LoRAMapping) -> None:\n if not self.lora_manager:\n raise RuntimeError(\"LoRA is not enabled.\")\n self.lora_manager.set_active_loras(lora_requests, lora_mapping)\n\n def add_lora(self, lora_request: LoRARequest) -> bool:\n if not self.lora_manager:\n raise RuntimeError(\"LoRA is not enabled.\")\n return self.lora_manager.add_lora(lora_request)\n\n def remove_lora(self, lora_id: int) -> bool:\n if not self.lora_manager:\n raise RuntimeError(\"LoRA is not enabled.\")\n return self.lora_manager.remove_lora(lora_id)\n\n def list_loras(self) -> Set[int]:\n if not self.lora_manager:\n raise RuntimeError(\"LoRA is not enabled.\")\n return self.lora_manager.list_loras()\n\n @torch.inference_mode()\n def capture_model(self, kv_caches: List[KVCache]) -> None:\n # NOTE(woosuk): This is a hack to ensure that the NCCL backend is never\n # deleted before the CUDA graphs.\n self.cupy_nccl_backend = cupy_utils.get_nccl_backend()\n\n assert not self.model_config.enforce_eager\n logger.info(\"Capturing the model for CUDA graphs. This may lead to \"\n \"unexpected consequences if the model is not static. To \"\n \"run the model in eager mode, set 'enforce_eager=True' or \"\n \"use '--enforce-eager' in the CLI.\")\n logger.info(\"CUDA graphs can take additional 1~3 GiB memory per GPU. \"\n \"If you are running out of memory, consider decreasing \"\n \"`gpu_memory_utilization` or enforcing eager mode. \"\n \"You can also reduce the `max_num_seqs` as needed \"\n \"to decrease memory usage.\")\n start_time = time.perf_counter()\n\n # Prepare dummy inputs. These will be reused for all batch sizes.\n max_batch_size = max(_BATCH_SIZES_TO_CAPTURE)\n input_tokens = torch.zeros(max_batch_size, 1, dtype=torch.long).cuda()\n input_positions = torch.zeros(max_batch_size, 1,\n dtype=torch.long).cuda()\n slot_mapping = torch.empty(max_batch_size, 1, dtype=torch.long).cuda()\n slot_mapping.fill_(_PAD_SLOT_ID)\n context_lens = torch.ones(max_batch_size, dtype=torch.int32).cuda()\n block_tables = torch.from_numpy(self.graph_block_tables).cuda()\n\n graph_batch_size = _get_graph_batch_size(\n self.scheduler_config.max_num_seqs)\n batch_size_capture_list = [\n bs for bs in _BATCH_SIZES_TO_CAPTURE if bs <= graph_batch_size\n ]\n\n # NOTE(woosuk): There are 3 backends for all-reduce: custom all-reduce\n # kernel, CuPy NCCL, and PyTorch NCCL. When using CUDA graph, we use\n # either custom all-reduce kernel or CuPy NCCL. When not using CUDA\n # graph, we use either custom all-reduce kernel or PyTorch NCCL.\n # We always prioritize using custom all-reduce kernel but fall back\n # to PyTorch or CuPy NCCL if it is disabled or not supported.\n with custom_all_reduce.capture():\n # NOTE: Capturing the largest batch size first may help reduce the\n # memory usage of CUDA graph.\n for batch_size in reversed(batch_size_capture_list):\n # Create dummy input_metadata.\n input_metadata = InputMetadata(\n is_prompt=False,\n slot_mapping=slot_mapping[:batch_size],\n prompt_lens=None,\n max_seq_len=None,\n start_loc=None,\n max_context_len=self.max_context_len_to_capture,\n context_lens=context_lens[:batch_size],\n block_tables=block_tables[:batch_size],\n use_cuda_graph=True,\n kv_cache_dtype=self.kv_cache_dtype,\n )\n\n if self.lora_config:\n lora_mapping = LoRAMapping(\n [0] * batch_size,\n [0] * batch_size,\n )\n self.set_active_loras(set(), lora_mapping)\n\n graph_runner = CUDAGraphRunner(self.model)\n graph_runner.capture(\n input_tokens[:batch_size],\n input_positions[:batch_size],\n kv_caches,\n input_metadata,\n memory_pool=self.graph_memory_pool,\n )\n self.graph_memory_pool = graph_runner.graph.pool()\n self.graph_runners[batch_size] = graph_runner\n\n end_time = time.perf_counter()\n elapsed_time = end_time - start_time\n # This usually takes < 10 seconds.\n logger.info(f\"Graph capturing finished in {elapsed_time:.0f} secs.\")\n\n def __del__(self) -> None:\n # Delete the CUDA graphs before deleting the CuPy NCCL communicator.\n # NOTE(woosuk): This is necessary because otherwise deadlocks can\n # happen.\n # FIXME(woosuk): This is a bit hacky. Find a more robust solution.\n self.graph_runners.clear()\n self.cupy_nccl_backend = None\n\n\nclass CUDAGraphRunner:\n\n def __init__(self, model: nn.Module):\n self.model = model\n self.graph = None\n self.input_buffers: Dict[str, torch.Tensor] = {}\n self.output_buffers: Dict[str, torch.Tensor] = {}\n\n def capture(\n self,\n input_ids: torch.Tensor,\n positions: torch.Tensor,\n kv_caches: List[KVCache],\n input_metadata: InputMetadata,\n memory_pool,\n ) -> None:\n assert self.graph is None\n # Run the model once without capturing the graph.\n # This is to make sure that the captured graph does not include the\n # kernel launches for initial benchmarking (e.g., Triton autotune).\n with _maybe_cupy_nccl():\n self.model(\n input_ids,\n positions,\n kv_caches,\n input_metadata,\n )\n torch.cuda.synchronize()\n\n # Capture the graph.\n # NOTE(woosuk): Python 3.8 does not support multi-line with statements.\n # https://stackoverflow.com/questions/31039022/python-multi-line-with-statement\n self.graph = torch.cuda.CUDAGraph()\n with torch.cuda.graph(self.graph, pool=memory_pool): # noqa: SIM117\n with _maybe_cupy_nccl():\n hidden_states = self.model(\n input_ids,\n positions,\n kv_caches,\n input_metadata,\n )\n torch.cuda.synchronize()\n\n # Save the input and output buffers.\n self.input_buffers = {\n \"input_ids\": input_ids,\n \"positions\": positions,\n \"kv_caches\": kv_caches,\n \"slot_mapping\": input_metadata.slot_mapping,\n \"context_lens\": input_metadata.context_lens,\n \"block_tables\": input_metadata.block_tables,\n }\n self.output_buffers = {\"hidden_states\": hidden_states}\n return\n\n def forward(\n self,\n input_ids: torch.Tensor,\n positions: torch.Tensor,\n kv_caches: List[Tuple[torch.Tensor, torch.Tensor]],\n input_metadata: InputMetadata,\n ) -> torch.Tensor:\n # KV caches are fixed tensors, so we don't need to copy them.\n del kv_caches\n\n # Copy the input tensors to the input buffers.\n self.input_buffers[\"input_ids\"].copy_(input_ids, non_blocking=True)\n self.input_buffers[\"positions\"].copy_(positions, non_blocking=True)\n self.input_buffers[\"slot_mapping\"].copy_(input_metadata.slot_mapping,\n non_blocking=True)\n self.input_buffers[\"context_lens\"].copy_(input_metadata.context_lens,\n non_blocking=True)\n self.input_buffers[\"block_tables\"].copy_(input_metadata.block_tables,\n non_blocking=True)\n\n # Run the graph.\n self.graph.replay()\n\n # Return the output tensor.\n return self.output_buffers[\"hidden_states\"]\n\n def __call__(self, *args, **kwargs):\n return self.forward(*args, **kwargs)\n\n\[email protected]\ndef _maybe_cupy_nccl():\n if cupy_utils.is_initialized() and not custom_all_reduce.is_initialized():\n with with_cupy_nccl_for_all_reduce():\n yield\n else:\n yield\n\n\ndef _pad_to_max(x: List[int], max_len: int, pad: int) -> List[int]:\n assert len(x) <= max_len\n return x + [pad] * (max_len - len(x))\n\n\ndef _make_tensor_with_pad(\n x: List[List[int]],\n max_len: int,\n pad: int,\n dtype: torch.dtype,\n device: Optional[Union[str, torch.device]],\n) -> torch.Tensor:\n padded_x = [_pad_to_max(x_i, max_len, pad) for x_i in x]\n return torch.tensor(padded_x, dtype=dtype, device=device)\n\n\ndef _get_graph_batch_size(batch_size: int) -> int:\n if batch_size <= 2:\n return batch_size\n elif batch_size <= 4:\n return 4\n else:\n return (batch_size + 7) // 8 * 8\n\n\ndef _async_h2d(\n data: list,\n dtype: torch.dtype,\n target_device: Union[str, torch.device],\n pin_memory: bool,\n) -> torch.Tensor:\n t = torch.tensor(data, dtype=dtype, pin_memory=pin_memory, device=\"cpu\")\n return t.to(device=target_device, non_blocking=True)\n", "path": "vllm/worker/model_runner.py" } ]
[ { "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, SequenceGroup, SequenceStatus\nfrom vllm.utils import Device\nfrom vllm.core.evictor import Evictor, EvictionPolicy, make_evictor\n\n\nclass BlockAllocator:\n \"\"\"Manages free physical token blocks for a device.\n\n The allocator maintains a list of free blocks and allocates a block when\n requested. When a block is freed, its reference count is decremented. If\n the reference count becomes zero, the block is added back to the free list.\n \"\"\"\n\n def __init__(self,\n device: Device,\n block_size: int,\n num_blocks: int,\n eviction_policy: EvictionPolicy = EvictionPolicy.LRU,\n enable_caching: bool = False) -> None:\n self.device = device\n self.block_size = block_size\n self.num_blocks = num_blocks\n self.enable_caching = enable_caching\n\n self.current_num_blocks = 0\n self.cached_blocks: Dict[int, PhysicalTokenBlock] = {}\n\n # Switch over to FIFO eviction when caching is disabled\n if not self.enable_caching:\n eviction_policy = EvictionPolicy.FIFO\n self.evictor: Evictor = make_evictor(eviction_policy)\n\n self.default_hash_ctr = count()\n\n def allocate_block(self, block_hash: int,\n num_hashed_tokens: int) -> PhysicalTokenBlock:\n if self.current_num_blocks == self.num_blocks:\n block = self.evictor.evict()\n block.block_hash = block_hash\n block.num_hashed_tokens = num_hashed_tokens\n return block\n block = PhysicalTokenBlock(device=self.device,\n block_number=self.current_num_blocks,\n block_size=self.block_size,\n block_hash=block_hash,\n num_hashed_tokens=num_hashed_tokens)\n self.current_num_blocks += 1\n return block\n\n def allocate(self,\n block_hash: Optional[int] = None,\n num_hashed_tokens: int = 0) -> PhysicalTokenBlock:\n # If caching is disabled, just allocate a new block and return it\n if not self.enable_caching:\n block = self.allocate_block(next(self.default_hash_ctr),\n num_hashed_tokens)\n block.ref_count += 1\n return block\n\n if block_hash is None:\n block_hash = next(self.default_hash_ctr)\n if block_hash in self.evictor:\n assert block_hash not in self.cached_blocks\n block = self.evictor.remove(block_hash)\n assert block.ref_count == 0\n self.cached_blocks[block_hash] = block\n block.ref_count += 1\n assert block.block_hash == block_hash\n return block\n if block_hash not in self.cached_blocks:\n self.cached_blocks[block_hash] = self.allocate_block(\n block_hash, num_hashed_tokens)\n block = self.cached_blocks[block_hash]\n assert block.block_hash == block_hash\n block.ref_count += 1\n return block\n\n def free(self, block: PhysicalTokenBlock) -> None:\n if block.ref_count == 0:\n raise ValueError(f\"Double free! {block} is already freed.\")\n block.ref_count -= 1\n if block.ref_count == 0:\n assert block.block_hash not in self.evictor\n self.evictor.add(block)\n\n # If caching is enabled, remove the block from the cached_blocks\n if self.enable_caching:\n del self.cached_blocks[block.block_hash]\n\n def get_num_free_blocks(self) -> int:\n return self.num_blocks - self.current_num_blocks + self.evictor.num_blocks\n\n def contains_block(self, block_hash: int) -> bool:\n return block_hash in self.cached_blocks or block_hash in self.evictor\n\n def update_hash(self, block_hash: int, block: PhysicalTokenBlock):\n # If caching is enabled, update the hash of block and the cached_blocks dictionary.\n if self.enable_caching:\n assert not self.contains_block(block_hash)\n old_hash = block.block_hash\n block.block_hash = block_hash\n del self.cached_blocks[old_hash]\n self.cached_blocks[block_hash] = block\n\n\nclass AllocStatus(enum.Enum):\n \"\"\"Result for BlockSpaceManager.can_allocate\n\n 1. Ok: seq_group can be allocated now.\n 2. Later: seq_group cannot be allocated.\n The capacity of allocator is larger than seq_group required.\n 3. Never: seq_group can never be allocated.\n The seq_group is too large to allocated in GPU.\n \"\"\"\n OK = enum.auto()\n LATER = enum.auto()\n NEVER = enum.auto()\n\n\nclass BlockSpaceManager:\n \"\"\"Manages the mapping between logical and physical token blocks.\"\"\"\n\n def __init__(\n self,\n block_size: int,\n num_gpu_blocks: int,\n num_cpu_blocks: int,\n watermark: float = 0.01,\n sliding_window: Optional[int] = None,\n enable_caching: bool = False,\n ) -> None:\n self.block_size = block_size\n self.num_total_gpu_blocks = num_gpu_blocks\n self.num_total_cpu_blocks = num_cpu_blocks\n\n self.block_sliding_window = None\n if sliding_window is not None:\n assert sliding_window % block_size == 0, (sliding_window,\n block_size)\n self.block_sliding_window = sliding_window // block_size\n\n self.watermark = watermark\n assert watermark >= 0.0\n\n self.enable_caching = enable_caching\n\n self.watermark_blocks = int(watermark * num_gpu_blocks)\n self.gpu_allocator = BlockAllocator(Device.GPU,\n block_size,\n num_gpu_blocks,\n enable_caching=enable_caching)\n self.cpu_allocator = BlockAllocator(Device.CPU,\n block_size,\n num_cpu_blocks,\n enable_caching=enable_caching)\n # Mapping: seq_id -> BlockTable.\n self.block_tables: Dict[int, BlockTable] = {}\n\n def can_allocate(self, seq_group: SequenceGroup) -> AllocStatus:\n # FIXME(woosuk): Here we assume that all sequences in the group share\n # the same prompt. This may not be true for preempted sequences.\n seq = seq_group.get_seqs(status=SequenceStatus.WAITING)[0]\n num_required_blocks = len(seq.logical_token_blocks)\n\n if self.block_sliding_window is not None:\n num_required_blocks = min(num_required_blocks,\n self.block_sliding_window)\n num_free_gpu_blocks = self.gpu_allocator.get_num_free_blocks()\n\n # Use watermark to avoid frequent cache eviction.\n if (self.num_total_gpu_blocks - num_required_blocks <\n self.watermark_blocks):\n return AllocStatus.NEVER\n if num_free_gpu_blocks - num_required_blocks >= self.watermark_blocks:\n return AllocStatus.OK\n else:\n return AllocStatus.LATER\n\n def allocate(self, seq_group: SequenceGroup) -> None:\n # NOTE: Here we assume that all sequences in the group have the same\n # prompt.\n seq = seq_group.get_seqs(status=SequenceStatus.WAITING)[0]\n\n # Allocate new physical token blocks that will store the prompt tokens.\n num_prompt_blocks = len(seq.logical_token_blocks)\n\n block_table: BlockTable = []\n for logical_idx in range(num_prompt_blocks):\n if (self.block_sliding_window is not None\n and logical_idx >= self.block_sliding_window):\n block = block_table[logical_idx % self.block_sliding_window]\n else:\n block = self.gpu_allocator.allocate(\n seq.hash_of_block(logical_idx),\n seq.num_hashed_tokens_of_block(logical_idx))\n block_table.append(block)\n\n # Assign the block table for each sequence.\n for seq in seq_group.get_seqs(status=SequenceStatus.WAITING):\n self.block_tables[seq.seq_id] = block_table.copy()\n\n def can_append_slot(self, seq_group: SequenceGroup) -> bool:\n # Simple heuristic: If there is at least one free block\n # for each sequence, we can append.\n num_free_gpu_blocks = self.gpu_allocator.get_num_free_blocks()\n num_seqs = seq_group.num_seqs(status=SequenceStatus.RUNNING)\n return num_seqs <= num_free_gpu_blocks\n\n def _promote_last_block(\n self,\n seq: Sequence,\n last_block: PhysicalTokenBlock,\n ) -> PhysicalTokenBlock:\n # Compute a new hash for the block so that it can be shared by other Sequences\n new_hash = seq.hash_of_block(len(seq.logical_token_blocks) - 1)\n\n # if new_hash is already in the cached table, then free last_block and return the cached version\n if self.gpu_allocator.contains_block(new_hash):\n self.gpu_allocator.free(last_block)\n return self.gpu_allocator.allocate(new_hash)\n else:\n self.gpu_allocator.update_hash(new_hash, last_block)\n return last_block\n\n def _is_last_block_full(\n self,\n seq: Sequence,\n ) -> bool:\n token_ids_len = len(seq.data.get_token_ids())\n return token_ids_len > 0 and token_ids_len % seq.block_size == 0\n\n def _maybe_promote_last_block(\n self,\n seq: Sequence,\n last_block: PhysicalTokenBlock,\n ) -> PhysicalTokenBlock:\n if self._is_last_block_full(seq):\n return self._promote_last_block(seq, last_block)\n else:\n return last_block\n\n def _allocate_last_physical_block(\n self,\n seq: Sequence,\n ) -> PhysicalTokenBlock:\n block_hash: Optional[int] = None\n if (self._is_last_block_full(seq)):\n block_hash = seq.hash_of_block(len(seq.logical_token_blocks) - 1)\n num_hashed_tokens = seq.num_hashed_tokens_of_block(\n len(seq.logical_token_blocks) - 1)\n new_block = self.gpu_allocator.allocate(block_hash, num_hashed_tokens)\n if block_hash is None:\n assert new_block.ref_count == 1\n return new_block\n\n def append_slot(\n self,\n seq: Sequence,\n ) -> Optional[Tuple[int, int]]:\n \"\"\"Allocate a physical slot for a new token.\"\"\"\n logical_blocks = seq.logical_token_blocks\n block_table = self.block_tables[seq.seq_id]\n # If we need to allocate a new physical block\n if len(block_table) < len(logical_blocks):\n # Currently this code only supports adding one physical block\n assert len(block_table) == len(logical_blocks) - 1\n\n if (self.block_sliding_window\n and len(block_table) >= self.block_sliding_window):\n # reuse a block\n block_table.append(block_table[len(block_table) %\n self.block_sliding_window])\n else:\n # The sequence has a new logical block.\n # Allocate a new physical block.\n new_block = self._allocate_last_physical_block(seq)\n block_table.append(new_block)\n return None\n\n # We want to append the token to the last physical block.\n last_block = block_table[-1]\n assert last_block.device == Device.GPU\n if last_block.ref_count == 1:\n # Not shared with other sequences. Appendable.\n # If the last block is now complete, promote it to a full block so that it can be shared\n new_block = self._maybe_promote_last_block(seq, last_block)\n block_table[-1] = new_block\n return None\n else:\n # The last block is shared with other sequences.\n # Copy on Write: Allocate a new block and copy the tokens.\n new_block = self._allocate_last_physical_block(seq)\n\n block_table[-1] = new_block\n self.gpu_allocator.free(last_block)\n return last_block.block_number, new_block.block_number\n\n def fork(self, parent_seq: Sequence, child_seq: Sequence) -> None:\n # NOTE: fork does not allocate a new physical block.\n # Thus, it is always safe from OOM.\n src_block_table = self.block_tables[parent_seq.seq_id]\n self.block_tables[child_seq.seq_id] = src_block_table.copy()\n for block in src_block_table:\n block.ref_count += 1\n\n def _get_physical_blocks(\n self, seq_group: SequenceGroup) -> List[PhysicalTokenBlock]:\n # NOTE: Here, we assume that the physical blocks are only shared by\n # the sequences in the same group.\n blocks: Set[PhysicalTokenBlock] = set()\n for seq in seq_group.get_seqs():\n if seq.is_finished():\n continue\n blocks.update(self.block_tables[seq.seq_id])\n return list(blocks)\n\n def can_swap_in(self, seq_group: SequenceGroup) -> bool:\n blocks = self._get_physical_blocks(seq_group)\n num_swapped_seqs = seq_group.num_seqs(status=SequenceStatus.SWAPPED)\n num_free_blocks = self.gpu_allocator.get_num_free_blocks()\n # NOTE: Conservatively, we assume that every sequence will allocate\n # at least one free block right after the swap-in.\n # NOTE: This should match the logic in can_append_slot().\n num_required_blocks = len(blocks) + num_swapped_seqs\n return num_free_blocks - num_required_blocks >= self.watermark_blocks\n\n def swap_in(self, seq_group: SequenceGroup) -> Dict[int, int]:\n # CPU block -> GPU block.\n mapping: Dict[PhysicalTokenBlock, PhysicalTokenBlock] = {}\n for seq in seq_group.get_seqs(status=SequenceStatus.SWAPPED):\n new_block_table: BlockTable = []\n block_table = self.block_tables[seq.seq_id]\n\n for cpu_block in block_table:\n if cpu_block in mapping:\n gpu_block = mapping[cpu_block]\n gpu_block.ref_count += 1\n else:\n gpu_block = self.gpu_allocator.allocate(\n cpu_block.block_hash, cpu_block.num_hashed_tokens)\n mapping[cpu_block] = gpu_block\n new_block_table.append(gpu_block)\n # Free the CPU block swapped in to GPU.\n self.cpu_allocator.free(cpu_block)\n self.block_tables[seq.seq_id] = new_block_table\n\n block_number_mapping = {\n cpu_block.block_number: gpu_block.block_number\n for cpu_block, gpu_block in mapping.items()\n }\n return block_number_mapping\n\n def can_swap_out(self, seq_group: SequenceGroup) -> bool:\n blocks = self._get_physical_blocks(seq_group)\n return len(blocks) <= self.cpu_allocator.get_num_free_blocks()\n\n def swap_out(self, seq_group: SequenceGroup) -> Dict[int, int]:\n # GPU block -> CPU block.\n mapping: Dict[PhysicalTokenBlock, PhysicalTokenBlock] = {}\n for seq in seq_group.get_seqs(status=SequenceStatus.RUNNING):\n new_block_table: BlockTable = []\n block_table = self.block_tables[seq.seq_id]\n\n for gpu_block in block_table:\n if gpu_block in mapping:\n cpu_block = mapping[gpu_block]\n cpu_block.ref_count += 1\n else:\n cpu_block = self.cpu_allocator.allocate(\n gpu_block.block_hash, gpu_block.num_hashed_tokens)\n mapping[gpu_block] = cpu_block\n new_block_table.append(cpu_block)\n # Free the GPU block swapped out to CPU.\n self.gpu_allocator.free(gpu_block)\n self.block_tables[seq.seq_id] = new_block_table\n\n block_number_mapping = {\n gpu_block.block_number: cpu_block.block_number\n for gpu_block, cpu_block in mapping.items()\n }\n return block_number_mapping\n\n def _free_block_table(self, block_table: BlockTable) -> None:\n for block in set(block_table):\n if block.device == Device.GPU:\n self.gpu_allocator.free(block)\n else:\n self.cpu_allocator.free(block)\n\n def free(self, seq: Sequence) -> None:\n if seq.seq_id not in self.block_tables:\n # Already freed or haven't been scheduled yet.\n return\n block_table = self.block_tables[seq.seq_id]\n self._free_block_table(block_table)\n del self.block_tables[seq.seq_id]\n\n def reset(self) -> None:\n for block_table in self.block_tables.values():\n self._free_block_table(block_table)\n self.block_tables.clear()\n\n def get_block_table(self, seq: Sequence) -> List[int]:\n block_table = self.block_tables[seq.seq_id]\n return [block.block_number for block in block_table]\n\n def get_num_free_gpu_blocks(self) -> int:\n return self.gpu_allocator.get_num_free_blocks()\n\n def get_num_free_cpu_blocks(self) -> int:\n return self.cpu_allocator.get_num_free_blocks()\n\n def access_all_blocks_in_seq(\n self,\n seq: Sequence,\n access_time: float,\n ) -> None:\n block_table = self.block_tables[seq.seq_id]\n for block in block_table:\n block.last_accessed = access_time\n\n def compute_full_blocks_in_seq(self, seq: Sequence):\n if seq.seq_id not in self.block_tables:\n return\n max_full_block = seq.get_len() // self.block_size - 1\n block_table = self.block_tables[seq.seq_id]\n if max_full_block == -1:\n return\n for i in reversed(range(max_full_block)):\n if block_table[i].computed:\n break\n block_table[i].computed = True\n\n def get_all_computed_blocks(self, seq: Sequence) -> List[int]:\n if seq.seq_id not in self.block_tables:\n return []\n block_table = self.block_tables[seq.seq_id]\n # NOTE We exclude the last block to avoid the case where the entire\n # prompt is cached. This would cause erroneous behavior in model\n # runner.\n return [\n b.block_number\n for b in takewhile(lambda b: b.computed, block_table[:-1])\n ]\n\n def get_common_computed_block_ids(self,\n seq_group: SequenceGroup) -> List[int]:\n # Can return non-empty result only with prefix caching enabled.\n if not self.enable_caching:\n return []\n\n ids_list = [\n self.get_all_computed_blocks(seq)\n for seq in iter(seq_group.seqs_dict.values())\n ]\n return commonprefix([ids for ids in ids_list if ids != []])\n\n def mark_blocks_as_computed(self, seq_group: SequenceGroup):\n if self.enable_caching:\n for seq in seq_group.seqs_dict.values():\n self.compute_full_blocks_in_seq(seq)\n", "path": "vllm/core/block_manager.py" }, { "content": "import contextlib\nimport time\nfrom typing import Dict, List, Optional, Tuple, Set, Union\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\n\nfrom vllm.config import (DeviceConfig, ModelConfig, LoRAConfig, ParallelConfig,\n SchedulerConfig)\nfrom vllm.logger import init_logger\nfrom vllm.model_executor import get_model, InputMetadata, SamplingMetadata\nfrom vllm.model_executor.parallel_utils import cupy_utils\nfrom vllm.model_executor.parallel_utils.communication_op import (\n broadcast_tensor_dict)\nfrom vllm.model_executor.parallel_utils.parallel_state import (\n with_cupy_nccl_for_all_reduce)\nfrom vllm.model_executor.parallel_utils import custom_all_reduce\nfrom vllm.sampling_params import SamplingParams, SamplingType\nfrom vllm.sequence import SamplerOutput, SequenceData, SequenceGroupMetadata\nfrom vllm.lora.worker_manager import LRUCacheWorkerLoRAManager\nfrom vllm.lora.layers import LoRAMapping\nfrom vllm.lora.request import LoRARequest\nfrom vllm.utils import in_wsl\n\nlogger = init_logger(__name__)\n\nKVCache = Tuple[torch.Tensor, torch.Tensor]\n_PAD_SLOT_ID = -1\nLORA_WARMUP_RANK = 8\n# Capture graphs for batch size 1, 2, 4, 8, 16, 24, 32, 40, ..., 256.\n# NOTE: _get_graph_batch_size needs to be updated if this list is changed.\n_BATCH_SIZES_TO_CAPTURE = [1, 2, 4] + [8 * i for i in range(1, 33)]\n\n\nclass ModelRunner:\n\n def __init__(\n self,\n model_config: ModelConfig,\n parallel_config: ParallelConfig,\n scheduler_config: SchedulerConfig,\n device_config: DeviceConfig,\n lora_config: Optional[LoRAConfig],\n kv_cache_dtype: Optional[str] = \"auto\",\n is_driver_worker: bool = False,\n ):\n self.model_config = model_config\n self.parallel_config = parallel_config\n self.scheduler_config = scheduler_config\n self.lora_config = lora_config\n self.is_driver_worker = is_driver_worker\n\n # model_config can be None in tests/samplers/test_sampler.py.\n # FIXME(woosuk): This is a hack to make the tests work. Refactor this.\n self.sliding_window = (model_config.get_sliding_window()\n if model_config is not None else None)\n self.device_config = (device_config\n if device_config is not None else DeviceConfig())\n self.device = self.device_config.device\n\n self.model = None\n self.block_size = None # Set after initial profiling.\n self.lora_manager = None\n\n self.graph_runners: Dict[int, CUDAGraphRunner] = {}\n self.graph_memory_pool = None # Set during graph capture.\n\n self.max_context_len_to_capture = (\n self.model_config.max_context_len_to_capture\n if self.model_config is not None else 0)\n # When using CUDA graph, the input block tables must be padded to\n # max_context_len_to_capture. However, creating the block table in\n # Python can be expensive. To optimize this, we cache the block table\n # in numpy and only copy the actual input content at every iteration.\n # The shape of the cached block table will be\n # (max batch size to capture, max context len to capture / block size).\n self.graph_block_tables = None # Set after initial profiling.\n # cache in_wsl result\n self.in_wsl = in_wsl()\n self.kv_cache_dtype = kv_cache_dtype\n\n # Set enforce_eager to True for Neuron backend, to avoid capturing graph\n if self.device_config.is_neuron:\n self.model_config.enforce_eager = True\n\n def load_model(self) -> None:\n self.model = get_model(self.model_config,\n self.device_config,\n lora_config=self.lora_config,\n parallel_config=self.parallel_config,\n scheduler_config=self.scheduler_config)\n\n vocab_size = self.model.config.vocab_size\n\n if self.lora_config:\n assert hasattr(\n self.model, \"supported_lora_modules\"\n ) and self.model.supported_lora_modules, \"Model does not support LoRA\"\n assert hasattr(\n self.model,\n \"embedding_modules\"), \"Model does not have embedding_modules\"\n assert hasattr(self.model, \"embedding_padding_modules\"\n ), \"Model does not have embedding_padding_modules\"\n self.lora_manager = LRUCacheWorkerLoRAManager(\n self.scheduler_config.max_num_seqs,\n self.scheduler_config.max_num_batched_tokens +\n self.scheduler_config.max_paddings, vocab_size,\n self.lora_config, self.device, self.model.embedding_modules,\n self.model.embedding_padding_modules)\n self.model = self.lora_manager.create_lora_manager(self.model)\n\n def set_block_size(self, block_size: int) -> None:\n self.block_size = block_size\n\n max_num_blocks = (self.max_context_len_to_capture + block_size -\n 1) // block_size\n self.graph_block_tables = np.zeros(\n (max(_BATCH_SIZES_TO_CAPTURE), max_num_blocks), dtype=np.int32)\n\n def _prepare_prompt(\n self,\n seq_group_metadata_list: List[SequenceGroupMetadata],\n ) -> Tuple[torch.Tensor, torch.Tensor, InputMetadata, List[int], List[int],\n List[int], List[int], Set[LoRARequest]]:\n assert len(seq_group_metadata_list) > 0\n input_tokens: List[List[int]] = []\n input_positions: List[List[int]] = []\n slot_mapping: List[List[int]] = []\n lora_index_mapping: List[int] = []\n lora_prompt_mapping: List[int] = []\n lora_requests: Set[LoRARequest] = set()\n\n prompt_lens: List[int] = []\n context_lens: List[int] = []\n subquery_lens: List[int] = []\n prefix_block_tables: List[List[int]] = []\n for seq_group_metadata in seq_group_metadata_list:\n assert seq_group_metadata.is_prompt\n seq_ids = list(seq_group_metadata.seq_data.keys())\n assert len(seq_ids) == 1\n seq_id = seq_ids[0]\n\n seq_data = seq_group_metadata.seq_data[seq_id]\n prompt_tokens = seq_data.get_token_ids()\n prompt_len = len(prompt_tokens)\n prompt_lens.append(prompt_len)\n computed_len = 0\n\n # NOTE: This only works for oooooooxxx style attention.\n computed_block_nums = seq_group_metadata.computed_block_nums\n if computed_block_nums is not None and len(\n computed_block_nums) > 0 and self.sliding_window is None:\n # Prefix is not supported with sliding_window\n computed_len = len(computed_block_nums) * self.block_size\n prompt_tokens = prompt_tokens[computed_len:]\n prefix_block_tables.append(computed_block_nums)\n else:\n prefix_block_tables.append([])\n # actual prompt lens\n context_lens.append(computed_len)\n subquery_lens.append(prompt_len - computed_len)\n\n input_tokens.append(prompt_tokens)\n # NOTE(woosuk): Here we assume that the first token in the prompt\n # is always the first token in the sequence.\n input_positions.append(\n list(range(computed_len, computed_len + len(prompt_tokens))))\n\n lora_id = seq_group_metadata.lora_int_id\n\n if lora_id > 0:\n lora_requests.add(seq_group_metadata.lora_request)\n\n lora_index_mapping.append([lora_id] * (prompt_len - computed_len))\n lora_prompt_mapping.extend(\n [lora_id] *\n (prompt_len - computed_len\n if seq_group_metadata.sampling_params.prompt_logprobs else 1))\n\n if seq_group_metadata.block_tables is None:\n # During memory profiling, the block tables are not initialized\n # yet. In this case, we just use a dummy slot mapping.\n slot_mapping.append([_PAD_SLOT_ID] * prompt_len)\n continue\n\n # Compute the slot mapping.\n slot_mapping.append([])\n block_table = seq_group_metadata.block_tables[seq_id]\n # Mask the [0, start_idx) tokens of the prompt with _PAD_SLOT_ID,\n # where start_idx is max(0, prompt_len - sliding_window).\n # For example, if the prompt len is 10, sliding window is 8, and\n # block size is 4, the first two tokens are masked and the slot\n # mapping will be [-1, -1, 2, 3, 4, 5, 6, 7, 0, 1].\n start_idx = 0\n if self.sliding_window is not None:\n assert computed_len == 0, (\n \"Prefix caching is currently not supported with \"\n \"sliding window attention\")\n start_idx = max(0, prompt_len - self.sliding_window)\n for i in range(computed_len, prompt_len):\n if i < start_idx:\n slot_mapping[-1].append(_PAD_SLOT_ID)\n continue\n\n block_number = block_table[i // self.block_size]\n block_offset = i % self.block_size\n slot = block_number * self.block_size + block_offset\n slot_mapping[-1].append(slot)\n\n max_prompt_len = max(subquery_lens)\n assert max_prompt_len > 0\n input_tokens = _make_tensor_with_pad(input_tokens,\n max_prompt_len,\n pad=0,\n dtype=torch.long,\n device=self.device)\n input_positions = _make_tensor_with_pad(input_positions,\n max_prompt_len,\n pad=0,\n dtype=torch.long,\n device=self.device)\n slot_mapping = _make_tensor_with_pad(slot_mapping,\n max_prompt_len,\n pad=_PAD_SLOT_ID,\n dtype=torch.long,\n device=self.device)\n lora_index_mapping = [\n _pad_to_max(mapping, max_prompt_len, pad=0)\n for mapping in lora_index_mapping\n ]\n context_lens_tensor = torch.tensor(context_lens,\n dtype=torch.int,\n device=self.device)\n # Prepare prefix block tables\n max_prompt_block_table_len = max(len(t) for t in prefix_block_tables)\n block_tables = _make_tensor_with_pad(\n prefix_block_tables,\n max_len=max_prompt_block_table_len,\n pad=0,\n dtype=torch.int,\n device=self.device,\n )\n start_loc_tensor = torch.arange(0,\n len(prompt_lens) * max_prompt_len,\n max_prompt_len,\n dtype=torch.long,\n device=self.device)\n prompt_lens_tensor = torch.tensor(prompt_lens,\n dtype=torch.long,\n device=self.device)\n\n input_metadata = InputMetadata(\n is_prompt=True,\n slot_mapping=slot_mapping,\n prompt_lens=prompt_lens_tensor,\n max_seq_len=max_prompt_len,\n start_loc=start_loc_tensor,\n max_context_len=None,\n context_lens=context_lens_tensor,\n block_tables=block_tables,\n use_cuda_graph=False,\n kv_cache_dtype=self.kv_cache_dtype,\n )\n return (input_tokens, input_positions, input_metadata, prompt_lens,\n subquery_lens, lora_index_mapping, lora_prompt_mapping,\n lora_requests)\n\n def _prepare_decode(\n self,\n seq_group_metadata_list: List[SequenceGroupMetadata],\n ) -> Tuple[torch.Tensor, torch.Tensor, InputMetadata, List[int], List[int],\n Set[LoRARequest]]:\n assert len(seq_group_metadata_list) > 0\n input_tokens: List[List[int]] = []\n input_positions: List[List[int]] = []\n slot_mapping: List[List[int]] = []\n context_lens: List[int] = []\n block_tables: List[List[int]] = []\n lora_index_mapping: List[int] = []\n lora_prompt_mapping: List[int] = []\n lora_requests: Set[LoRARequest] = set()\n\n for seq_group_metadata in seq_group_metadata_list:\n assert not seq_group_metadata.is_prompt\n\n seq_ids = list(seq_group_metadata.seq_data.keys())\n lora_id = seq_group_metadata.lora_int_id\n\n if lora_id > 0:\n lora_requests.add(seq_group_metadata.lora_request)\n\n for seq_id in seq_ids:\n seq_data = seq_group_metadata.seq_data[seq_id]\n generation_token = seq_data.get_last_token_id()\n input_tokens.append([generation_token])\n\n seq_len = seq_data.get_len()\n position = seq_len - 1\n input_positions.append([position])\n\n context_len = seq_len if self.sliding_window is None else min(\n seq_len, self.sliding_window)\n context_lens.append(context_len)\n\n block_table = seq_group_metadata.block_tables[seq_id]\n block_number = block_table[position // self.block_size]\n block_offset = position % self.block_size\n slot = block_number * self.block_size + block_offset\n slot_mapping.append([slot])\n lora_index_mapping.append([lora_id])\n lora_prompt_mapping.append(lora_id)\n\n if self.sliding_window is not None:\n sliding_window_blocks = (self.sliding_window //\n self.block_size)\n block_table = block_table[-sliding_window_blocks:]\n block_tables.append(block_table)\n\n batch_size = len(input_tokens)\n max_context_len = max(context_lens)\n use_captured_graph = (\n not self.model_config.enforce_eager\n and batch_size <= _BATCH_SIZES_TO_CAPTURE[-1]\n and max_context_len <= self.max_context_len_to_capture)\n if use_captured_graph:\n # Pad the input tokens, positions, and slot mapping to match the\n # batch size of the captured graph.\n graph_batch_size = _get_graph_batch_size(batch_size)\n assert graph_batch_size >= batch_size\n for _ in range(graph_batch_size - batch_size):\n input_tokens.append([])\n input_positions.append([])\n slot_mapping.append([])\n context_lens.append(1)\n block_tables.append([])\n batch_size = graph_batch_size\n\n input_tokens = _make_tensor_with_pad(input_tokens,\n max_len=1,\n pad=0,\n dtype=torch.long,\n device=self.device)\n input_positions = _make_tensor_with_pad(input_positions,\n max_len=1,\n pad=0,\n dtype=torch.long,\n device=self.device)\n slot_mapping = _make_tensor_with_pad(slot_mapping,\n max_len=1,\n pad=_PAD_SLOT_ID,\n dtype=torch.long,\n device=self.device)\n context_lens = torch.tensor(context_lens,\n dtype=torch.int,\n device=self.device)\n\n if use_captured_graph:\n # The shape of graph_block_tables is\n # [max batch size, max context len // block size].\n input_block_tables = self.graph_block_tables[:batch_size]\n for i, block_table in enumerate(block_tables):\n if block_table:\n input_block_tables[i, :len(block_table)] = block_table\n block_tables = torch.tensor(input_block_tables, device=self.device)\n else:\n max_block_table_len = max(\n len(block_table) for block_table in block_tables)\n block_tables = _make_tensor_with_pad(\n block_tables,\n max_len=max_block_table_len,\n pad=0,\n dtype=torch.int,\n device=self.device,\n )\n\n lora_index_mapping = [\n _pad_to_max(mapping, 1, pad=0) for mapping in lora_index_mapping\n ]\n\n input_metadata = InputMetadata(\n is_prompt=False,\n slot_mapping=slot_mapping,\n prompt_lens=None,\n max_seq_len=None,\n start_loc=None,\n max_context_len=max_context_len,\n context_lens=context_lens,\n block_tables=block_tables,\n use_cuda_graph=use_captured_graph,\n kv_cache_dtype=self.kv_cache_dtype,\n )\n return (input_tokens, input_positions, input_metadata,\n lora_index_mapping, lora_prompt_mapping, lora_requests)\n\n def _prepare_sample(\n self,\n seq_group_metadata_list: List[SequenceGroupMetadata],\n prompt_lens: List[int],\n subquery_lens: Optional[List[int]],\n ) -> SamplingMetadata:\n seq_groups: List[Tuple[List[int], SamplingParams]] = []\n selected_token_indices: List[int] = []\n generators: List[torch.Generator] = []\n selected_token_start_idx = 0\n categorized_sample_indices = {t: [] for t in SamplingType}\n categorized_sample_indices_start_idx = 0\n pin_memory = not self.in_wsl and not self.device_config.is_neuron\n\n max_subquery_len = max(subquery_lens) if subquery_lens else 1\n for i, seq_group_metadata in enumerate(seq_group_metadata_list):\n seq_ids = list(seq_group_metadata.seq_data.keys())\n sampling_params = seq_group_metadata.sampling_params\n seq_groups.append((seq_ids, sampling_params))\n\n if seq_group_metadata.is_prompt:\n assert len(seq_ids) == 1\n assert subquery_lens is not None\n subquery_len = subquery_lens[i]\n if sampling_params.prompt_logprobs is not None:\n # NOTE: prompt token positions do not need sample, skip\n categorized_sample_indices_start_idx += subquery_len - 1\n\n categorized_sample_indices[\n sampling_params.sampling_type].append(\n categorized_sample_indices_start_idx)\n categorized_sample_indices_start_idx += 1\n\n if sampling_params.prompt_logprobs is not None:\n selected_token_indices.extend(\n range(selected_token_start_idx,\n selected_token_start_idx + subquery_len - 1))\n selected_token_indices.append(selected_token_start_idx +\n subquery_len - 1)\n selected_token_start_idx += max_subquery_len\n\n if sampling_params.seed is not None:\n seq_group_metadata.state.generator = torch.Generator(\n device=\"cuda\").manual_seed(sampling_params.seed)\n else:\n num_seqs = len(seq_ids)\n selected_token_indices.extend(\n range(selected_token_start_idx,\n selected_token_start_idx + num_seqs))\n selected_token_start_idx += num_seqs\n\n categorized_sample_indices[\n sampling_params.sampling_type].extend(\n range(categorized_sample_indices_start_idx,\n categorized_sample_indices_start_idx + num_seqs))\n categorized_sample_indices_start_idx += num_seqs\n\n if sampling_params.seed is not None:\n generators.append(seq_group_metadata.state.generator)\n\n selected_token_indices = _async_h2d(selected_token_indices,\n dtype=torch.long,\n target_device=self.device,\n pin_memory=pin_memory)\n categorized_sample_indices = {\n t: _async_h2d(seq_ids,\n dtype=torch.int,\n target_device=self.device,\n pin_memory=pin_memory)\n for t, seq_ids in categorized_sample_indices.items()\n }\n\n seq_data: Dict[int, SequenceData] = {}\n for seq_group_metadata in seq_group_metadata_list:\n seq_data.update(seq_group_metadata.seq_data)\n\n sampling_metadata = SamplingMetadata(\n seq_groups=seq_groups,\n seq_data=seq_data,\n prompt_lens=prompt_lens,\n selected_token_indices=selected_token_indices,\n categorized_sample_indices=categorized_sample_indices,\n generators=generators,\n )\n return sampling_metadata\n\n def prepare_input_tensors(\n self,\n seq_group_metadata_list: Optional[List[SequenceGroupMetadata]],\n ) -> Tuple[torch.Tensor, torch.Tensor, InputMetadata, SamplingMetadata,\n Set[int], LoRAMapping]:\n if self.is_driver_worker:\n # NOTE: We assume that all sequences in the group are all prompts or\n # all decodes.\n is_prompt = seq_group_metadata_list[0].is_prompt\n # Prepare input tensors.\n if is_prompt:\n (input_tokens, input_positions, input_metadata, prompt_lens,\n subquery_lens, lora_index_mapping, lora_prompt_mapping,\n lora_requests) = self._prepare_prompt(seq_group_metadata_list)\n else:\n (input_tokens, input_positions, input_metadata,\n lora_index_mapping, lora_prompt_mapping,\n lora_requests) = self._prepare_decode(seq_group_metadata_list)\n prompt_lens = []\n subquery_lens = None\n sampling_metadata = self._prepare_sample(seq_group_metadata_list,\n prompt_lens,\n subquery_lens)\n\n if self.lora_config:\n flat_lora_index_mapping = [\n item for sublist in lora_index_mapping for item in sublist\n ]\n lora_mapping = LoRAMapping(\n flat_lora_index_mapping,\n lora_prompt_mapping,\n )\n else:\n lora_mapping = None\n\n # Broadcast the metadata.\n metadata_dict = {\n \"input_tokens\": input_tokens,\n \"input_positions\": input_positions,\n \"is_prompt\": input_metadata.is_prompt,\n \"slot_mapping\": input_metadata.slot_mapping,\n \"prompt_lens\": input_metadata.prompt_lens,\n \"max_seq_len\": input_metadata.max_seq_len,\n \"start_loc\": input_metadata.start_loc,\n \"max_context_len\": input_metadata.max_context_len,\n \"context_lens\": input_metadata.context_lens,\n \"block_tables\": input_metadata.block_tables,\n \"use_cuda_graph\": input_metadata.use_cuda_graph,\n \"kv_cache_dtype\": input_metadata.kv_cache_dtype,\n \"selected_token_indices\":\n sampling_metadata.selected_token_indices,\n \"lora_requests\": lora_requests,\n \"lora_mapping\": lora_mapping,\n }\n broadcast_tensor_dict(metadata_dict, src=0)\n else:\n metadata_dict = broadcast_tensor_dict(src=0)\n input_tokens = metadata_dict[\"input_tokens\"]\n input_positions = metadata_dict[\"input_positions\"]\n lora_mapping = metadata_dict[\"lora_mapping\"]\n lora_requests = metadata_dict[\"lora_requests\"]\n input_metadata = InputMetadata(\n is_prompt=metadata_dict[\"is_prompt\"],\n slot_mapping=metadata_dict[\"slot_mapping\"],\n prompt_lens=metadata_dict[\"prompt_lens\"],\n max_seq_len=metadata_dict[\"max_seq_len\"],\n start_loc=metadata_dict[\"start_loc\"],\n max_context_len=metadata_dict[\"max_context_len\"],\n context_lens=metadata_dict[\"context_lens\"],\n block_tables=metadata_dict[\"block_tables\"],\n use_cuda_graph=metadata_dict[\"use_cuda_graph\"],\n kv_cache_dtype=metadata_dict[\"kv_cache_dtype\"],\n )\n sampling_metadata = SamplingMetadata(\n seq_groups=None,\n seq_data=None,\n prompt_lens=None,\n selected_token_indices=metadata_dict[\"selected_token_indices\"],\n categorized_sample_indices=None,\n generators=None,\n perform_sampling=False,\n )\n\n return (input_tokens, input_positions, input_metadata,\n sampling_metadata, lora_requests, lora_mapping)\n\n @torch.inference_mode()\n def execute_model(\n self,\n seq_group_metadata_list: Optional[List[SequenceGroupMetadata]],\n kv_caches: List[Tuple[torch.Tensor, torch.Tensor]],\n ) -> Optional[SamplerOutput]:\n (input_tokens, input_positions, input_metadata, sampling_metadata,\n lora_requests,\n lora_mapping) = self.prepare_input_tensors(seq_group_metadata_list)\n\n if self.lora_config:\n self.set_active_loras(lora_requests, lora_mapping)\n\n # Execute the model.\n if input_metadata.use_cuda_graph:\n graph_batch_size = input_tokens.shape[0]\n model_executable = self.graph_runners[graph_batch_size]\n else:\n model_executable = self.model\n hidden_states = model_executable(\n input_ids=input_tokens,\n positions=input_positions,\n kv_caches=kv_caches,\n input_metadata=input_metadata,\n )\n\n # Sample the next token.\n output = self.model.sample(\n hidden_states=hidden_states,\n sampling_metadata=sampling_metadata,\n )\n return output\n\n @torch.inference_mode()\n def profile_run(self) -> None:\n # Enable top-k sampling to reflect the accurate memory usage.\n vocab_size = self.model_config.get_vocab_size()\n sampling_params = SamplingParams(top_p=0.99, top_k=vocab_size - 1)\n max_num_batched_tokens = self.scheduler_config.max_num_batched_tokens\n max_num_seqs = self.scheduler_config.max_num_seqs\n\n # This represents the maximum number of different requests\n # that will have unique loras, an therefore the max amount of memory\n # consumption create dummy lora request copies from the lora request\n # passed in, which contains a lora from the lora warmup path.\n dummy_lora_requests = []\n dummy_lora_requests_per_seq = []\n if self.lora_config:\n for idx in range(self.lora_config.max_loras):\n lora_id = idx + 1\n dummy_lora_request = LoRARequest(\n lora_name=f\"warmup_{lora_id}\",\n lora_int_id=lora_id,\n lora_local_path=\"/not/a/real/path\",\n )\n self.lora_manager.add_dummy_lora(dummy_lora_request,\n rank=LORA_WARMUP_RANK)\n dummy_lora_requests.append(dummy_lora_request)\n dummy_lora_requests_per_seq = [\n dummy_lora_requests[idx % len(dummy_lora_requests)]\n for idx in range(max_num_seqs)\n ]\n\n # Profile memory usage with max_num_sequences sequences and the total\n # number of tokens equal to max_num_batched_tokens.\n seqs: List[SequenceGroupMetadata] = []\n for group_id in range(max_num_seqs):\n seq_len = (max_num_batched_tokens // max_num_seqs +\n (group_id < max_num_batched_tokens % max_num_seqs))\n seq_data = SequenceData([0] * seq_len)\n seq = SequenceGroupMetadata(\n request_id=str(group_id),\n is_prompt=True,\n seq_data={group_id: seq_data},\n sampling_params=sampling_params,\n block_tables=None,\n lora_request=dummy_lora_requests_per_seq[group_id]\n if dummy_lora_requests_per_seq else None,\n )\n seqs.append(seq)\n\n # Run the model with the dummy inputs.\n num_layers = self.model_config.get_num_layers(self.parallel_config)\n kv_caches = [(None, None)] * num_layers\n self.execute_model(seqs, kv_caches)\n torch.cuda.synchronize()\n return\n\n def remove_all_loras(self) -> bool:\n if not self.lora_manager:\n raise RuntimeError(\"LoRA is not enabled.\")\n return self.lora_manager.remove_all_loras()\n\n def set_active_loras(self, lora_requests: List[LoRARequest],\n lora_mapping: LoRAMapping) -> None:\n if not self.lora_manager:\n raise RuntimeError(\"LoRA is not enabled.\")\n self.lora_manager.set_active_loras(lora_requests, lora_mapping)\n\n def add_lora(self, lora_request: LoRARequest) -> bool:\n if not self.lora_manager:\n raise RuntimeError(\"LoRA is not enabled.\")\n return self.lora_manager.add_lora(lora_request)\n\n def remove_lora(self, lora_id: int) -> bool:\n if not self.lora_manager:\n raise RuntimeError(\"LoRA is not enabled.\")\n return self.lora_manager.remove_lora(lora_id)\n\n def list_loras(self) -> Set[int]:\n if not self.lora_manager:\n raise RuntimeError(\"LoRA is not enabled.\")\n return self.lora_manager.list_loras()\n\n @torch.inference_mode()\n def capture_model(self, kv_caches: List[KVCache]) -> None:\n # NOTE(woosuk): This is a hack to ensure that the NCCL backend is never\n # deleted before the CUDA graphs.\n self.cupy_nccl_backend = cupy_utils.get_nccl_backend()\n\n assert not self.model_config.enforce_eager\n logger.info(\"Capturing the model for CUDA graphs. This may lead to \"\n \"unexpected consequences if the model is not static. To \"\n \"run the model in eager mode, set 'enforce_eager=True' or \"\n \"use '--enforce-eager' in the CLI.\")\n logger.info(\"CUDA graphs can take additional 1~3 GiB memory per GPU. \"\n \"If you are running out of memory, consider decreasing \"\n \"`gpu_memory_utilization` or enforcing eager mode. \"\n \"You can also reduce the `max_num_seqs` as needed \"\n \"to decrease memory usage.\")\n start_time = time.perf_counter()\n\n # Prepare dummy inputs. These will be reused for all batch sizes.\n max_batch_size = max(_BATCH_SIZES_TO_CAPTURE)\n input_tokens = torch.zeros(max_batch_size, 1, dtype=torch.long).cuda()\n input_positions = torch.zeros(max_batch_size, 1,\n dtype=torch.long).cuda()\n slot_mapping = torch.empty(max_batch_size, 1, dtype=torch.long).cuda()\n slot_mapping.fill_(_PAD_SLOT_ID)\n context_lens = torch.ones(max_batch_size, dtype=torch.int32).cuda()\n block_tables = torch.from_numpy(self.graph_block_tables).cuda()\n\n graph_batch_size = _get_graph_batch_size(\n self.scheduler_config.max_num_seqs)\n batch_size_capture_list = [\n bs for bs in _BATCH_SIZES_TO_CAPTURE if bs <= graph_batch_size\n ]\n\n # NOTE(woosuk): There are 3 backends for all-reduce: custom all-reduce\n # kernel, CuPy NCCL, and PyTorch NCCL. When using CUDA graph, we use\n # either custom all-reduce kernel or CuPy NCCL. When not using CUDA\n # graph, we use either custom all-reduce kernel or PyTorch NCCL.\n # We always prioritize using custom all-reduce kernel but fall back\n # to PyTorch or CuPy NCCL if it is disabled or not supported.\n with custom_all_reduce.capture():\n # NOTE: Capturing the largest batch size first may help reduce the\n # memory usage of CUDA graph.\n for batch_size in reversed(batch_size_capture_list):\n # Create dummy input_metadata.\n input_metadata = InputMetadata(\n is_prompt=False,\n slot_mapping=slot_mapping[:batch_size],\n prompt_lens=None,\n max_seq_len=None,\n start_loc=None,\n max_context_len=self.max_context_len_to_capture,\n context_lens=context_lens[:batch_size],\n block_tables=block_tables[:batch_size],\n use_cuda_graph=True,\n kv_cache_dtype=self.kv_cache_dtype,\n )\n\n if self.lora_config:\n lora_mapping = LoRAMapping(\n [0] * batch_size,\n [0] * batch_size,\n )\n self.set_active_loras(set(), lora_mapping)\n\n graph_runner = CUDAGraphRunner(self.model)\n graph_runner.capture(\n input_tokens[:batch_size],\n input_positions[:batch_size],\n kv_caches,\n input_metadata,\n memory_pool=self.graph_memory_pool,\n )\n self.graph_memory_pool = graph_runner.graph.pool()\n self.graph_runners[batch_size] = graph_runner\n\n end_time = time.perf_counter()\n elapsed_time = end_time - start_time\n # This usually takes < 10 seconds.\n logger.info(f\"Graph capturing finished in {elapsed_time:.0f} secs.\")\n\n def __del__(self) -> None:\n # Delete the CUDA graphs before deleting the CuPy NCCL communicator.\n # NOTE(woosuk): This is necessary because otherwise deadlocks can\n # happen.\n # FIXME(woosuk): This is a bit hacky. Find a more robust solution.\n self.graph_runners.clear()\n self.cupy_nccl_backend = None\n\n\nclass CUDAGraphRunner:\n\n def __init__(self, model: nn.Module):\n self.model = model\n self.graph = None\n self.input_buffers: Dict[str, torch.Tensor] = {}\n self.output_buffers: Dict[str, torch.Tensor] = {}\n\n def capture(\n self,\n input_ids: torch.Tensor,\n positions: torch.Tensor,\n kv_caches: List[KVCache],\n input_metadata: InputMetadata,\n memory_pool,\n ) -> None:\n assert self.graph is None\n # Run the model once without capturing the graph.\n # This is to make sure that the captured graph does not include the\n # kernel launches for initial benchmarking (e.g., Triton autotune).\n with _maybe_cupy_nccl():\n self.model(\n input_ids,\n positions,\n kv_caches,\n input_metadata,\n )\n torch.cuda.synchronize()\n\n # Capture the graph.\n # NOTE(woosuk): Python 3.8 does not support multi-line with statements.\n # https://stackoverflow.com/questions/31039022/python-multi-line-with-statement\n self.graph = torch.cuda.CUDAGraph()\n with torch.cuda.graph(self.graph, pool=memory_pool): # noqa: SIM117\n with _maybe_cupy_nccl():\n hidden_states = self.model(\n input_ids,\n positions,\n kv_caches,\n input_metadata,\n )\n torch.cuda.synchronize()\n\n # Save the input and output buffers.\n self.input_buffers = {\n \"input_ids\": input_ids,\n \"positions\": positions,\n \"kv_caches\": kv_caches,\n \"slot_mapping\": input_metadata.slot_mapping,\n \"context_lens\": input_metadata.context_lens,\n \"block_tables\": input_metadata.block_tables,\n }\n self.output_buffers = {\"hidden_states\": hidden_states}\n return\n\n def forward(\n self,\n input_ids: torch.Tensor,\n positions: torch.Tensor,\n kv_caches: List[Tuple[torch.Tensor, torch.Tensor]],\n input_metadata: InputMetadata,\n ) -> torch.Tensor:\n # KV caches are fixed tensors, so we don't need to copy them.\n del kv_caches\n\n # Copy the input tensors to the input buffers.\n self.input_buffers[\"input_ids\"].copy_(input_ids, non_blocking=True)\n self.input_buffers[\"positions\"].copy_(positions, non_blocking=True)\n self.input_buffers[\"slot_mapping\"].copy_(input_metadata.slot_mapping,\n non_blocking=True)\n self.input_buffers[\"context_lens\"].copy_(input_metadata.context_lens,\n non_blocking=True)\n self.input_buffers[\"block_tables\"].copy_(input_metadata.block_tables,\n non_blocking=True)\n\n # Run the graph.\n self.graph.replay()\n\n # Return the output tensor.\n return self.output_buffers[\"hidden_states\"]\n\n def __call__(self, *args, **kwargs):\n return self.forward(*args, **kwargs)\n\n\[email protected]\ndef _maybe_cupy_nccl():\n if cupy_utils.is_initialized() and not custom_all_reduce.is_initialized():\n with with_cupy_nccl_for_all_reduce():\n yield\n else:\n yield\n\n\ndef _pad_to_max(x: List[int], max_len: int, pad: int) -> List[int]:\n assert len(x) <= max_len\n return x + [pad] * (max_len - len(x))\n\n\ndef _make_tensor_with_pad(\n x: List[List[int]],\n max_len: int,\n pad: int,\n dtype: torch.dtype,\n device: Optional[Union[str, torch.device]],\n) -> torch.Tensor:\n padded_x = [_pad_to_max(x_i, max_len, pad) for x_i in x]\n return torch.tensor(padded_x, dtype=dtype, device=device)\n\n\ndef _get_graph_batch_size(batch_size: int) -> int:\n if batch_size <= 2:\n return batch_size\n elif batch_size <= 4:\n return 4\n else:\n return (batch_size + 7) // 8 * 8\n\n\ndef _async_h2d(\n data: list,\n dtype: torch.dtype,\n target_device: Union[str, torch.device],\n pin_memory: bool,\n) -> torch.Tensor:\n t = torch.tensor(data, dtype=dtype, pin_memory=pin_memory, device=\"cpu\")\n return t.to(device=target_device, non_blocking=True)\n", "path": "vllm/worker/model_runner.py" } ]
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 + + [email protected]("model", ["facebook/opt-125m"]) [email protected]("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 PreTrainedTokenizerBase\n\nfrom vllm.entrypoints.openai.protocol import (ChatCompletionRequest,\n CompletionRequest)\nfrom vllm.model_executor.guided_decoding.outlines_logits_processors import (\n CFGLogitsProcessor, JSONLogitsProcessor, RegexLogitsProcessor)\n\n\nclass GuidedDecodingMode(Enum):\n JSON = \"json\"\n REGEX = \"regex\"\n CHOICE = \"choice\"\n GRAMMAR = \"grammar\"\n\n\n# https://github.com/outlines-dev/outlines/blob/main/outlines/grammars/json.lark\n# the main difference is that we changed the start: value to\n# start: object | array, so we are denying scalar values as the root of the\n# JSON. Starting with scalars as the root seems to cause llama to generate\n# without stop.\nJSON_GRAMMAR = r\"\"\"\n?start: object | array\n\n?value: object\n| array\n| UNESCAPED_STRING\n| SIGNED_NUMBER -> number\n| \"true\" -> true\n| \"false\" -> false\n| \"null\" -> null\n\narray : \"[\" [value (\",\" value)*] \"]\"\nobject : \"{\" [pair (\",\" pair)*] \"}\"\npair : UNESCAPED_STRING \":\" value\n\n%import common.UNESCAPED_STRING\n%import common.SIGNED_NUMBER\n%import common.WS\n\n%ignore WS\n\"\"\"\n\nglobal_thread_pool = None # used for generating logits processor fsm\n\n\nasync def get_outlines_guided_decoding_logits_processor(\n request: Union[CompletionRequest, ChatCompletionRequest],\n tokenizer) -> Union[JSONLogitsProcessor, RegexLogitsProcessor, None]:\n \"\"\"\n Given an OpenAI-compatible request, check for guided decoding parameters\n and get the necessary logits processor for the given guide.\n We cache logit processors by (guide, tokenizer), and on cache hit\n we make a shallow copy to reuse the same underlying FSM.\n \"\"\"\n global global_thread_pool\n guide, mode = _get_guide_and_mode(request)\n if not guide:\n return None\n\n if global_thread_pool is None:\n global_thread_pool = concurrent.futures.ThreadPoolExecutor(\n max_workers=2)\n loop = asyncio.get_running_loop()\n\n result = await loop.run_in_executor(global_thread_pool,\n _get_cached_logits_processor, guide,\n tokenizer, mode,\n request.guided_whitespace_pattern)\n\n logits_processor = copy(result)\n # reset logits processor's internal state\n logits_processor.init_state()\n return logits_processor\n\n\ndef _get_guide_and_mode(\n request: Union[CompletionRequest, ChatCompletionRequest]\n) -> Union[Tuple[str, GuidedDecodingMode], Tuple[None, None]]:\n\n if request.guided_json:\n json = request.guided_json\n if isinstance(json, dict):\n # turn dict into hashable string\n json = json_dumps(json)\n elif isinstance(json, BaseModel):\n # use pydantic signature so that different model classes\n # with the same fields will get hashed the same\n json = str(json.__signature__)\n return json, GuidedDecodingMode.JSON\n elif request.guided_regex:\n return request.guided_regex, GuidedDecodingMode.REGEX\n elif request.guided_choice:\n # choice just uses regex\n choices = [\n regex_escape(str(choice)) for choice in request.guided_choice\n ]\n choices_regex = \"(\" + \"|\".join(choices) + \")\"\n return choices_regex, GuidedDecodingMode.CHOICE\n elif request.guided_grammar:\n return request.guided_grammar, GuidedDecodingMode.GRAMMAR\n elif (request.response_format is not None\n and request.response_format.type == \"json_object\"):\n return JSON_GRAMMAR, GuidedDecodingMode.GRAMMAR\n else:\n return None, None\n\n\n@lru_cache(maxsize=32)\ndef _get_cached_logits_processor(guide: str,\n tokenizer: PreTrainedTokenizerBase,\n mode: GuidedDecodingMode,\n whitespace_pattern: Union[str, None]):\n if mode == GuidedDecodingMode.JSON:\n return JSONLogitsProcessor(guide, tokenizer, whitespace_pattern)\n elif mode == GuidedDecodingMode.REGEX or mode == GuidedDecodingMode.CHOICE:\n return RegexLogitsProcessor(guide, tokenizer)\n elif mode == GuidedDecodingMode.GRAMMAR:\n return CFGLogitsProcessor(guide, tokenizer)\n else:\n raise ValueError(f\"Unknown guided decoding mode {mode}\")\n", "path": "vllm/model_executor/guided_decoding/outlines_decoding.py" }, { "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 obtain a copy of the License at\n\n# http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport copy\nimport json\nimport math\nfrom collections import defaultdict\nfrom functools import lru_cache\nfrom typing import Callable, DefaultDict, Dict, List, Union\n\nimport torch\nfrom outlines.fsm.fsm import CFGFSM, FSM, RegexFSM\nfrom outlines.fsm.json_schema import build_regex_from_schema\nfrom pydantic import BaseModel\nfrom transformers import PreTrainedTokenizerBase\n\n\nclass BaseLogitsProcessor:\n\n def __init__(self):\n # Child class should use initialize in their init.\n self.fsm: FSM\n\n def init_state(self):\n \"\"\"Initialize the FSM states.\"\"\"\n self.fsm_state: DefaultDict[int, int] = defaultdict(int)\n\n def __call__(self, input_ids: List[int],\n scores: torch.Tensor) -> torch.Tensor:\n \"\"\"Use the FSM to bias the logits before sampling the next token.\"\"\"\n seq_id = hash(tuple(input_ids))\n\n if len(input_ids) == 0:\n self.init_state()\n else:\n last_token = input_ids[-1]\n last_seq_id = hash(tuple(input_ids[:-1]))\n self.fsm_state[seq_id] = self.fsm.next_state(\n self.fsm_state[last_seq_id], last_token)\n\n allowed_tokens = self.fsm.allowed_token_ids(self.fsm_state[seq_id])\n\n mask = torch.full((scores.shape[-1], ),\n -math.inf,\n device=scores.device)\n mask[allowed_tokens] = 0\n scores.add_(mask)\n return scores\n\n\nclass RegexLogitsProcessor(BaseLogitsProcessor):\n\n def __init__(self, regex_string: str, tokenizer: PreTrainedTokenizerBase):\n \"\"\"Compile the FSM that drives the regex-structured generation.\n\n Parameters\n ----------\n regex_string\n A string that represents a regular expression\n tokenizer\n The model's tokenizer\n\n \"\"\"\n tokenizer = _adapt_tokenizer(tokenizer)\n fsm = RegexFSM(regex_string, tokenizer)\n self.fsm = fsm\n\n\nclass JSONLogitsProcessor(RegexLogitsProcessor):\n\n def __init__(self, schema: Union[str, Dict, BaseModel],\n tokenizer: PreTrainedTokenizerBase,\n whitespace_pattern: Union[str, None]):\n \"\"\"Compile the FSM that drives the JSON-guided generation.\n\n Parameters\n ----------\n schema\n A JSON schema that encodes the structure we want the model to\n generate\n tokenizer\n The model's tokenizer\n whitespace_pattern\n Pattern to use for JSON syntactic whitespace (doesn't impact\n string literals)\n Example: allow only a single space or newline with\n `whitespace_pattern=r\"[\\n ]?\"`\n \"\"\"\n if isinstance(schema, type(BaseModel)):\n schema_str = json.dumps(schema.model_json_schema())\n elif isinstance(schema, Dict):\n schema_str = json.dumps(schema)\n elif isinstance(schema, str):\n schema_str = schema\n else:\n raise ValueError(\n f\"Cannot parse schema {schema}. The schema must be either \"\n f\"a Pydantic object, a dictionary or a string that contains \"\n f\"the JSON Schema specification\")\n regex_string = build_regex_from_schema(schema_str, whitespace_pattern)\n super().__init__(regex_string, tokenizer)\n\n\nclass CFGLogitsProcessor(BaseLogitsProcessor):\n\n def __init__(self, cfg: str, tokenizer: PreTrainedTokenizerBase):\n \"\"\"Compile the FSM that drives the context free grammar generation.\n\n Parameters\n ----------\n cfg\n A string that represents a context-free grammar\n tokenizer\n The model's tokenizer\n\n \"\"\"\n tokenizer = _adapt_tokenizer(tokenizer)\n fsm = CFGFSM(cfg, tokenizer)\n self.fsm = fsm\n\n def init_state(self):\n \"\"\"Initialize state with a CFGFSM copy.\"\"\"\n super().init_state()\n self.fsm = self.fsm.copy()\n\n\n@lru_cache\ndef _adapt_tokenizer(tokenizer: PreTrainedTokenizerBase):\n \"\"\"Adapt vLLM's tokenizer to use to compile the FSM.\n\n The API of Outlines tokenizers is slightly different to that of\n `transformers`. The decoder of outlines, returns a list whereas\n the decode of vLLM returns an str. To sync the vLLM decoder with\n outlines internal api, the decoder should be adapted. In addition\n we need to handle the missing spaces to Llama's tokenizer to be\n able to compile FSMs for this model.\n\n \"\"\"\n if getattr(tokenizer, \"_outlines_adapted\", False):\n return tokenizer\n\n tokenizer = copy.deepcopy(tokenizer)\n\n tokenizer.vocabulary = tokenizer.get_vocab()\n tokenizer.special_tokens = set(tokenizer.all_special_tokens)\n\n def convert_token_to_string(token: str) -> str:\n from transformers.file_utils import SPIECE_UNDERLINE\n\n string = tokenizer.convert_tokens_to_string([token])\n\n # A hack to handle missing spaces to HF's Llama tokenizers\n if token.startswith(SPIECE_UNDERLINE) or token == \"<0x20>\":\n return \" \" + string\n\n return string\n\n def change_decoder(\n decoder: Callable[[List[int]],\n str]) -> Callable[[List[int]], List[str]]:\n \"\"\"Sync vLLM's decoder with the outlines by returning list.\"\"\"\n\n def new_decoder(inp_tokens: List[int]) -> List[str]:\n return [decoder(inp_tokens)]\n\n return new_decoder\n\n tokenizer.convert_token_to_string = convert_token_to_string\n tokenizer.decode = change_decoder(tokenizer.decode)\n setattr(tokenizer, \"_outlines_adapted\", True) # noqa: B010\n\n return tokenizer\n", "path": "vllm/model_executor/guided_decoding/outlines_logits_processors.py" } ]
[ { "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.protocol import (ChatCompletionRequest,\n CompletionRequest)\nfrom vllm.model_executor.guided_decoding.outlines_logits_processors import (\n CFGLogitsProcessor, JSONLogitsProcessor, RegexLogitsProcessor)\n\n\nclass GuidedDecodingMode(Enum):\n JSON = \"json\"\n REGEX = \"regex\"\n CHOICE = \"choice\"\n GRAMMAR = \"grammar\"\n\n\n# https://github.com/outlines-dev/outlines/blob/main/outlines/grammars/json.lark\n# the main difference is that we changed the start: value to\n# start: object | array, so we are denying scalar values as the root of the\n# JSON. Starting with scalars as the root seems to cause llama to generate\n# without stop.\nJSON_GRAMMAR = r\"\"\"\n?start: object | array\n\n?value: object\n| array\n| UNESCAPED_STRING\n| SIGNED_NUMBER -> number\n| \"true\" -> true\n| \"false\" -> false\n| \"null\" -> null\n\narray : \"[\" [value (\",\" value)*] \"]\"\nobject : \"{\" [pair (\",\" pair)*] \"}\"\npair : UNESCAPED_STRING \":\" value\n\n%import common.UNESCAPED_STRING\n%import common.SIGNED_NUMBER\n%import common.WS\n\n%ignore WS\n\"\"\"\n\nglobal_thread_pool = None # used for generating logits processor fsm\n\n\nasync def get_outlines_guided_decoding_logits_processor(\n request: Union[CompletionRequest,\n ChatCompletionRequest], tokenizer: PreTrainedTokenizerBase\n) -> Union[JSONLogitsProcessor, RegexLogitsProcessor, CFGLogitsProcessor,\n None]:\n \"\"\"\n Given an OpenAI-compatible request, check for guided decoding parameters\n and get the necessary logits processor for the given guide.\n We cache logit processors by (guide, tokenizer), and on cache hit\n we make a shallow copy to reuse the same underlying FSM.\n \"\"\"\n global global_thread_pool\n guide, mode = _get_guide_and_mode(request)\n if not guide or not mode:\n return None\n\n if global_thread_pool is None:\n global_thread_pool = concurrent.futures.ThreadPoolExecutor(\n max_workers=2)\n loop = asyncio.get_running_loop()\n\n return await loop.run_in_executor(global_thread_pool,\n _get_logits_processor, guide, tokenizer,\n mode, request.guided_whitespace_pattern)\n\n\ndef _get_guide_and_mode(\n request: Union[CompletionRequest, ChatCompletionRequest]\n) -> Union[Tuple[str, GuidedDecodingMode], Tuple[None, None]]:\n\n if request.guided_json:\n json = request.guided_json\n if isinstance(json, dict):\n # turn dict into hashable string\n json = json_dumps(json)\n elif isinstance(json, BaseModel):\n # use pydantic signature so that different model classes\n # with the same fields will get hashed the same\n json = str(json.__signature__)\n return json, GuidedDecodingMode.JSON\n elif request.guided_regex:\n return request.guided_regex, GuidedDecodingMode.REGEX\n elif request.guided_choice:\n # choice just uses regex\n choices = [\n regex_escape(str(choice)) for choice in request.guided_choice\n ]\n choices_regex = \"(\" + \"|\".join(choices) + \")\"\n return choices_regex, GuidedDecodingMode.CHOICE\n elif request.guided_grammar:\n return request.guided_grammar, GuidedDecodingMode.GRAMMAR\n elif (request.response_format is not None\n and request.response_format.type == \"json_object\"):\n return JSON_GRAMMAR, GuidedDecodingMode.GRAMMAR\n else:\n return None, None\n\n\ndef _get_logits_processor(\n guide: str, tokenizer: PreTrainedTokenizerBase, mode: GuidedDecodingMode,\n whitespace_pattern: Union[str, None]\n) -> Union[JSONLogitsProcessor, RegexLogitsProcessor, CFGLogitsProcessor]:\n if mode == GuidedDecodingMode.JSON:\n return JSONLogitsProcessor(guide, tokenizer, whitespace_pattern)\n elif mode == GuidedDecodingMode.REGEX or mode == GuidedDecodingMode.CHOICE:\n return RegexLogitsProcessor(guide, tokenizer)\n elif mode == GuidedDecodingMode.GRAMMAR:\n return CFGLogitsProcessor(guide, tokenizer)\n else:\n raise ValueError(f\"Unknown guided decoding mode {mode}\")\n", "path": "vllm/model_executor/guided_decoding/outlines_decoding.py" }, { "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 obtain a copy of the License at\n\n# http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport copy\nimport json\nimport math\nfrom collections import defaultdict\nfrom functools import lru_cache\nfrom typing import Callable, DefaultDict, Dict, List, Union\n\nimport torch\nfrom outlines.fsm.guide import CFGGuide, Generate, Guide, RegexGuide, Write\nfrom outlines.fsm.json_schema import build_regex_from_schema\nfrom pydantic import BaseModel\nfrom transformers import PreTrainedTokenizerBase\n\n\nclass BaseLogitsProcessor:\n\n def __init__(self, guide: Guide):\n self._guide: Guide = guide\n self._fsm_state: DefaultDict[int, int] = defaultdict(int)\n\n def __call__(self, input_ids: List[int],\n scores: torch.Tensor) -> torch.Tensor:\n \"\"\"Use the FSM to bias the logits before sampling the next token.\"\"\"\n seq_id = hash(tuple(input_ids))\n\n if len(input_ids) > 0:\n last_token = input_ids[-1]\n last_seq_id = hash(tuple(input_ids[:-1]))\n self._fsm_state[seq_id] = self._guide.get_next_state(\n state=self._fsm_state[last_seq_id], token_id=last_token)\n\n instruction = self._guide.get_next_instruction(\n state=self._fsm_state[seq_id])\n\n if type(instruction) == Generate:\n allowed_tokens = instruction.tokens\n elif type(instruction) == Write:\n # TODO: support fast forward tokens\n allowed_tokens = [instruction.tokens[0]]\n else:\n raise TypeError(\n f\"Unsupported instruction type {type(instruction)}\")\n\n mask = torch.full((scores.shape[-1], ),\n -math.inf,\n device=scores.device)\n mask[allowed_tokens] = 0\n scores.add_(mask)\n return scores\n\n\nclass RegexLogitsProcessor(BaseLogitsProcessor):\n\n @classmethod\n @lru_cache(maxsize=32)\n def _get_guide(cls, regex_string: str,\n tokenizer: PreTrainedTokenizerBase) -> Guide:\n tokenizer = _adapt_tokenizer(tokenizer)\n return RegexGuide(regex_string, tokenizer)\n\n def __init__(self, regex_string: str, tokenizer: PreTrainedTokenizerBase):\n \"\"\"Compile the FSM that drives the regex-structured generation.\n\n Parameters\n ----------\n regex_string\n A string that represents a regular expression\n tokenizer\n The model's tokenizer\n\n \"\"\"\n super().__init__(\n RegexLogitsProcessor._get_guide(regex_string, tokenizer))\n\n\nclass JSONLogitsProcessor(RegexLogitsProcessor):\n\n def __init__(self, schema: Union[str, Dict, BaseModel],\n tokenizer: PreTrainedTokenizerBase,\n whitespace_pattern: Union[str, None]):\n \"\"\"Compile the FSM that drives the JSON-guided generation.\n\n Parameters\n ----------\n schema\n A JSON schema that encodes the structure we want the model to\n generate\n tokenizer\n The model's tokenizer\n whitespace_pattern\n Pattern to use for JSON syntactic whitespace (doesn't impact\n string literals)\n Example: allow only a single space or newline with\n `whitespace_pattern=r\"[\\n ]?\"`\n \"\"\"\n if isinstance(schema, type(BaseModel)):\n schema_str = json.dumps(schema.model_json_schema())\n elif isinstance(schema, Dict):\n schema_str = json.dumps(schema)\n elif isinstance(schema, str):\n schema_str = schema\n else:\n raise ValueError(\n f\"Cannot parse schema {schema}. The schema must be either \"\n f\"a Pydantic object, a dictionary or a string that contains \"\n f\"the JSON Schema specification\")\n regex_string = build_regex_from_schema(schema_str, whitespace_pattern)\n super().__init__(regex_string, tokenizer)\n\n\nclass CFGLogitsProcessor(BaseLogitsProcessor):\n\n @classmethod\n @lru_cache(maxsize=32)\n def _get_guide(cls, cfg: str, tokenizer: PreTrainedTokenizerBase) -> Guide:\n tokenizer = _adapt_tokenizer(tokenizer)\n return CFGGuide(cfg, tokenizer)\n\n def __init__(self, cfg: str, tokenizer: PreTrainedTokenizerBase):\n \"\"\"Compile the FSM that drives the context free grammar generation.\n\n Parameters\n ----------\n cfg\n A string that represents a context-free grammar\n tokenizer\n The model's tokenizer\n\n \"\"\"\n super().__init__(CFGLogitsProcessor._get_guide(cfg, tokenizer))\n self._guide = self._guide.copy()\n\n\n@lru_cache(maxsize=32)\ndef _adapt_tokenizer(tokenizer: PreTrainedTokenizerBase):\n \"\"\"Adapt vLLM's tokenizer to use to compile the FSM.\n\n The API of Outlines tokenizers is slightly different to that of\n `transformers`. The decoder of outlines, returns a list whereas\n the decode of vLLM returns an str. To sync the vLLM decoder with\n outlines internal api, the decoder should be adapted. In addition\n we need to handle the missing spaces to Llama's tokenizer to be\n able to compile FSMs for this model.\n\n \"\"\"\n if getattr(tokenizer, \"_outlines_adapted\", False):\n return tokenizer\n\n tokenizer = copy.deepcopy(tokenizer)\n\n tokenizer.vocabulary = tokenizer.get_vocab()\n tokenizer.special_tokens = set(tokenizer.all_special_tokens)\n\n def convert_token_to_string(token: str) -> str:\n from transformers.file_utils import SPIECE_UNDERLINE\n\n string = tokenizer.convert_tokens_to_string([token])\n\n # A hack to handle missing spaces to HF's Llama tokenizers\n if token.startswith(SPIECE_UNDERLINE) or token == \"<0x20>\":\n return \" \" + string\n\n return string\n\n def change_decoder(\n decoder: Callable[[List[int]],\n str]) -> Callable[[List[int]], List[str]]:\n \"\"\"Sync vLLM's decoder with the outlines by returning list.\"\"\"\n\n def new_decoder(inp_tokens: List[int]) -> List[str]:\n return [decoder(inp_tokens)]\n\n return new_decoder\n\n tokenizer.convert_token_to_string = convert_token_to_string\n tokenizer.decode = change_decoder(tokenizer.decode)\n setattr(tokenizer, \"_outlines_adapted\", True) # noqa: B010\n\n return tokenizer\n", "path": "vllm/model_executor/guided_decoding/outlines_logits_processors.py" } ]
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 @triton.jit\n def _fwd_kernel(\n Q,\n K,\n V,\n K_cache,\n V_cache,\n B_Loc,\n sm_scale,\n B_Start_Loc,\n B_Seqlen,\n B_Ctxlen,\n block_size,\n x,\n Out,\n stride_b_loc_b,\n stride_b_loc_s,\n stride_qbs,\n stride_qh,\n stride_qd,\n stride_kbs,\n stride_kh,\n stride_kd,\n stride_vbs,\n stride_vh,\n stride_vd,\n stride_obs,\n stride_oh,\n stride_od,\n stride_k_cache_bs,\n stride_k_cache_h,\n stride_k_cache_d,\n stride_k_cache_bl,\n stride_k_cache_x,\n stride_v_cache_bs,\n stride_v_cache_h,\n stride_v_cache_d,\n stride_v_cache_bl,\n num_queries_per_kv: int,\n BLOCK_M: tl.constexpr,\n BLOCK_DMODEL: tl.constexpr,\n BLOCK_N: tl.constexpr,\n ):\n cur_batch = tl.program_id(0)\n cur_head = tl.program_id(1)\n start_m = tl.program_id(2)\n\n cur_kv_head = cur_head // num_queries_per_kv\n\n cur_batch_ctx_len = tl.load(B_Ctxlen + cur_batch)\n cur_batch_seq_len = tl.load(B_Seqlen + cur_batch)\n cur_batch_in_all_start_index = tl.load(B_Start_Loc + cur_batch)\n\n block_start_loc = BLOCK_M * start_m\n\n # initialize offsets\n offs_n = tl.arange(0, BLOCK_N)\n offs_d = tl.arange(0, BLOCK_DMODEL)\n offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)\n off_q = (\n (cur_batch_in_all_start_index + offs_m[:, None]) * stride_qbs +\n cur_head * stride_qh + offs_d[None, :] * stride_qd)\n\n q = tl.load(\n Q + off_q,\n mask=offs_m[:, None] < cur_batch_seq_len - cur_batch_ctx_len,\n other=0.0)\n\n # # initialize pointer to m and l\n m_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float(\"inf\")\n l_i = tl.zeros([BLOCK_M], dtype=tl.float32)\n acc = tl.zeros([BLOCK_M, BLOCK_DMODEL], dtype=tl.float32)\n\n for start_n in range(0, cur_batch_ctx_len, BLOCK_N):\n start_n = tl.multiple_of(start_n, BLOCK_N)\n # -- compute qk ----\n bn = tl.load(B_Loc + cur_batch * stride_b_loc_b +\n ((start_n + offs_n) // block_size) * stride_b_loc_s,\n mask=(start_n + offs_n) < cur_batch_ctx_len,\n other=0)\n off_k = (bn[None, :] * stride_k_cache_bs +\n cur_kv_head * stride_k_cache_h +\n (offs_d[:, None] // x) * stride_k_cache_d +\n ((start_n + offs_n[None, :]) % block_size) *\n stride_k_cache_bl +\n (offs_d[:, None] % x) * stride_k_cache_x)\n off_v = (\n bn[:, None] * stride_v_cache_bs +\n cur_kv_head * stride_v_cache_h +\n offs_d[None, :] * stride_v_cache_d +\n (start_n + offs_n[:, None]) % block_size * stride_v_cache_bl)\n k = tl.load(K_cache + off_k,\n mask=(start_n + offs_n[None, :]) < cur_batch_ctx_len,\n other=0.0)\n\n qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32)\n qk += tl.dot(q, k)\n qk = tl.where((start_n + offs_n[None, :]) < cur_batch_ctx_len, qk,\n float(\"-inf\"))\n qk *= sm_scale\n\n # -- compute m_ij, p, l_ij\n m_ij = tl.max(qk, 1)\n p = tl.exp(qk - m_ij[:, None])\n l_ij = tl.sum(p, 1)\n # -- update m_i and l_i\n m_i_new = tl.maximum(m_i, m_ij)\n alpha = tl.exp(m_i - m_i_new)\n beta = tl.exp(m_ij - m_i_new)\n l_i_new = alpha * l_i + beta * l_ij\n # -- update output accumulator --\n # scale p\n p_scale = beta / l_i_new\n p = p * p_scale[:, None]\n # scale acc\n acc_scale = l_i / l_i_new * alpha\n acc = acc * acc_scale[:, None]\n # update acc\n v = tl.load(V_cache + off_v,\n mask=(start_n + offs_n[:, None]) < cur_batch_ctx_len,\n other=0.0)\n\n p = p.to(v.dtype)\n acc += tl.dot(p, v)\n # # update m_i and l_i\n l_i = l_i_new\n m_i = m_i_new\n\n off_k = (offs_n[None, :] * stride_kbs + cur_kv_head * stride_kh +\n offs_d[:, None] * stride_kd)\n off_v = (offs_n[:, None] * stride_vbs + cur_kv_head * stride_vh +\n offs_d[None, :] * stride_vd)\n k_ptrs = K + off_k\n v_ptrs = V + off_v\n\n block_mask = tl.where(\n block_start_loc < cur_batch_seq_len - cur_batch_ctx_len, 1, 0)\n\n for start_n in range(0, block_mask * (start_m + 1) * BLOCK_M, BLOCK_N):\n start_n = tl.multiple_of(start_n, BLOCK_N)\n # -- compute qk ----\n k = tl.load(k_ptrs +\n (cur_batch_in_all_start_index + start_n) * stride_kbs,\n mask=(start_n + offs_n[None, :]) <\n cur_batch_seq_len - cur_batch_ctx_len,\n other=0.0)\n\n qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32)\n qk += tl.dot(q, k)\n qk *= sm_scale\n qk = tl.where(offs_m[:, None] >= (start_n + offs_n[None, :]), qk,\n float(\"-inf\"))\n\n # -- compute m_ij, p, l_ij\n m_ij = tl.max(qk, 1)\n p = tl.exp(qk - m_ij[:, None])\n l_ij = tl.sum(p, 1)\n # -- update m_i and l_i\n m_i_new = tl.maximum(m_i, m_ij)\n alpha = tl.exp(m_i - m_i_new)\n beta = tl.exp(m_ij - m_i_new)\n l_i_new = alpha * l_i + beta * l_ij\n # -- update output accumulator --\n # scale p\n p_scale = beta / l_i_new\n p = p * p_scale[:, None]\n # scale acc\n acc_scale = l_i / l_i_new * alpha\n acc = acc * acc_scale[:, None]\n # update acc\n v = tl.load(v_ptrs +\n (cur_batch_in_all_start_index + start_n) * stride_vbs,\n mask=(start_n + offs_n[:, None]) <\n cur_batch_seq_len - cur_batch_ctx_len,\n other=0.0)\n\n p = p.to(v.dtype)\n acc += tl.dot(p, v)\n # update m_i and l_i\n l_i = l_i_new\n m_i = m_i_new\n # initialize pointers to output\n off_o = (\n (cur_batch_in_all_start_index + offs_m[:, None]) * stride_obs +\n cur_head * stride_oh + offs_d[None, :] * stride_od)\n out_ptrs = Out + off_o\n tl.store(out_ptrs,\n acc,\n mask=offs_m[:, None] < cur_batch_seq_len - cur_batch_ctx_len)\n return\n\n @triton.jit\n def _fwd_kernel_flash_attn_v2(\n Q,\n K,\n V,\n K_cache,\n V_cache,\n B_Loc,\n sm_scale,\n B_Start_Loc,\n B_Seqlen,\n B_Ctxlen,\n block_size,\n x,\n Out,\n stride_b_loc_b,\n stride_b_loc_s,\n stride_qbs,\n stride_qh,\n stride_qd,\n stride_kbs,\n stride_kh,\n stride_kd,\n stride_vbs,\n stride_vh,\n stride_vd,\n stride_obs,\n stride_oh,\n stride_od,\n stride_k_cache_bs,\n stride_k_cache_h,\n stride_k_cache_d,\n stride_k_cache_bl,\n stride_k_cache_x,\n stride_v_cache_bs,\n stride_v_cache_h,\n stride_v_cache_d,\n stride_v_cache_bl,\n num_queries_per_kv: int,\n BLOCK_M: tl.constexpr,\n BLOCK_DMODEL: tl.constexpr,\n BLOCK_N: tl.constexpr,\n ):\n cur_batch = tl.program_id(0)\n cur_head = tl.program_id(1)\n start_m = tl.program_id(2)\n\n cur_kv_head = cur_head // num_queries_per_kv\n\n cur_batch_ctx_len = tl.load(B_Ctxlen + cur_batch)\n cur_batch_seq_len = tl.load(B_Seqlen + cur_batch)\n cur_batch_in_all_start_index = tl.load(B_Start_Loc + cur_batch)\n\n block_start_loc = BLOCK_M * start_m\n\n # initialize offsets\n offs_n = tl.arange(0, BLOCK_N)\n offs_d = tl.arange(0, BLOCK_DMODEL)\n offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)\n off_q = (\n (cur_batch_in_all_start_index + offs_m[:, None]) * stride_qbs +\n cur_head * stride_qh + offs_d[None, :] * stride_qd)\n\n q = tl.load(\n Q + off_q,\n mask=offs_m[:, None] < cur_batch_seq_len - cur_batch_ctx_len,\n other=0.0)\n\n # # initialize pointer to m and l\n m_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float(\"inf\")\n l_i = tl.zeros([BLOCK_M], dtype=tl.float32)\n acc = tl.zeros([BLOCK_M, BLOCK_DMODEL], dtype=tl.float32)\n\n for start_n in range(0, cur_batch_ctx_len, BLOCK_N):\n start_n = tl.multiple_of(start_n, BLOCK_N)\n # -- compute qk ----\n bn = tl.load(B_Loc + cur_batch * stride_b_loc_b +\n ((start_n + offs_n) // block_size) * stride_b_loc_s,\n mask=(start_n + offs_n) < cur_batch_ctx_len,\n other=0)\n off_k = (bn[None, :] * stride_k_cache_bs +\n cur_kv_head * stride_k_cache_h +\n (offs_d[:, None] // x) * stride_k_cache_d +\n ((start_n + offs_n[None, :]) % block_size) *\n stride_k_cache_bl +\n (offs_d[:, None] % x) * stride_k_cache_x)\n off_v = (\n bn[:, None] * stride_v_cache_bs +\n cur_kv_head * stride_v_cache_h +\n offs_d[None, :] * stride_v_cache_d +\n (start_n + offs_n[:, None]) % block_size * stride_v_cache_bl)\n k = tl.load(K_cache + off_k,\n mask=(start_n + offs_n[None, :]) < cur_batch_ctx_len,\n other=0.0)\n\n qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32)\n qk += tl.dot(q, k)\n qk = tl.where((start_n + offs_n[None, :]) < cur_batch_ctx_len, qk,\n float(\"-inf\"))\n qk *= sm_scale\n\n # -- compute m_ij, p, l_ij\n m_ij = tl.max(qk, 1)\n m_i_new = tl.maximum(m_i, m_ij)\n p = tl.math.exp(qk - m_i_new[:, None])\n l_ij = tl.sum(p, 1)\n # -- update m_i and l_i\n\n alpha = tl.math.exp(m_i - m_i_new)\n l_i_new = alpha * l_i + l_ij\n # -- update output accumulator --\n # scale p\n # scale acc\n acc_scale = alpha\n # acc_scale = l_i / l_i_new * alpha\n acc = acc * acc_scale[:, None]\n # update acc\n v = tl.load(V_cache + off_v,\n mask=(start_n + offs_n[:, None]) < cur_batch_ctx_len,\n other=0.0)\n\n p = p.to(v.dtype)\n acc += tl.dot(p, v)\n # update m_i and l_i\n l_i = l_i_new\n m_i = m_i_new\n\n off_k = (offs_n[None, :] * stride_kbs + cur_kv_head * stride_kh +\n offs_d[:, None] * stride_kd)\n off_v = (offs_n[:, None] * stride_vbs + cur_kv_head * stride_vh +\n offs_d[None, :] * stride_vd)\n k_ptrs = K + off_k\n v_ptrs = V + off_v\n\n block_mask = tl.where(\n block_start_loc < cur_batch_seq_len - cur_batch_ctx_len, 1, 0)\n\n for start_n in range(0, block_mask * (start_m + 1) * BLOCK_M, BLOCK_N):\n start_n = tl.multiple_of(start_n, BLOCK_N)\n # -- compute qk ----\n k = tl.load(k_ptrs +\n (cur_batch_in_all_start_index + start_n) * stride_kbs,\n mask=(start_n + offs_n[None, :]) <\n cur_batch_seq_len - cur_batch_ctx_len,\n other=0.0)\n\n qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32)\n qk += tl.dot(q, k)\n qk *= sm_scale\n qk = tl.where(offs_m[:, None] >= (start_n + offs_n[None, :]), qk,\n float(\"-inf\"))\n\n # -- compute m_ij, p, l_ij\n m_ij = tl.max(qk, 1)\n m_i_new = tl.maximum(m_i, m_ij)\n p = tl.math.exp(qk - m_i_new[:, None])\n l_ij = tl.sum(p, 1)\n # -- update m_i and l_i\n\n alpha = tl.math.exp(m_i - m_i_new)\n l_i_new = alpha * l_i + l_ij\n # -- update output accumulator --\n # scale p\n # scale acc\n acc_scale = alpha\n # acc_scale = l_i / l_i_new * alpha\n acc = acc * acc_scale[:, None]\n # update acc\n v = tl.load(v_ptrs +\n (cur_batch_in_all_start_index + start_n) * stride_vbs,\n mask=(start_n + offs_n[:, None]) <\n cur_batch_seq_len - cur_batch_ctx_len,\n other=0.0)\n\n p = p.to(v.dtype)\n acc += tl.dot(p, v)\n # update m_i and l_i\n l_i = l_i_new\n m_i = m_i_new\n\n # acc /= l_i[:, None]\n # initialize pointers to output\n off_o = (\n (cur_batch_in_all_start_index + offs_m[:, None]) * stride_obs +\n cur_head * stride_oh + offs_d[None, :] * stride_od)\n out_ptrs = Out + off_o\n tl.store(out_ptrs,\n acc,\n mask=offs_m[:, None] < cur_batch_seq_len - cur_batch_ctx_len)\n return\n\n @triton.jit\n def _fwd_kernel_alibi(\n Q,\n K,\n V,\n K_cache,\n V_cache,\n B_Loc,\n sm_scale,\n B_Start_Loc,\n B_Seqlen,\n B_Ctxlen,\n Alibi_slopes,\n block_size,\n x,\n Out,\n stride_b_loc_b,\n stride_b_loc_s,\n stride_qbs,\n stride_qh,\n stride_qd,\n stride_kbs,\n stride_kh,\n stride_kd,\n stride_vbs,\n stride_vh,\n stride_vd,\n stride_obs,\n stride_oh,\n stride_od,\n stride_k_cache_bs,\n stride_k_cache_h,\n stride_k_cache_d,\n stride_k_cache_bl,\n stride_k_cache_x,\n stride_v_cache_bs,\n stride_v_cache_h,\n stride_v_cache_d,\n stride_v_cache_bl,\n num_queries_per_kv: int,\n BLOCK_M: tl.constexpr,\n BLOCK_DMODEL: tl.constexpr,\n BLOCK_N: tl.constexpr,\n ):\n # attn_bias[]\n cur_batch = tl.program_id(0)\n cur_head = tl.program_id(1)\n start_m = tl.program_id(2)\n\n cur_kv_head = cur_head // num_queries_per_kv\n\n # cur_batch_seq_len: the length of prompts\n # cur_batch_ctx_len: the length of prefix\n # cur_batch_in_all_start_index: the start id of the dim=0\n cur_batch_ctx_len = tl.load(B_Ctxlen + cur_batch)\n cur_batch_seq_len = tl.load(B_Seqlen + cur_batch)\n cur_batch_in_all_start_index = tl.load(B_Start_Loc + cur_batch)\n\n block_start_loc = BLOCK_M * start_m\n\n # initialize offsets\n offs_n = tl.arange(0, BLOCK_N)\n offs_d = tl.arange(0, BLOCK_DMODEL)\n offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)\n off_q = (\n (cur_batch_in_all_start_index + offs_m[:, None]) * stride_qbs +\n cur_head * stride_qh + offs_d[None, :] * stride_qd)\n\n q = tl.load(\n Q + off_q,\n mask=offs_m[:, None] < cur_batch_seq_len - cur_batch_ctx_len,\n other=0.0)\n\n # # initialize pointer to m and l\n m_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float(\"inf\")\n l_i = tl.zeros([BLOCK_M], dtype=tl.float32)\n acc = tl.zeros([BLOCK_M, BLOCK_DMODEL], dtype=tl.float32)\n\n alibi_slope = tl.load(Alibi_slopes + cur_head)\n alibi_start_q = tl.arange(\n 0, BLOCK_M) + block_start_loc + cur_batch_ctx_len\n alibi_start_k = 0\n for start_n in range(0, cur_batch_ctx_len, BLOCK_N):\n start_n = tl.multiple_of(start_n, BLOCK_N)\n # -- compute qk ----\n bn = tl.load(B_Loc + cur_batch * stride_b_loc_b +\n ((start_n + offs_n) // block_size) * stride_b_loc_s,\n mask=(start_n + offs_n) < cur_batch_ctx_len,\n other=0)\n off_k = (bn[None, :] * stride_k_cache_bs +\n cur_kv_head * stride_k_cache_h +\n (offs_d[:, None] // x) * stride_k_cache_d +\n ((start_n + offs_n[None, :]) % block_size) *\n stride_k_cache_bl +\n (offs_d[:, None] % x) * stride_k_cache_x)\n off_v = (\n bn[:, None] * stride_v_cache_bs +\n cur_kv_head * stride_v_cache_h +\n offs_d[None, :] * stride_v_cache_d +\n (start_n + offs_n[:, None]) % block_size * stride_v_cache_bl)\n k = tl.load(K_cache + off_k,\n mask=(start_n + offs_n[None, :]) < cur_batch_ctx_len,\n other=0.0)\n\n qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32)\n qk += tl.dot(q, k)\n qk = tl.where((start_n + offs_n[None, :]) < cur_batch_ctx_len, qk,\n float(\"-inf\"))\n qk *= sm_scale\n\n # load alibi\n alibi = (tl.arange(0, BLOCK_N)[None, :] + alibi_start_k -\n alibi_start_q[:, None]) * alibi_slope\n alibi = tl.where(\n (alibi <= 0) & (alibi_start_q[:, None] < cur_batch_seq_len),\n alibi, float(\"-inf\"))\n qk += alibi\n alibi_start_k += BLOCK_N\n\n # -- compute m_ij, p, l_ij\n m_ij = tl.max(qk, 1)\n m_i_new = tl.maximum(m_i, m_ij)\n p = tl.math.exp(qk - m_i_new[:, None])\n l_ij = tl.sum(p, 1)\n # -- update m_i and l_i\n\n alpha = tl.math.exp(m_i - m_i_new)\n l_i_new = alpha * l_i + l_ij\n # -- update output accumulator --\n # scale p\n # scale acc\n acc_scale = alpha\n # acc_scale = l_i / l_i_new * alpha\n acc = acc * acc_scale[:, None]\n # update acc\n v = tl.load(V_cache + off_v,\n mask=(start_n + offs_n[:, None]) < cur_batch_ctx_len,\n other=0.0)\n\n p = p.to(v.dtype)\n acc += tl.dot(p, v, allow_tf32=False)\n # update m_i and l_i\n l_i = l_i_new\n m_i = m_i_new\n\n off_k = (offs_n[None, :] * stride_kbs + cur_kv_head * stride_kh +\n offs_d[:, None] * stride_kd)\n off_v = (offs_n[:, None] * stride_vbs + cur_kv_head * stride_vh +\n offs_d[None, :] * stride_vd)\n k_ptrs = K + off_k\n v_ptrs = V + off_v\n\n block_mask = tl.where(\n block_start_loc < cur_batch_seq_len - cur_batch_ctx_len, 1, 0)\n\n # init alibi\n alibi_slope = tl.load(Alibi_slopes + cur_head)\n alibi_start_q = tl.arange(\n 0, BLOCK_M) + block_start_loc + cur_batch_ctx_len\n alibi_start_k = cur_batch_ctx_len\n # # init debugger\n # offset_db_q = tl.arange(0, BLOCK_M) + block_start_loc\n # offset_db_k = tl.arange(0, BLOCK_N)\n # calc q[BLOCK_M, BLOCK_MODEL] mul k[prefix_len: , BLOCK_DMODEL]\n for start_n in range(0, block_mask * (start_m + 1) * BLOCK_M, BLOCK_N):\n start_n = tl.multiple_of(start_n, BLOCK_N)\n # -- compute qk ----\n k = tl.load(k_ptrs +\n (cur_batch_in_all_start_index + start_n) * stride_kbs,\n mask=(start_n + offs_n[None, :]) <\n cur_batch_seq_len - cur_batch_ctx_len,\n other=0.0)\n\n qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32)\n qk += tl.dot(q, k, allow_tf32=False)\n qk *= sm_scale\n qk = tl.where(offs_m[:, None] >= (start_n + offs_n[None, :]), qk,\n float(\"-inf\"))\n\n # load alibi\n alibi = (tl.arange(0, BLOCK_N)[None, :] + alibi_start_k -\n alibi_start_q[:, None]) * alibi_slope\n alibi = tl.where(\n (alibi <= 0) & (alibi_start_q[:, None] < cur_batch_seq_len),\n alibi, float(\"-inf\"))\n qk += alibi\n alibi_start_k += BLOCK_N\n\n # -- compute m_ij, p, l_ij\n m_ij = tl.max(qk, 1)\n m_i_new = tl.maximum(m_i, m_ij)\n p = tl.math.exp(qk - m_i_new[:, None])\n l_ij = tl.sum(p, 1)\n # -- update m_i and l_i\n\n alpha = tl.math.exp(m_i - m_i_new)\n l_i_new = alpha * l_i + l_ij\n # -- update output accumulator --\n # scale p\n # scale acc\n acc_scale = alpha\n # acc_scale = l_i / l_i_new * alpha\n acc = acc * acc_scale[:, None]\n # update acc\n v = tl.load(v_ptrs +\n (cur_batch_in_all_start_index + start_n) * stride_vbs,\n mask=(start_n + offs_n[:, None]) <\n cur_batch_seq_len - cur_batch_ctx_len,\n other=0.0)\n\n p = p.to(v.dtype)\n acc += tl.dot(p, v, allow_tf32=False)\n # update m_i and l_i\n l_i = l_i_new\n m_i = m_i_new\n\n acc = acc / l_i[:, None]\n\n # initialize pointers to output\n off_o = (\n (cur_batch_in_all_start_index + offs_m[:, None]) * stride_obs +\n cur_head * stride_oh + offs_d[None, :] * stride_od)\n out_ptrs = Out + off_o\n tl.store(out_ptrs,\n acc,\n mask=offs_m[:, None] < cur_batch_seq_len - cur_batch_ctx_len)\n return\n\n @torch.inference_mode()\n def context_attention_fwd(q,\n k,\n v,\n o,\n k_cache,\n v_cache,\n b_loc,\n b_start_loc,\n b_seq_len,\n b_ctx_len,\n max_input_len,\n alibi_slopes=None):\n\n cap = torch.cuda.get_device_capability()\n BLOCK = 128 if cap[0] >= 8 else 64\n # shape constraints\n Lq, Lk, Lv = q.shape[-1], k.shape[-1], v.shape[-1]\n assert Lq == Lk and Lk == Lv\n assert Lk in {16, 32, 64, 128}\n\n sm_scale = 1.0 / (Lq**0.5)\n batch, head = b_seq_len.shape[0], q.shape[1]\n num_queries_per_kv = q.shape[1] // k.shape[1]\n\n grid = (batch, head, triton.cdiv(max_input_len, BLOCK)) # batch, head,\n\n num_warps = 8 if Lk <= 64 else 8\n if alibi_slopes is not None:\n _fwd_kernel_alibi[grid](\n q,\n k,\n v,\n k_cache,\n v_cache,\n b_loc,\n sm_scale,\n b_start_loc,\n b_seq_len,\n b_ctx_len,\n alibi_slopes,\n v_cache.shape[3],\n 8,\n o,\n b_loc.stride(0),\n b_loc.stride(1),\n q.stride(0),\n q.stride(1),\n q.stride(2),\n k.stride(0),\n k.stride(1),\n k.stride(2),\n v.stride(0),\n v.stride(1),\n v.stride(2),\n o.stride(0),\n o.stride(1),\n o.stride(2),\n k_cache.stride(0),\n k_cache.stride(1),\n k_cache.stride(2),\n k_cache.stride(3),\n k_cache.stride(\n 4\n ), #[num_blocks, num_kv_heads, head_size/x, block_size, x]\n v_cache.stride(0),\n v_cache.stride(1),\n v_cache.stride(2),\n v_cache.stride(\n 3), #[num_blocks, num_kv_heads, head_size, block_size]\n num_queries_per_kv=num_queries_per_kv,\n BLOCK_M=BLOCK,\n BLOCK_DMODEL=Lk,\n BLOCK_N=BLOCK,\n num_warps=num_warps,\n num_stages=1,\n )\n return\n\n _fwd_kernel[grid](\n q,\n k,\n v,\n k_cache,\n v_cache,\n b_loc,\n sm_scale,\n b_start_loc,\n b_seq_len,\n b_ctx_len,\n v_cache.shape[3],\n 8,\n o,\n b_loc.stride(0),\n b_loc.stride(1),\n q.stride(0),\n q.stride(1),\n q.stride(2),\n k.stride(0),\n k.stride(1),\n k.stride(2),\n v.stride(0),\n v.stride(1),\n v.stride(2),\n o.stride(0),\n o.stride(1),\n o.stride(2),\n k_cache.stride(0),\n k_cache.stride(1),\n k_cache.stride(2),\n k_cache.stride(3),\n k_cache.stride(\n 4), #[num_blocks, num_kv_heads, head_size/x, block_size, x]\n v_cache.stride(0),\n v_cache.stride(1),\n v_cache.stride(2),\n v_cache.stride(\n 3), #[num_blocks, num_kv_heads, head_size, block_size]\n num_queries_per_kv=num_queries_per_kv,\n BLOCK_M=BLOCK,\n BLOCK_DMODEL=Lk,\n BLOCK_N=BLOCK,\n num_warps=num_warps,\n num_stages=1,\n )\n return\n", "path": "vllm/attention/ops/prefix_prefill.py" } ]
[ { "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 @triton.jit\n def _fwd_kernel(\n Q,\n K,\n V,\n K_cache,\n V_cache,\n B_Loc,\n sm_scale,\n B_Start_Loc,\n B_Seqlen,\n B_Ctxlen,\n block_size,\n x,\n Out,\n stride_b_loc_b,\n stride_b_loc_s,\n stride_qbs,\n stride_qh,\n stride_qd,\n stride_kbs,\n stride_kh,\n stride_kd,\n stride_vbs,\n stride_vh,\n stride_vd,\n stride_obs,\n stride_oh,\n stride_od,\n stride_k_cache_bs,\n stride_k_cache_h,\n stride_k_cache_d,\n stride_k_cache_bl,\n stride_k_cache_x,\n stride_v_cache_bs,\n stride_v_cache_h,\n stride_v_cache_d,\n stride_v_cache_bl,\n num_queries_per_kv: int,\n BLOCK_M: tl.constexpr,\n BLOCK_DMODEL: tl.constexpr, # head size\n BLOCK_DMODEL_PADDED: tl.constexpr, # head size padded to a power of 2\n BLOCK_N: tl.constexpr,\n ):\n cur_batch = tl.program_id(0)\n cur_head = tl.program_id(1)\n start_m = tl.program_id(2)\n\n cur_kv_head = cur_head // num_queries_per_kv\n\n cur_batch_ctx_len = tl.load(B_Ctxlen + cur_batch)\n cur_batch_seq_len = tl.load(B_Seqlen + cur_batch)\n cur_batch_in_all_start_index = tl.load(B_Start_Loc + cur_batch)\n cur_batch_query_len = cur_batch_seq_len - cur_batch_ctx_len\n\n block_start_loc = BLOCK_M * start_m\n\n # initialize offsets\n offs_n = tl.arange(0, BLOCK_N)\n offs_d = tl.arange(0, BLOCK_DMODEL_PADDED)\n offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)\n off_q = (\n (cur_batch_in_all_start_index + offs_m[:, None]) * stride_qbs +\n cur_head * stride_qh + offs_d[None, :] * stride_qd)\n\n dim_mask = tl.where(\n tl.arange(0, BLOCK_DMODEL_PADDED) < BLOCK_DMODEL, 1, 0).to(tl.int1)\n\n q = tl.load(Q + off_q,\n mask=dim_mask[None, :] &\n (offs_m[:, None] < cur_batch_query_len),\n other=0.0)\n\n # # initialize pointer to m and l\n m_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float(\"inf\")\n l_i = tl.zeros([BLOCK_M], dtype=tl.float32)\n acc = tl.zeros([BLOCK_M, BLOCK_DMODEL_PADDED], dtype=tl.float32)\n\n for start_n in range(0, cur_batch_ctx_len, BLOCK_N):\n start_n = tl.multiple_of(start_n, BLOCK_N)\n # -- compute qk ----\n bn = tl.load(B_Loc + cur_batch * stride_b_loc_b +\n ((start_n + offs_n) // block_size) * stride_b_loc_s,\n mask=(start_n + offs_n) < cur_batch_ctx_len,\n other=0)\n off_k = (bn[None, :] * stride_k_cache_bs +\n cur_kv_head * stride_k_cache_h +\n (offs_d[:, None] // x) * stride_k_cache_d +\n ((start_n + offs_n[None, :]) % block_size) *\n stride_k_cache_bl +\n (offs_d[:, None] % x) * stride_k_cache_x)\n off_v = (\n bn[:, None] * stride_v_cache_bs +\n cur_kv_head * stride_v_cache_h +\n offs_d[None, :] * stride_v_cache_d +\n (start_n + offs_n[:, None]) % block_size * stride_v_cache_bl)\n k = tl.load(K_cache + off_k,\n mask=dim_mask[:, None] &\n ((start_n + offs_n[None, :]) < cur_batch_ctx_len),\n other=0.0)\n\n qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32)\n qk += tl.dot(q, k)\n qk = tl.where((start_n + offs_n[None, :]) < cur_batch_ctx_len, qk,\n float(\"-inf\"))\n qk *= sm_scale\n\n # -- compute m_ij, p, l_ij\n m_ij = tl.max(qk, 1)\n p = tl.exp(qk - m_ij[:, None])\n l_ij = tl.sum(p, 1)\n # -- update m_i and l_i\n m_i_new = tl.maximum(m_i, m_ij)\n alpha = tl.exp(m_i - m_i_new)\n beta = tl.exp(m_ij - m_i_new)\n l_i_new = alpha * l_i + beta * l_ij\n # -- update output accumulator --\n # scale p\n p_scale = beta / l_i_new\n p = p * p_scale[:, None]\n # scale acc\n acc_scale = l_i / l_i_new * alpha\n acc = acc * acc_scale[:, None]\n # update acc\n v = tl.load(V_cache + off_v,\n mask=dim_mask[None, :] &\n ((start_n + offs_n[:, None]) < cur_batch_ctx_len),\n other=0.0)\n\n p = p.to(v.dtype)\n acc += tl.dot(p, v)\n # # update m_i and l_i\n l_i = l_i_new\n m_i = m_i_new\n\n off_k = (offs_n[None, :] * stride_kbs + cur_kv_head * stride_kh +\n offs_d[:, None] * stride_kd)\n off_v = (offs_n[:, None] * stride_vbs + cur_kv_head * stride_vh +\n offs_d[None, :] * stride_vd)\n k_ptrs = K + off_k\n v_ptrs = V + off_v\n\n block_mask = tl.where(block_start_loc < cur_batch_query_len, 1, 0)\n\n for start_n in range(0, block_mask * (start_m + 1) * BLOCK_M, BLOCK_N):\n start_n = tl.multiple_of(start_n, BLOCK_N)\n # -- compute qk ----\n k = tl.load(k_ptrs +\n (cur_batch_in_all_start_index + start_n) * stride_kbs,\n mask=dim_mask[:, None] &\n ((start_n + offs_n[None, :]) < cur_batch_query_len),\n other=0.0)\n\n qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32)\n qk += tl.dot(q, k)\n qk *= sm_scale\n qk = tl.where(offs_m[:, None] >= (start_n + offs_n[None, :]), qk,\n float(\"-inf\"))\n\n # -- compute m_ij, p, l_ij\n m_ij = tl.max(qk, 1)\n p = tl.exp(qk - m_ij[:, None])\n l_ij = tl.sum(p, 1)\n # -- update m_i and l_i\n m_i_new = tl.maximum(m_i, m_ij)\n alpha = tl.exp(m_i - m_i_new)\n beta = tl.exp(m_ij - m_i_new)\n l_i_new = alpha * l_i + beta * l_ij\n # -- update output accumulator --\n # scale p\n p_scale = beta / l_i_new\n p = p * p_scale[:, None]\n # scale acc\n acc_scale = l_i / l_i_new * alpha\n acc = acc * acc_scale[:, None]\n # update acc\n v = tl.load(v_ptrs +\n (cur_batch_in_all_start_index + start_n) * stride_vbs,\n mask=dim_mask[None, :] &\n ((start_n + offs_n[:, None]) < cur_batch_query_len),\n other=0.0)\n\n p = p.to(v.dtype)\n acc += tl.dot(p, v)\n # update m_i and l_i\n l_i = l_i_new\n m_i = m_i_new\n # initialize pointers to output\n off_o = (\n (cur_batch_in_all_start_index + offs_m[:, None]) * stride_obs +\n cur_head * stride_oh + offs_d[None, :] * stride_od)\n out_ptrs = Out + off_o\n tl.store(out_ptrs,\n acc,\n mask=dim_mask[None, :] &\n (offs_m[:, None] < cur_batch_query_len))\n return\n\n @triton.jit\n def _fwd_kernel_flash_attn_v2(\n Q,\n K,\n V,\n K_cache,\n V_cache,\n B_Loc,\n sm_scale,\n B_Start_Loc,\n B_Seqlen,\n B_Ctxlen,\n block_size,\n x,\n Out,\n stride_b_loc_b,\n stride_b_loc_s,\n stride_qbs,\n stride_qh,\n stride_qd,\n stride_kbs,\n stride_kh,\n stride_kd,\n stride_vbs,\n stride_vh,\n stride_vd,\n stride_obs,\n stride_oh,\n stride_od,\n stride_k_cache_bs,\n stride_k_cache_h,\n stride_k_cache_d,\n stride_k_cache_bl,\n stride_k_cache_x,\n stride_v_cache_bs,\n stride_v_cache_h,\n stride_v_cache_d,\n stride_v_cache_bl,\n num_queries_per_kv: int,\n BLOCK_M: tl.constexpr,\n BLOCK_DMODEL: tl.constexpr,\n BLOCK_N: tl.constexpr,\n ):\n cur_batch = tl.program_id(0)\n cur_head = tl.program_id(1)\n start_m = tl.program_id(2)\n\n cur_kv_head = cur_head // num_queries_per_kv\n\n cur_batch_ctx_len = tl.load(B_Ctxlen + cur_batch)\n cur_batch_seq_len = tl.load(B_Seqlen + cur_batch)\n cur_batch_in_all_start_index = tl.load(B_Start_Loc + cur_batch)\n\n block_start_loc = BLOCK_M * start_m\n\n # initialize offsets\n offs_n = tl.arange(0, BLOCK_N)\n offs_d = tl.arange(0, BLOCK_DMODEL)\n offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)\n off_q = (\n (cur_batch_in_all_start_index + offs_m[:, None]) * stride_qbs +\n cur_head * stride_qh + offs_d[None, :] * stride_qd)\n\n q = tl.load(\n Q + off_q,\n mask=offs_m[:, None] < cur_batch_seq_len - cur_batch_ctx_len,\n other=0.0)\n\n # # initialize pointer to m and l\n m_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float(\"inf\")\n l_i = tl.zeros([BLOCK_M], dtype=tl.float32)\n acc = tl.zeros([BLOCK_M, BLOCK_DMODEL], dtype=tl.float32)\n\n for start_n in range(0, cur_batch_ctx_len, BLOCK_N):\n start_n = tl.multiple_of(start_n, BLOCK_N)\n # -- compute qk ----\n bn = tl.load(B_Loc + cur_batch * stride_b_loc_b +\n ((start_n + offs_n) // block_size) * stride_b_loc_s,\n mask=(start_n + offs_n) < cur_batch_ctx_len,\n other=0)\n off_k = (bn[None, :] * stride_k_cache_bs +\n cur_kv_head * stride_k_cache_h +\n (offs_d[:, None] // x) * stride_k_cache_d +\n ((start_n + offs_n[None, :]) % block_size) *\n stride_k_cache_bl +\n (offs_d[:, None] % x) * stride_k_cache_x)\n off_v = (\n bn[:, None] * stride_v_cache_bs +\n cur_kv_head * stride_v_cache_h +\n offs_d[None, :] * stride_v_cache_d +\n (start_n + offs_n[:, None]) % block_size * stride_v_cache_bl)\n k = tl.load(K_cache + off_k,\n mask=(start_n + offs_n[None, :]) < cur_batch_ctx_len,\n other=0.0)\n\n qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32)\n qk += tl.dot(q, k)\n qk = tl.where((start_n + offs_n[None, :]) < cur_batch_ctx_len, qk,\n float(\"-inf\"))\n qk *= sm_scale\n\n # -- compute m_ij, p, l_ij\n m_ij = tl.max(qk, 1)\n m_i_new = tl.maximum(m_i, m_ij)\n p = tl.math.exp(qk - m_i_new[:, None])\n l_ij = tl.sum(p, 1)\n # -- update m_i and l_i\n\n alpha = tl.math.exp(m_i - m_i_new)\n l_i_new = alpha * l_i + l_ij\n # -- update output accumulator --\n # scale p\n # scale acc\n acc_scale = alpha\n # acc_scale = l_i / l_i_new * alpha\n acc = acc * acc_scale[:, None]\n # update acc\n v = tl.load(V_cache + off_v,\n mask=(start_n + offs_n[:, None]) < cur_batch_ctx_len,\n other=0.0)\n\n p = p.to(v.dtype)\n acc += tl.dot(p, v)\n # update m_i and l_i\n l_i = l_i_new\n m_i = m_i_new\n\n off_k = (offs_n[None, :] * stride_kbs + cur_kv_head * stride_kh +\n offs_d[:, None] * stride_kd)\n off_v = (offs_n[:, None] * stride_vbs + cur_kv_head * stride_vh +\n offs_d[None, :] * stride_vd)\n k_ptrs = K + off_k\n v_ptrs = V + off_v\n\n block_mask = tl.where(\n block_start_loc < cur_batch_seq_len - cur_batch_ctx_len, 1, 0)\n\n for start_n in range(0, block_mask * (start_m + 1) * BLOCK_M, BLOCK_N):\n start_n = tl.multiple_of(start_n, BLOCK_N)\n # -- compute qk ----\n k = tl.load(k_ptrs +\n (cur_batch_in_all_start_index + start_n) * stride_kbs,\n mask=(start_n + offs_n[None, :]) <\n cur_batch_seq_len - cur_batch_ctx_len,\n other=0.0)\n\n qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32)\n qk += tl.dot(q, k)\n qk *= sm_scale\n qk = tl.where(offs_m[:, None] >= (start_n + offs_n[None, :]), qk,\n float(\"-inf\"))\n\n # -- compute m_ij, p, l_ij\n m_ij = tl.max(qk, 1)\n m_i_new = tl.maximum(m_i, m_ij)\n p = tl.math.exp(qk - m_i_new[:, None])\n l_ij = tl.sum(p, 1)\n # -- update m_i and l_i\n\n alpha = tl.math.exp(m_i - m_i_new)\n l_i_new = alpha * l_i + l_ij\n # -- update output accumulator --\n # scale p\n # scale acc\n acc_scale = alpha\n # acc_scale = l_i / l_i_new * alpha\n acc = acc * acc_scale[:, None]\n # update acc\n v = tl.load(v_ptrs +\n (cur_batch_in_all_start_index + start_n) * stride_vbs,\n mask=(start_n + offs_n[:, None]) <\n cur_batch_seq_len - cur_batch_ctx_len,\n other=0.0)\n\n p = p.to(v.dtype)\n acc += tl.dot(p, v)\n # update m_i and l_i\n l_i = l_i_new\n m_i = m_i_new\n\n # acc /= l_i[:, None]\n # initialize pointers to output\n off_o = (\n (cur_batch_in_all_start_index + offs_m[:, None]) * stride_obs +\n cur_head * stride_oh + offs_d[None, :] * stride_od)\n out_ptrs = Out + off_o\n tl.store(out_ptrs,\n acc,\n mask=offs_m[:, None] < cur_batch_seq_len - cur_batch_ctx_len)\n return\n\n @triton.jit\n def _fwd_kernel_alibi(\n Q,\n K,\n V,\n K_cache,\n V_cache,\n B_Loc,\n sm_scale,\n B_Start_Loc,\n B_Seqlen,\n B_Ctxlen,\n Alibi_slopes,\n block_size,\n x,\n Out,\n stride_b_loc_b,\n stride_b_loc_s,\n stride_qbs,\n stride_qh,\n stride_qd,\n stride_kbs,\n stride_kh,\n stride_kd,\n stride_vbs,\n stride_vh,\n stride_vd,\n stride_obs,\n stride_oh,\n stride_od,\n stride_k_cache_bs,\n stride_k_cache_h,\n stride_k_cache_d,\n stride_k_cache_bl,\n stride_k_cache_x,\n stride_v_cache_bs,\n stride_v_cache_h,\n stride_v_cache_d,\n stride_v_cache_bl,\n num_queries_per_kv: int,\n BLOCK_M: tl.constexpr,\n BLOCK_DMODEL: tl.constexpr,\n BLOCK_N: tl.constexpr,\n ):\n # attn_bias[]\n cur_batch = tl.program_id(0)\n cur_head = tl.program_id(1)\n start_m = tl.program_id(2)\n\n cur_kv_head = cur_head // num_queries_per_kv\n\n # cur_batch_seq_len: the length of prompts\n # cur_batch_ctx_len: the length of prefix\n # cur_batch_in_all_start_index: the start id of the dim=0\n cur_batch_ctx_len = tl.load(B_Ctxlen + cur_batch)\n cur_batch_seq_len = tl.load(B_Seqlen + cur_batch)\n cur_batch_in_all_start_index = tl.load(B_Start_Loc + cur_batch)\n\n block_start_loc = BLOCK_M * start_m\n\n # initialize offsets\n offs_n = tl.arange(0, BLOCK_N)\n offs_d = tl.arange(0, BLOCK_DMODEL)\n offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)\n off_q = (\n (cur_batch_in_all_start_index + offs_m[:, None]) * stride_qbs +\n cur_head * stride_qh + offs_d[None, :] * stride_qd)\n\n q = tl.load(\n Q + off_q,\n mask=offs_m[:, None] < cur_batch_seq_len - cur_batch_ctx_len,\n other=0.0)\n\n # # initialize pointer to m and l\n m_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float(\"inf\")\n l_i = tl.zeros([BLOCK_M], dtype=tl.float32)\n acc = tl.zeros([BLOCK_M, BLOCK_DMODEL], dtype=tl.float32)\n\n alibi_slope = tl.load(Alibi_slopes + cur_head)\n alibi_start_q = tl.arange(\n 0, BLOCK_M) + block_start_loc + cur_batch_ctx_len\n alibi_start_k = 0\n for start_n in range(0, cur_batch_ctx_len, BLOCK_N):\n start_n = tl.multiple_of(start_n, BLOCK_N)\n # -- compute qk ----\n bn = tl.load(B_Loc + cur_batch * stride_b_loc_b +\n ((start_n + offs_n) // block_size) * stride_b_loc_s,\n mask=(start_n + offs_n) < cur_batch_ctx_len,\n other=0)\n off_k = (bn[None, :] * stride_k_cache_bs +\n cur_kv_head * stride_k_cache_h +\n (offs_d[:, None] // x) * stride_k_cache_d +\n ((start_n + offs_n[None, :]) % block_size) *\n stride_k_cache_bl +\n (offs_d[:, None] % x) * stride_k_cache_x)\n off_v = (\n bn[:, None] * stride_v_cache_bs +\n cur_kv_head * stride_v_cache_h +\n offs_d[None, :] * stride_v_cache_d +\n (start_n + offs_n[:, None]) % block_size * stride_v_cache_bl)\n k = tl.load(K_cache + off_k,\n mask=(start_n + offs_n[None, :]) < cur_batch_ctx_len,\n other=0.0)\n\n qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32)\n qk += tl.dot(q, k)\n qk = tl.where((start_n + offs_n[None, :]) < cur_batch_ctx_len, qk,\n float(\"-inf\"))\n qk *= sm_scale\n\n # load alibi\n alibi = (tl.arange(0, BLOCK_N)[None, :] + alibi_start_k -\n alibi_start_q[:, None]) * alibi_slope\n alibi = tl.where(\n (alibi <= 0) & (alibi_start_q[:, None] < cur_batch_seq_len),\n alibi, float(\"-inf\"))\n qk += alibi\n alibi_start_k += BLOCK_N\n\n # -- compute m_ij, p, l_ij\n m_ij = tl.max(qk, 1)\n m_i_new = tl.maximum(m_i, m_ij)\n p = tl.math.exp(qk - m_i_new[:, None])\n l_ij = tl.sum(p, 1)\n # -- update m_i and l_i\n\n alpha = tl.math.exp(m_i - m_i_new)\n l_i_new = alpha * l_i + l_ij\n # -- update output accumulator --\n # scale p\n # scale acc\n acc_scale = alpha\n # acc_scale = l_i / l_i_new * alpha\n acc = acc * acc_scale[:, None]\n # update acc\n v = tl.load(V_cache + off_v,\n mask=(start_n + offs_n[:, None]) < cur_batch_ctx_len,\n other=0.0)\n\n p = p.to(v.dtype)\n acc += tl.dot(p, v, allow_tf32=False)\n # update m_i and l_i\n l_i = l_i_new\n m_i = m_i_new\n\n off_k = (offs_n[None, :] * stride_kbs + cur_kv_head * stride_kh +\n offs_d[:, None] * stride_kd)\n off_v = (offs_n[:, None] * stride_vbs + cur_kv_head * stride_vh +\n offs_d[None, :] * stride_vd)\n k_ptrs = K + off_k\n v_ptrs = V + off_v\n\n block_mask = tl.where(\n block_start_loc < cur_batch_seq_len - cur_batch_ctx_len, 1, 0)\n\n # init alibi\n alibi_slope = tl.load(Alibi_slopes + cur_head)\n alibi_start_q = tl.arange(\n 0, BLOCK_M) + block_start_loc + cur_batch_ctx_len\n alibi_start_k = cur_batch_ctx_len\n # # init debugger\n # offset_db_q = tl.arange(0, BLOCK_M) + block_start_loc\n # offset_db_k = tl.arange(0, BLOCK_N)\n # calc q[BLOCK_M, BLOCK_MODEL] mul k[prefix_len: , BLOCK_DMODEL]\n for start_n in range(0, block_mask * (start_m + 1) * BLOCK_M, BLOCK_N):\n start_n = tl.multiple_of(start_n, BLOCK_N)\n # -- compute qk ----\n k = tl.load(k_ptrs +\n (cur_batch_in_all_start_index + start_n) * stride_kbs,\n mask=(start_n + offs_n[None, :]) <\n cur_batch_seq_len - cur_batch_ctx_len,\n other=0.0)\n\n qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32)\n qk += tl.dot(q, k, allow_tf32=False)\n qk *= sm_scale\n qk = tl.where(offs_m[:, None] >= (start_n + offs_n[None, :]), qk,\n float(\"-inf\"))\n\n # load alibi\n alibi = (tl.arange(0, BLOCK_N)[None, :] + alibi_start_k -\n alibi_start_q[:, None]) * alibi_slope\n alibi = tl.where(\n (alibi <= 0) & (alibi_start_q[:, None] < cur_batch_seq_len),\n alibi, float(\"-inf\"))\n qk += alibi\n alibi_start_k += BLOCK_N\n\n # -- compute m_ij, p, l_ij\n m_ij = tl.max(qk, 1)\n m_i_new = tl.maximum(m_i, m_ij)\n p = tl.math.exp(qk - m_i_new[:, None])\n l_ij = tl.sum(p, 1)\n # -- update m_i and l_i\n\n alpha = tl.math.exp(m_i - m_i_new)\n l_i_new = alpha * l_i + l_ij\n # -- update output accumulator --\n # scale p\n # scale acc\n acc_scale = alpha\n # acc_scale = l_i / l_i_new * alpha\n acc = acc * acc_scale[:, None]\n # update acc\n v = tl.load(v_ptrs +\n (cur_batch_in_all_start_index + start_n) * stride_vbs,\n mask=(start_n + offs_n[:, None]) <\n cur_batch_seq_len - cur_batch_ctx_len,\n other=0.0)\n\n p = p.to(v.dtype)\n acc += tl.dot(p, v, allow_tf32=False)\n # update m_i and l_i\n l_i = l_i_new\n m_i = m_i_new\n\n acc = acc / l_i[:, None]\n\n # initialize pointers to output\n off_o = (\n (cur_batch_in_all_start_index + offs_m[:, None]) * stride_obs +\n cur_head * stride_oh + offs_d[None, :] * stride_od)\n out_ptrs = Out + off_o\n tl.store(out_ptrs,\n acc,\n mask=offs_m[:, None] < cur_batch_seq_len - cur_batch_ctx_len)\n return\n\n @torch.inference_mode()\n def context_attention_fwd(q,\n k,\n v,\n o,\n k_cache,\n v_cache,\n b_loc,\n b_start_loc,\n b_seq_len,\n b_ctx_len,\n max_input_len,\n alibi_slopes=None):\n\n cap = torch.cuda.get_device_capability()\n BLOCK = 128 if cap[0] >= 8 else 64\n # shape constraints\n Lq, Lk, Lv = q.shape[-1], k.shape[-1], v.shape[-1]\n assert Lq == Lk and Lk == Lv\n # round up Lk to a power of 2 - this is required for Triton block size\n Lk_padded = 2**((Lk - 1).bit_length())\n\n sm_scale = 1.0 / (Lq**0.5)\n batch, head = b_seq_len.shape[0], q.shape[1]\n num_queries_per_kv = q.shape[1] // k.shape[1]\n\n grid = (batch, head, triton.cdiv(max_input_len, BLOCK)) # batch, head,\n\n num_warps = 8 if Lk <= 64 else 8\n if alibi_slopes is not None:\n assert Lk == Lk_padded\n _fwd_kernel_alibi[grid](\n q,\n k,\n v,\n k_cache,\n v_cache,\n b_loc,\n sm_scale,\n b_start_loc,\n b_seq_len,\n b_ctx_len,\n alibi_slopes,\n v_cache.shape[3],\n 8,\n o,\n b_loc.stride(0),\n b_loc.stride(1),\n q.stride(0),\n q.stride(1),\n q.stride(2),\n k.stride(0),\n k.stride(1),\n k.stride(2),\n v.stride(0),\n v.stride(1),\n v.stride(2),\n o.stride(0),\n o.stride(1),\n o.stride(2),\n k_cache.stride(0),\n k_cache.stride(1),\n k_cache.stride(2),\n k_cache.stride(3),\n k_cache.stride(\n 4\n ), #[num_blocks, num_kv_heads, head_size/x, block_size, x]\n v_cache.stride(0),\n v_cache.stride(1),\n v_cache.stride(2),\n v_cache.stride(\n 3), #[num_blocks, num_kv_heads, head_size, block_size]\n num_queries_per_kv=num_queries_per_kv,\n BLOCK_M=BLOCK,\n BLOCK_DMODEL=Lk,\n BLOCK_N=BLOCK,\n num_warps=num_warps,\n num_stages=1,\n )\n return\n\n _fwd_kernel[grid](\n q,\n k,\n v,\n k_cache,\n v_cache,\n b_loc,\n sm_scale,\n b_start_loc,\n b_seq_len,\n b_ctx_len,\n v_cache.shape[3],\n 8,\n o,\n b_loc.stride(0),\n b_loc.stride(1),\n q.stride(0),\n q.stride(1),\n q.stride(2),\n k.stride(0),\n k.stride(1),\n k.stride(2),\n v.stride(0),\n v.stride(1),\n v.stride(2),\n o.stride(0),\n o.stride(1),\n o.stride(2),\n k_cache.stride(0),\n k_cache.stride(1),\n k_cache.stride(2),\n k_cache.stride(3),\n k_cache.stride(\n 4), #[num_blocks, num_kv_heads, head_size/x, block_size, x]\n v_cache.stride(0),\n v_cache.stride(1),\n v_cache.stride(2),\n v_cache.stride(\n 3), #[num_blocks, num_kv_heads, head_size, block_size]\n num_queries_per_kv=num_queries_per_kv,\n BLOCK_M=BLOCK,\n BLOCK_DMODEL=Lk,\n BLOCK_DMODEL_PADDED=Lk_padded,\n BLOCK_N=BLOCK,\n num_warps=num_warps,\n num_stages=1,\n )\n return\n", "path": "vllm/attention/ops/prefix_prefill.py" } ]
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 --------------------------------------------------------------\n\n# If extensions (or modules to document with autodoc) are in another directory,\n# add these directories to sys.path here. If the directory is relative to the\n# documentation root, use os.path.abspath to make it absolute, like shown here.\n\nimport logging\nimport sys\nfrom typing import List\n\nfrom sphinx.ext import autodoc\n\nlogger = logging.getLogger(__name__)\n\n# -- Project information -----------------------------------------------------\n\nproject = 'vLLM'\ncopyright = '2024, vLLM Team'\nauthor = 'the vLLM Team'\n\n# -- General configuration ---------------------------------------------------\n\n# Add any Sphinx extension module names here, as strings. They can be\n# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom\n# ones.\nextensions = [\n \"sphinx.ext.napoleon\",\n \"sphinx.ext.viewcode\",\n \"sphinx.ext.intersphinx\",\n \"sphinx_copybutton\",\n \"sphinx.ext.autodoc\",\n \"sphinx.ext.autosummary\",\n \"myst_parser\",\n \"sphinxarg.ext\",\n]\n\n# Add any paths that contain templates here, relative to this directory.\ntemplates_path = ['_templates']\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\n# This pattern also affects html_static_path and html_extra_path.\nexclude_patterns: List[str] = []\n\n# Exclude the prompt \"$\" when copying code\ncopybutton_prompt_text = r\"\\$ \"\ncopybutton_prompt_is_regexp = True\n\n# -- Options for HTML output -------------------------------------------------\n\n# The theme to use for HTML and HTML Help pages. See the documentation for\n# a list of builtin themes.\n#\nhtml_title = project\nhtml_theme = 'sphinx_book_theme'\nhtml_logo = 'assets/logos/vllm-logo-text-light.png'\nhtml_theme_options = {\n 'path_to_docs': 'docs/source',\n 'repository_url': 'https://github.com/vllm-project/vllm',\n 'use_repository_button': True,\n}\n\n# Add any paths that contain custom static files (such as style sheets) here,\n# relative to this directory. They are copied after the builtin static files,\n# so a file named \"default.css\" will overwrite the builtin \"default.css\".\n# html_static_path = ['_static']\n\n# Mock out external dependencies here.\nautodoc_mock_imports = [\n \"cpuinfo\",\n \"torch\",\n \"transformers\",\n \"psutil\",\n \"prometheus_client\",\n \"sentencepiece\",\n \"vllm.cuda_utils\",\n \"vllm._C\",\n \"numpy\",\n \"tqdm\",\n \"tensorizer\",\n]\n\nfor mock_target in autodoc_mock_imports:\n if mock_target in sys.modules:\n logger.info(\n f\"Potentially problematic mock target ({mock_target}) found; \"\n \"autodoc_mock_imports cannot mock modules that have already \"\n \"been loaded into sys.modules when the sphinx build starts.\")\n\n\nclass MockedClassDocumenter(autodoc.ClassDocumenter):\n \"\"\"Remove note about base class when a class is derived from object.\"\"\"\n\n def add_line(self, line: str, source: str, *lineno: int) -> None:\n if line == \" Bases: :py:class:`object`\":\n return\n super().add_line(line, source, *lineno)\n\n\nautodoc.ClassDocumenter = MockedClassDocumenter\n\nnavigation_with_keys = False\n", "path": "docs/source/conf.py" }, { "content": "import argparse\nimport dataclasses\nfrom dataclasses import dataclass\nfrom typing import Optional\n\nfrom vllm.config import (CacheConfig, DecodingConfig, DeviceConfig,\n EngineConfig, LoadConfig, LoRAConfig, ModelConfig,\n ParallelConfig, SchedulerConfig, SpeculativeConfig,\n TokenizerPoolConfig, VisionLanguageConfig)\nfrom vllm.model_executor.layers.quantization import QUANTIZATION_METHODS\nfrom vllm.utils import str_to_int_tuple\n\n\n@dataclass\nclass EngineArgs:\n \"\"\"Arguments for vLLM engine.\"\"\"\n model: str\n tokenizer: Optional[str] = None\n tokenizer_mode: str = 'auto'\n trust_remote_code: bool = False\n download_dir: Optional[str] = None\n load_format: str = 'auto'\n dtype: str = 'auto'\n kv_cache_dtype: str = 'auto'\n quantization_param_path: Optional[str] = None\n seed: int = 0\n max_model_len: Optional[int] = None\n worker_use_ray: bool = False\n pipeline_parallel_size: int = 1\n tensor_parallel_size: int = 1\n max_parallel_loading_workers: Optional[int] = None\n block_size: int = 16\n enable_prefix_caching: bool = False\n use_v2_block_manager: bool = False\n swap_space: int = 4 # GiB\n gpu_memory_utilization: float = 0.90\n max_num_batched_tokens: Optional[int] = None\n max_num_seqs: int = 256\n max_logprobs: int = 5 # OpenAI default value\n disable_log_stats: bool = False\n revision: Optional[str] = None\n code_revision: Optional[str] = None\n tokenizer_revision: Optional[str] = None\n quantization: Optional[str] = None\n enforce_eager: bool = False\n max_context_len_to_capture: int = 8192\n disable_custom_all_reduce: bool = False\n tokenizer_pool_size: int = 0\n tokenizer_pool_type: str = \"ray\"\n tokenizer_pool_extra_config: Optional[dict] = None\n enable_lora: bool = False\n max_loras: int = 1\n max_lora_rank: int = 16\n lora_extra_vocab_size: int = 256\n lora_dtype = 'auto'\n max_cpu_loras: Optional[int] = None\n device: str = 'auto'\n ray_workers_use_nsight: bool = False\n num_gpu_blocks_override: Optional[int] = None\n num_lookahead_slots: int = 0\n model_loader_extra_config: Optional[dict] = None\n\n # Related to Vision-language models such as llava\n image_input_type: Optional[str] = None\n image_token_id: Optional[int] = None\n image_input_shape: Optional[str] = None\n image_feature_size: Optional[int] = None\n scheduler_delay_factor: float = 0.0\n enable_chunked_prefill: bool = False\n\n guided_decoding_backend: str = 'outlines'\n # Speculative decoding configuration.\n speculative_model: Optional[str] = None\n num_speculative_tokens: Optional[int] = None\n\n def __post_init__(self):\n if self.tokenizer is None:\n self.tokenizer = self.model\n\n @staticmethod\n def add_cli_args(\n parser: argparse.ArgumentParser) -> argparse.ArgumentParser:\n \"\"\"Shared CLI arguments for vLLM engine.\"\"\"\n\n # NOTE: If you update any of the arguments below, please also\n # make sure to update docs/source/models/engine_args.rst\n\n # Model arguments\n parser.add_argument(\n '--model',\n type=str,\n default='facebook/opt-125m',\n help='name or path of the huggingface model to use')\n parser.add_argument(\n '--tokenizer',\n type=str,\n default=EngineArgs.tokenizer,\n help='name or path of the huggingface tokenizer to use')\n parser.add_argument(\n '--revision',\n type=str,\n default=None,\n help='the specific model version to use. It can be a branch '\n 'name, a tag name, or a commit id. If unspecified, will use '\n 'the default version.')\n parser.add_argument(\n '--code-revision',\n type=str,\n default=None,\n help='the specific revision to use for the model code on '\n 'Hugging Face Hub. It can be a branch name, a tag name, or a '\n 'commit id. If unspecified, will use the default version.')\n parser.add_argument(\n '--tokenizer-revision',\n type=str,\n default=None,\n help='the specific tokenizer version to use. It can be a branch '\n 'name, a tag name, or a commit id. If unspecified, will use '\n 'the default version.')\n parser.add_argument('--tokenizer-mode',\n type=str,\n default=EngineArgs.tokenizer_mode,\n choices=['auto', 'slow'],\n help='tokenizer mode. \"auto\" will use the fast '\n 'tokenizer if available, and \"slow\" will '\n 'always use the slow tokenizer.')\n parser.add_argument('--trust-remote-code',\n action='store_true',\n help='trust remote code from huggingface')\n parser.add_argument('--download-dir',\n type=str,\n default=EngineArgs.download_dir,\n help='directory to download and load the weights, '\n 'default to the default cache dir of '\n 'huggingface')\n parser.add_argument(\n '--load-format',\n type=str,\n default=EngineArgs.load_format,\n choices=[\n 'auto', 'pt', 'safetensors', 'npcache', 'dummy', 'tensorizer'\n ],\n help='The format of the model weights to load. '\n '\"auto\" will try to load the weights in the safetensors format '\n 'and fall back to the pytorch bin format if safetensors format '\n '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 '\n 'a numpy cache to speed up the loading. '\n '\"dummy\" will initialize the weights with random values, '\n 'which is mainly for profiling.'\n '\"tensorizer\" will load the weights using tensorizer from CoreWeave'\n 'which assumes tensorizer_uri is set to the location of the '\n 'serialized weights.')\n parser.add_argument(\n '--dtype',\n type=str,\n default=EngineArgs.dtype,\n choices=[\n 'auto', 'half', 'float16', 'bfloat16', 'float', 'float32'\n ],\n help='data type for model weights and activations. '\n 'The \"auto\" option will use FP16 precision '\n 'for FP32 and FP16 models, and BF16 precision '\n 'for BF16 models.')\n parser.add_argument(\n '--kv-cache-dtype',\n type=str,\n choices=['auto', 'fp8'],\n default=EngineArgs.kv_cache_dtype,\n help='Data type for kv cache storage. If \"auto\", will use model '\n 'data type. FP8_E5M2 (without scaling) is only supported on cuda '\n 'version greater than 11.8. On ROCm (AMD GPU), FP8_E4M3 is instead '\n 'supported for common inference criteria. ')\n parser.add_argument(\n '--quantization-param-path',\n type=str,\n default=None,\n help='Path to the JSON file containing the KV cache '\n 'scaling factors. This should generally be supplied, when '\n 'KV cache dtype is FP8. Otherwise, KV cache scaling factors '\n 'default to 1.0, which may cause accuracy issues. '\n 'FP8_E5M2 (without scaling) is only supported on cuda version'\n 'greater than 11.8. On ROCm (AMD GPU), FP8_E4M3 is instead '\n 'supported for common inference criteria. ')\n parser.add_argument('--max-model-len',\n type=int,\n default=EngineArgs.max_model_len,\n help='model context length. If unspecified, '\n 'will be automatically derived from the model.')\n parser.add_argument(\n '--guided-decoding-backend',\n type=str,\n default='outlines',\n choices=['outlines', 'lm-format-enforcer'],\n help='Which engine will be used for guided decoding'\n ' (JSON schema / regex etc)')\n # Parallel arguments\n parser.add_argument('--worker-use-ray',\n action='store_true',\n help='use Ray for distributed serving, will be '\n 'automatically set when using more than 1 GPU')\n parser.add_argument('--pipeline-parallel-size',\n '-pp',\n type=int,\n default=EngineArgs.pipeline_parallel_size,\n help='number of pipeline stages')\n parser.add_argument('--tensor-parallel-size',\n '-tp',\n type=int,\n default=EngineArgs.tensor_parallel_size,\n help='number of tensor parallel replicas')\n parser.add_argument(\n '--max-parallel-loading-workers',\n type=int,\n default=EngineArgs.max_parallel_loading_workers,\n help='load model sequentially in multiple batches, '\n 'to avoid RAM OOM when using tensor '\n 'parallel and large models')\n parser.add_argument(\n '--ray-workers-use-nsight',\n action='store_true',\n help='If specified, use nsight to profile ray workers')\n # KV cache arguments\n parser.add_argument('--block-size',\n type=int,\n default=EngineArgs.block_size,\n choices=[8, 16, 32, 128],\n help='token block size')\n\n parser.add_argument('--enable-prefix-caching',\n action='store_true',\n help='Enables automatic prefix caching')\n parser.add_argument('--use-v2-block-manager',\n action='store_true',\n help='Use BlockSpaceMangerV2')\n parser.add_argument(\n '--num-lookahead-slots',\n type=int,\n default=EngineArgs.num_lookahead_slots,\n help='Experimental scheduling config necessary for '\n 'speculative decoding. This will be replaced by '\n 'speculative config in the future; it is present '\n 'to enable correctness tests until then.')\n\n parser.add_argument('--seed',\n type=int,\n default=EngineArgs.seed,\n help='random seed')\n parser.add_argument('--swap-space',\n type=int,\n default=EngineArgs.swap_space,\n help='CPU swap space size (GiB) per GPU')\n parser.add_argument(\n '--gpu-memory-utilization',\n type=float,\n default=EngineArgs.gpu_memory_utilization,\n help='the fraction of GPU memory to be used for '\n 'the model executor, which can range from 0 to 1.'\n 'If unspecified, will use the default value of 0.9.')\n parser.add_argument(\n '--num-gpu-blocks-override',\n type=int,\n default=None,\n help='If specified, ignore GPU profiling result and use this number'\n 'of GPU blocks. Used for testing preemption.')\n parser.add_argument('--max-num-batched-tokens',\n type=int,\n default=EngineArgs.max_num_batched_tokens,\n help='maximum number of batched tokens per '\n 'iteration')\n parser.add_argument('--max-num-seqs',\n type=int,\n default=EngineArgs.max_num_seqs,\n help='maximum number of sequences per iteration')\n parser.add_argument(\n '--max-logprobs',\n type=int,\n default=EngineArgs.max_logprobs,\n help=('max number of log probs to return logprobs is specified in'\n ' SamplingParams'))\n parser.add_argument('--disable-log-stats',\n action='store_true',\n help='disable logging statistics')\n # Quantization settings.\n parser.add_argument('--quantization',\n '-q',\n type=str,\n choices=[*QUANTIZATION_METHODS, None],\n default=EngineArgs.quantization,\n help='Method used to quantize the weights. If '\n 'None, we first check the `quantization_config` '\n 'attribute in the model config file. If that is '\n 'None, we assume the model weights are not '\n 'quantized and use `dtype` to determine the data '\n 'type of the weights.')\n parser.add_argument('--enforce-eager',\n action='store_true',\n help='Always use eager-mode PyTorch. If False, '\n 'will use eager mode and CUDA graph in hybrid '\n 'for maximal performance and flexibility.')\n parser.add_argument('--max-context-len-to-capture',\n type=int,\n default=EngineArgs.max_context_len_to_capture,\n help='maximum context length covered by CUDA '\n 'graphs. When a sequence has context length '\n 'larger than this, we fall back to eager mode.')\n parser.add_argument('--disable-custom-all-reduce',\n action='store_true',\n default=EngineArgs.disable_custom_all_reduce,\n help='See ParallelConfig')\n parser.add_argument('--tokenizer-pool-size',\n type=int,\n default=EngineArgs.tokenizer_pool_size,\n help='Size of tokenizer pool to use for '\n 'asynchronous tokenization. If 0, will '\n 'use synchronous tokenization.')\n parser.add_argument('--tokenizer-pool-type',\n type=str,\n default=EngineArgs.tokenizer_pool_type,\n help='Type of tokenizer pool to use for '\n 'asynchronous tokenization. Ignored '\n 'if tokenizer_pool_size is 0.')\n parser.add_argument('--tokenizer-pool-extra-config',\n type=str,\n default=EngineArgs.tokenizer_pool_extra_config,\n help='Extra config for tokenizer pool. '\n 'This should be a JSON string that will be '\n 'parsed into a dictionary. Ignored if '\n 'tokenizer_pool_size is 0.')\n # LoRA related configs\n parser.add_argument('--enable-lora',\n action='store_true',\n help='If True, enable handling of LoRA adapters.')\n parser.add_argument('--max-loras',\n type=int,\n default=EngineArgs.max_loras,\n help='Max number of LoRAs in a single batch.')\n parser.add_argument('--max-lora-rank',\n type=int,\n default=EngineArgs.max_lora_rank,\n help='Max LoRA rank.')\n parser.add_argument(\n '--lora-extra-vocab-size',\n type=int,\n default=EngineArgs.lora_extra_vocab_size,\n help=('Maximum size of extra vocabulary that can be '\n 'present in a LoRA adapter (added to the base '\n 'model vocabulary).'))\n parser.add_argument(\n '--lora-dtype',\n type=str,\n default=EngineArgs.lora_dtype,\n choices=['auto', 'float16', 'bfloat16', 'float32'],\n help=('Data type for LoRA. If auto, will default to '\n 'base model dtype.'))\n parser.add_argument(\n '--max-cpu-loras',\n type=int,\n default=EngineArgs.max_cpu_loras,\n help=('Maximum number of LoRAs to store in CPU memory. '\n 'Must be >= than max_num_seqs. '\n 'Defaults to max_num_seqs.'))\n parser.add_argument(\"--device\",\n type=str,\n default=EngineArgs.device,\n choices=[\"auto\", \"cuda\", \"neuron\", \"cpu\"],\n help='Device type for vLLM execution.')\n # Related to Vision-language models such as llava\n parser.add_argument(\n '--image-input-type',\n type=str,\n default=None,\n choices=[\n t.name.lower() for t in VisionLanguageConfig.ImageInputType\n ],\n help=('The image input type passed into vLLM. '\n 'Should be one of \"pixel_values\" or \"image_features\".'))\n parser.add_argument('--image-token-id',\n type=int,\n default=None,\n help=('Input id for image token.'))\n parser.add_argument(\n '--image-input-shape',\n type=str,\n default=None,\n help=('The biggest image input shape (worst for memory footprint) '\n 'given an input type. Only used for vLLM\\'s profile_run.'))\n parser.add_argument(\n '--image-feature-size',\n type=int,\n default=None,\n help=('The image feature size along the context dimension.'))\n parser.add_argument(\n '--scheduler-delay-factor',\n type=float,\n default=EngineArgs.scheduler_delay_factor,\n help='Apply a delay (of delay factor multiplied by previous'\n 'prompt latency) before scheduling next prompt.')\n parser.add_argument(\n '--enable-chunked-prefill',\n action='store_true',\n help='If set, the prefill requests can be chunked based on the '\n 'max_num_batched_tokens')\n\n parser.add_argument(\n '--speculative-model',\n type=str,\n default=None,\n help=\n 'The name of the draft model to be used in speculative decoding.')\n\n parser.add_argument(\n '--num-speculative-tokens',\n type=int,\n default=None,\n help='The number of speculative tokens to sample from '\n 'the draft model in speculative decoding')\n\n parser.add_argument('--model-loader-extra-config',\n type=str,\n default=EngineArgs.model_loader_extra_config,\n help='Extra config for model loader. '\n 'This will be passed to the model loader '\n 'corresponding to the chosen load_format. '\n 'This should be a JSON string that will be '\n 'parsed into a dictionary.')\n\n return parser\n\n @classmethod\n def from_cli_args(cls, args: argparse.Namespace) -> 'EngineArgs':\n # Get the list of attributes of this dataclass.\n attrs = [attr.name for attr in dataclasses.fields(cls)]\n # Set the attributes from the parsed arguments.\n engine_args = cls(**{attr: getattr(args, attr) for attr in attrs})\n return engine_args\n\n def create_engine_config(self, ) -> EngineConfig:\n device_config = DeviceConfig(self.device)\n model_config = ModelConfig(\n self.model, self.tokenizer, self.tokenizer_mode,\n self.trust_remote_code, self.dtype, self.seed, self.revision,\n self.code_revision, self.tokenizer_revision, self.max_model_len,\n self.quantization, self.quantization_param_path,\n self.enforce_eager, self.max_context_len_to_capture,\n self.max_logprobs)\n cache_config = CacheConfig(self.block_size,\n self.gpu_memory_utilization,\n self.swap_space, self.kv_cache_dtype,\n self.num_gpu_blocks_override,\n model_config.get_sliding_window(),\n self.enable_prefix_caching)\n parallel_config = ParallelConfig(\n self.pipeline_parallel_size, self.tensor_parallel_size,\n self.worker_use_ray, self.max_parallel_loading_workers,\n self.disable_custom_all_reduce,\n TokenizerPoolConfig.create_config(\n self.tokenizer_pool_size,\n self.tokenizer_pool_type,\n self.tokenizer_pool_extra_config,\n ), self.ray_workers_use_nsight)\n\n speculative_config = SpeculativeConfig.maybe_create_spec_config(\n target_model_config=model_config,\n target_parallel_config=parallel_config,\n target_dtype=self.dtype,\n speculative_model=self.speculative_model,\n num_speculative_tokens=self.num_speculative_tokens,\n )\n\n scheduler_config = SchedulerConfig(\n self.max_num_batched_tokens,\n self.max_num_seqs,\n model_config.max_model_len,\n self.use_v2_block_manager,\n num_lookahead_slots=(self.num_lookahead_slots\n if speculative_config is None else\n speculative_config.num_lookahead_slots),\n delay_factor=self.scheduler_delay_factor,\n enable_chunked_prefill=self.enable_chunked_prefill,\n )\n lora_config = LoRAConfig(\n max_lora_rank=self.max_lora_rank,\n max_loras=self.max_loras,\n lora_extra_vocab_size=self.lora_extra_vocab_size,\n lora_dtype=self.lora_dtype,\n max_cpu_loras=self.max_cpu_loras if self.max_cpu_loras\n and self.max_cpu_loras > 0 else None) if self.enable_lora else None\n\n load_config = LoadConfig(\n load_format=self.load_format,\n download_dir=self.download_dir,\n model_loader_extra_config=self.model_loader_extra_config,\n )\n\n if self.image_input_type:\n if (not self.image_token_id or not self.image_input_shape\n or not self.image_feature_size):\n raise ValueError(\n 'Specify `image_token_id`, `image_input_shape` and '\n '`image_feature_size` together with `image_input_type`.')\n vision_language_config = VisionLanguageConfig(\n image_input_type=VisionLanguageConfig.\n get_image_input_enum_type(self.image_input_type),\n image_token_id=self.image_token_id,\n image_input_shape=str_to_int_tuple(self.image_input_shape),\n image_feature_size=self.image_feature_size,\n )\n else:\n vision_language_config = None\n\n decoding_config = DecodingConfig(\n guided_decoding_backend=self.guided_decoding_backend)\n\n return EngineConfig(model_config=model_config,\n cache_config=cache_config,\n parallel_config=parallel_config,\n scheduler_config=scheduler_config,\n device_config=device_config,\n lora_config=lora_config,\n vision_language_config=vision_language_config,\n speculative_config=speculative_config,\n load_config=load_config,\n decoding_config=decoding_config)\n\n\n@dataclass\nclass AsyncEngineArgs(EngineArgs):\n \"\"\"Arguments for asynchronous vLLM engine.\"\"\"\n engine_use_ray: bool = False\n disable_log_requests: bool = False\n max_log_len: Optional[int] = None\n\n @staticmethod\n def add_cli_args(\n parser: argparse.ArgumentParser) -> argparse.ArgumentParser:\n parser = EngineArgs.add_cli_args(parser)\n parser.add_argument('--engine-use-ray',\n action='store_true',\n help='use Ray to start the LLM engine in a '\n 'separate process as the server process.')\n parser.add_argument('--disable-log-requests',\n action='store_true',\n help='disable logging requests')\n parser.add_argument('--max-log-len',\n type=int,\n default=None,\n help='max number of prompt characters or prompt '\n 'ID numbers being printed in log. '\n 'Default: unlimited.')\n return parser\n", "path": "vllm/engine/arg_utils.py" } ]
[ { "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 --------------------------------------------------------------\n\n# If extensions (or modules to document with autodoc) are in another directory,\n# add these directories to sys.path here. If the directory is relative to the\n# documentation root, use os.path.abspath to make it absolute, like shown here.\n\nimport logging\nimport os\nimport sys\nfrom typing import List\n\nfrom sphinx.ext import autodoc\n\nlogger = logging.getLogger(__name__)\nsys.path.append(os.path.abspath(\"../..\"))\n\n# -- Project information -----------------------------------------------------\n\nproject = 'vLLM'\ncopyright = '2024, vLLM Team'\nauthor = 'the vLLM Team'\n\n# -- General configuration ---------------------------------------------------\n\n# Add any Sphinx extension module names here, as strings. They can be\n# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom\n# ones.\nextensions = [\n \"sphinx.ext.napoleon\",\n \"sphinx.ext.viewcode\",\n \"sphinx.ext.intersphinx\",\n \"sphinx_copybutton\",\n \"sphinx.ext.autodoc\",\n \"sphinx.ext.autosummary\",\n \"myst_parser\",\n \"sphinxarg.ext\",\n]\n\n# Add any paths that contain templates here, relative to this directory.\ntemplates_path = ['_templates']\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\n# This pattern also affects html_static_path and html_extra_path.\nexclude_patterns: List[str] = []\n\n# Exclude the prompt \"$\" when copying code\ncopybutton_prompt_text = r\"\\$ \"\ncopybutton_prompt_is_regexp = True\n\n# -- Options for HTML output -------------------------------------------------\n\n# The theme to use for HTML and HTML Help pages. See the documentation for\n# a list of builtin themes.\n#\nhtml_title = project\nhtml_theme = 'sphinx_book_theme'\nhtml_logo = 'assets/logos/vllm-logo-text-light.png'\nhtml_theme_options = {\n 'path_to_docs': 'docs/source',\n 'repository_url': 'https://github.com/vllm-project/vllm',\n 'use_repository_button': True,\n}\n\n# Add any paths that contain custom static files (such as style sheets) here,\n# relative to this directory. They are copied after the builtin static files,\n# so a file named \"default.css\" will overwrite the builtin \"default.css\".\n# html_static_path = ['_static']\n\n# Mock out external dependencies here.\nautodoc_mock_imports = [\n \"cpuinfo\",\n \"torch\",\n \"transformers\",\n \"psutil\",\n \"prometheus_client\",\n \"sentencepiece\",\n \"vllm.cuda_utils\",\n \"vllm._C\",\n \"numpy\",\n \"tqdm\",\n \"tensorizer\",\n]\n\nfor mock_target in autodoc_mock_imports:\n if mock_target in sys.modules:\n logger.info(\n f\"Potentially problematic mock target ({mock_target}) found; \"\n \"autodoc_mock_imports cannot mock modules that have already \"\n \"been loaded into sys.modules when the sphinx build starts.\")\n\n\nclass MockedClassDocumenter(autodoc.ClassDocumenter):\n \"\"\"Remove note about base class when a class is derived from object.\"\"\"\n\n def add_line(self, line: str, source: str, *lineno: int) -> None:\n if line == \" Bases: :py:class:`object`\":\n return\n super().add_line(line, source, *lineno)\n\n\nautodoc.ClassDocumenter = MockedClassDocumenter\n\nnavigation_with_keys = False\n", "path": "docs/source/conf.py" }, { "content": "import argparse\nimport dataclasses\nfrom dataclasses import dataclass\nfrom typing import Optional\n\nfrom vllm.config import (CacheConfig, DecodingConfig, DeviceConfig,\n EngineConfig, LoadConfig, LoRAConfig, ModelConfig,\n ParallelConfig, SchedulerConfig, SpeculativeConfig,\n TokenizerPoolConfig, VisionLanguageConfig)\nfrom vllm.model_executor.layers.quantization import QUANTIZATION_METHODS\nfrom vllm.utils import str_to_int_tuple\n\n\n@dataclass\nclass EngineArgs:\n \"\"\"Arguments for vLLM engine.\"\"\"\n model: str\n tokenizer: Optional[str] = None\n tokenizer_mode: str = 'auto'\n trust_remote_code: bool = False\n download_dir: Optional[str] = None\n load_format: str = 'auto'\n dtype: str = 'auto'\n kv_cache_dtype: str = 'auto'\n quantization_param_path: Optional[str] = None\n seed: int = 0\n max_model_len: Optional[int] = None\n worker_use_ray: bool = False\n pipeline_parallel_size: int = 1\n tensor_parallel_size: int = 1\n max_parallel_loading_workers: Optional[int] = None\n block_size: int = 16\n enable_prefix_caching: bool = False\n use_v2_block_manager: bool = False\n swap_space: int = 4 # GiB\n gpu_memory_utilization: float = 0.90\n max_num_batched_tokens: Optional[int] = None\n max_num_seqs: int = 256\n max_logprobs: int = 5 # OpenAI default value\n disable_log_stats: bool = False\n revision: Optional[str] = None\n code_revision: Optional[str] = None\n tokenizer_revision: Optional[str] = None\n quantization: Optional[str] = None\n enforce_eager: bool = False\n max_context_len_to_capture: int = 8192\n disable_custom_all_reduce: bool = False\n tokenizer_pool_size: int = 0\n tokenizer_pool_type: str = \"ray\"\n tokenizer_pool_extra_config: Optional[dict] = None\n enable_lora: bool = False\n max_loras: int = 1\n max_lora_rank: int = 16\n lora_extra_vocab_size: int = 256\n lora_dtype = 'auto'\n max_cpu_loras: Optional[int] = None\n device: str = 'auto'\n ray_workers_use_nsight: bool = False\n num_gpu_blocks_override: Optional[int] = None\n num_lookahead_slots: int = 0\n model_loader_extra_config: Optional[dict] = None\n\n # Related to Vision-language models such as llava\n image_input_type: Optional[str] = None\n image_token_id: Optional[int] = None\n image_input_shape: Optional[str] = None\n image_feature_size: Optional[int] = None\n scheduler_delay_factor: float = 0.0\n enable_chunked_prefill: bool = False\n\n guided_decoding_backend: str = 'outlines'\n # Speculative decoding configuration.\n speculative_model: Optional[str] = None\n num_speculative_tokens: Optional[int] = None\n\n def __post_init__(self):\n if self.tokenizer is None:\n self.tokenizer = self.model\n\n @staticmethod\n def add_cli_args(\n parser: argparse.ArgumentParser) -> argparse.ArgumentParser:\n \"\"\"Shared CLI arguments for vLLM engine.\"\"\"\n\n # Model arguments\n parser.add_argument(\n '--model',\n type=str,\n default='facebook/opt-125m',\n help='Name or path of the huggingface model to use.')\n parser.add_argument(\n '--tokenizer',\n type=str,\n default=EngineArgs.tokenizer,\n help='Name or path of the huggingface tokenizer to use.')\n parser.add_argument(\n '--revision',\n type=str,\n default=None,\n help='The specific model version to use. It can be a branch '\n 'name, a tag name, or a commit id. If unspecified, will use '\n 'the default version.')\n parser.add_argument(\n '--code-revision',\n type=str,\n default=None,\n help='The specific revision to use for the model code on '\n 'Hugging Face Hub. It can be a branch name, a tag name, or a '\n 'commit id. If unspecified, will use the default version.')\n parser.add_argument(\n '--tokenizer-revision',\n type=str,\n default=None,\n help='The specific tokenizer version to use. It can be a branch '\n 'name, a tag name, or a commit id. If unspecified, will use '\n 'the default version.')\n parser.add_argument(\n '--tokenizer-mode',\n type=str,\n default=EngineArgs.tokenizer_mode,\n choices=['auto', 'slow'],\n help='The tokenizer mode.\\n\\n* \"auto\" will use the '\n 'fast tokenizer if available.\\n* \"slow\" will '\n 'always use the slow tokenizer.')\n parser.add_argument('--trust-remote-code',\n action='store_true',\n help='Trust remote code from huggingface.')\n parser.add_argument('--download-dir',\n type=str,\n default=EngineArgs.download_dir,\n help='Directory to download and load the weights, '\n 'default to the default cache dir of '\n 'huggingface.')\n parser.add_argument(\n '--load-format',\n type=str,\n default=EngineArgs.load_format,\n choices=[\n 'auto', 'pt', 'safetensors', 'npcache', 'dummy', 'tensorizer'\n ],\n help='The format of the model weights to load.\\n\\n'\n '* \"auto\" will try to load the weights in the safetensors format '\n 'and fall back to the pytorch bin format if safetensors format '\n 'is not available.\\n'\n '* \"pt\" will load the weights in the pytorch bin format.\\n'\n '* \"safetensors\" will load the weights in the safetensors format.\\n'\n '* \"npcache\" will load the weights in pytorch format and store '\n 'a numpy cache to speed up the loading.\\n'\n '* \"dummy\" will initialize the weights with random values, '\n 'which is mainly for profiling.\\n'\n '* \"tensorizer\" will load the weights using tensorizer from '\n 'CoreWeave which assumes tensorizer_uri is set to the location of '\n 'the serialized weights.')\n parser.add_argument(\n '--dtype',\n type=str,\n default=EngineArgs.dtype,\n choices=[\n 'auto', 'half', 'float16', 'bfloat16', 'float', 'float32'\n ],\n help='Data type for model weights and activations.\\n\\n'\n '* \"auto\" will use FP16 precision for FP32 and FP16 models, and '\n 'BF16 precision for BF16 models.\\n'\n '* \"half\" for FP16. Recommended for AWQ quantization.\\n'\n '* \"float16\" is the same as \"half\".\\n'\n '* \"bfloat16\" for a balance between precision and range.\\n'\n '* \"float\" is shorthand for FP32 precision.\\n'\n '* \"float32\" for FP32 precision.')\n parser.add_argument(\n '--kv-cache-dtype',\n type=str,\n choices=['auto', 'fp8'],\n default=EngineArgs.kv_cache_dtype,\n help='Data type for kv cache storage. If \"auto\", will use model '\n 'data type. FP8_E5M2 (without scaling) is only supported on cuda '\n 'version greater than 11.8. On ROCm (AMD GPU), FP8_E4M3 is instead '\n 'supported for common inference criteria.')\n parser.add_argument(\n '--quantization-param-path',\n type=str,\n default=None,\n help='Path to the JSON file containing the KV cache '\n 'scaling factors. This should generally be supplied, when '\n 'KV cache dtype is FP8. Otherwise, KV cache scaling factors '\n 'default to 1.0, which may cause accuracy issues. '\n 'FP8_E5M2 (without scaling) is only supported on cuda version'\n 'greater than 11.8. On ROCm (AMD GPU), FP8_E4M3 is instead '\n 'supported for common inference criteria.')\n parser.add_argument('--max-model-len',\n type=int,\n default=EngineArgs.max_model_len,\n help='Model context length. If unspecified, will '\n 'be automatically derived from the model config.')\n parser.add_argument(\n '--guided-decoding-backend',\n type=str,\n default='outlines',\n choices=['outlines', 'lm-format-enforcer'],\n help='Which engine will be used for guided decoding'\n ' (JSON schema / regex etc).')\n # Parallel arguments\n parser.add_argument('--worker-use-ray',\n action='store_true',\n help='Use Ray for distributed serving, will be '\n 'automatically set when using more than 1 GPU.')\n parser.add_argument('--pipeline-parallel-size',\n '-pp',\n type=int,\n default=EngineArgs.pipeline_parallel_size,\n help='Number of pipeline stages.')\n parser.add_argument('--tensor-parallel-size',\n '-tp',\n type=int,\n default=EngineArgs.tensor_parallel_size,\n help='Number of tensor parallel replicas.')\n parser.add_argument(\n '--max-parallel-loading-workers',\n type=int,\n default=EngineArgs.max_parallel_loading_workers,\n help='Load model sequentially in multiple batches, '\n 'to avoid RAM OOM when using tensor '\n 'parallel and large models.')\n parser.add_argument(\n '--ray-workers-use-nsight',\n action='store_true',\n help='If specified, use nsight to profile Ray workers.')\n # KV cache arguments\n parser.add_argument('--block-size',\n type=int,\n default=EngineArgs.block_size,\n choices=[8, 16, 32, 128],\n help='Token block size for contiguous chunks of '\n 'tokens.')\n\n parser.add_argument('--enable-prefix-caching',\n action='store_true',\n help='Enables automatic prefix caching.')\n parser.add_argument('--use-v2-block-manager',\n action='store_true',\n help='Use BlockSpaceMangerV2.')\n parser.add_argument(\n '--num-lookahead-slots',\n type=int,\n default=EngineArgs.num_lookahead_slots,\n help='Experimental scheduling config necessary for '\n 'speculative decoding. This will be replaced by '\n 'speculative config in the future; it is present '\n 'to enable correctness tests until then.')\n\n parser.add_argument('--seed',\n type=int,\n default=EngineArgs.seed,\n help='Random seed for operations.')\n parser.add_argument('--swap-space',\n type=int,\n default=EngineArgs.swap_space,\n help='CPU swap space size (GiB) per GPU.')\n parser.add_argument(\n '--gpu-memory-utilization',\n type=float,\n default=EngineArgs.gpu_memory_utilization,\n help='The fraction of GPU memory to be used for the model '\n 'executor, which can range from 0 to 1. For example, a value of '\n '0.5 would imply 50%% GPU memory utilization. If unspecified, '\n 'will use the default value of 0.9.')\n parser.add_argument(\n '--num-gpu-blocks-override',\n type=int,\n default=None,\n help='If specified, ignore GPU profiling result and use this number'\n 'of GPU blocks. Used for testing preemption.')\n parser.add_argument('--max-num-batched-tokens',\n type=int,\n default=EngineArgs.max_num_batched_tokens,\n help='Maximum number of batched tokens per '\n 'iteration.')\n parser.add_argument('--max-num-seqs',\n type=int,\n default=EngineArgs.max_num_seqs,\n help='Maximum number of sequences per iteration.')\n parser.add_argument(\n '--max-logprobs',\n type=int,\n default=EngineArgs.max_logprobs,\n help=('Max number of log probs to return logprobs is specified in'\n ' SamplingParams.'))\n parser.add_argument('--disable-log-stats',\n action='store_true',\n help='Disable logging statistics.')\n # Quantization settings.\n parser.add_argument('--quantization',\n '-q',\n type=str,\n choices=[*QUANTIZATION_METHODS, None],\n default=EngineArgs.quantization,\n help='Method used to quantize the weights. If '\n 'None, we first check the `quantization_config` '\n 'attribute in the model config file. If that is '\n 'None, we assume the model weights are not '\n 'quantized and use `dtype` to determine the data '\n 'type of the weights.')\n parser.add_argument('--enforce-eager',\n action='store_true',\n help='Always use eager-mode PyTorch. If False, '\n 'will use eager mode and CUDA graph in hybrid '\n 'for maximal performance and flexibility.')\n parser.add_argument('--max-context-len-to-capture',\n type=int,\n default=EngineArgs.max_context_len_to_capture,\n help='Maximum context length covered by CUDA '\n 'graphs. When a sequence has context length '\n 'larger than this, we fall back to eager mode.')\n parser.add_argument('--disable-custom-all-reduce',\n action='store_true',\n default=EngineArgs.disable_custom_all_reduce,\n help='See ParallelConfig.')\n parser.add_argument('--tokenizer-pool-size',\n type=int,\n default=EngineArgs.tokenizer_pool_size,\n help='Size of tokenizer pool to use for '\n 'asynchronous tokenization. If 0, will '\n 'use synchronous tokenization.')\n parser.add_argument('--tokenizer-pool-type',\n type=str,\n default=EngineArgs.tokenizer_pool_type,\n help='Type of tokenizer pool to use for '\n 'asynchronous tokenization. Ignored '\n 'if tokenizer_pool_size is 0.')\n parser.add_argument('--tokenizer-pool-extra-config',\n type=str,\n default=EngineArgs.tokenizer_pool_extra_config,\n help='Extra config for tokenizer pool. '\n 'This should be a JSON string that will be '\n 'parsed into a dictionary. Ignored if '\n 'tokenizer_pool_size is 0.')\n # LoRA related configs\n parser.add_argument('--enable-lora',\n action='store_true',\n help='If True, enable handling of LoRA adapters.')\n parser.add_argument('--max-loras',\n type=int,\n default=EngineArgs.max_loras,\n help='Max number of LoRAs in a single batch.')\n parser.add_argument('--max-lora-rank',\n type=int,\n default=EngineArgs.max_lora_rank,\n help='Max LoRA rank.')\n parser.add_argument(\n '--lora-extra-vocab-size',\n type=int,\n default=EngineArgs.lora_extra_vocab_size,\n help=('Maximum size of extra vocabulary that can be '\n 'present in a LoRA adapter (added to the base '\n 'model vocabulary).'))\n parser.add_argument(\n '--lora-dtype',\n type=str,\n default=EngineArgs.lora_dtype,\n choices=['auto', 'float16', 'bfloat16', 'float32'],\n help=('Data type for LoRA. If auto, will default to '\n 'base model dtype.'))\n parser.add_argument(\n '--max-cpu-loras',\n type=int,\n default=EngineArgs.max_cpu_loras,\n help=('Maximum number of LoRAs to store in CPU memory. '\n 'Must be >= than max_num_seqs. '\n 'Defaults to max_num_seqs.'))\n parser.add_argument(\"--device\",\n type=str,\n default=EngineArgs.device,\n choices=[\"auto\", \"cuda\", \"neuron\", \"cpu\"],\n help='Device type for vLLM execution.')\n # Related to Vision-language models such as llava\n parser.add_argument(\n '--image-input-type',\n type=str,\n default=None,\n choices=[\n t.name.lower() for t in VisionLanguageConfig.ImageInputType\n ],\n help=('The image input type passed into vLLM. '\n 'Should be one of \"pixel_values\" or \"image_features\".'))\n parser.add_argument('--image-token-id',\n type=int,\n default=None,\n help=('Input id for image token.'))\n parser.add_argument(\n '--image-input-shape',\n type=str,\n default=None,\n help=('The biggest image input shape (worst for memory footprint) '\n 'given an input type. Only used for vLLM\\'s profile_run.'))\n parser.add_argument(\n '--image-feature-size',\n type=int,\n default=None,\n help=('The image feature size along the context dimension.'))\n parser.add_argument(\n '--scheduler-delay-factor',\n type=float,\n default=EngineArgs.scheduler_delay_factor,\n help='Apply a delay (of delay factor multiplied by previous'\n 'prompt latency) before scheduling next prompt.')\n parser.add_argument(\n '--enable-chunked-prefill',\n action='store_true',\n help='If set, the prefill requests can be chunked based on the '\n 'max_num_batched_tokens.')\n\n parser.add_argument(\n '--speculative-model',\n type=str,\n default=None,\n help=\n 'The name of the draft model to be used in speculative decoding.')\n\n parser.add_argument(\n '--num-speculative-tokens',\n type=int,\n default=None,\n help='The number of speculative tokens to sample from '\n 'the draft model in speculative decoding.')\n\n parser.add_argument('--model-loader-extra-config',\n type=str,\n default=EngineArgs.model_loader_extra_config,\n help='Extra config for model loader. '\n 'This will be passed to the model loader '\n 'corresponding to the chosen load_format. '\n 'This should be a JSON string that will be '\n 'parsed into a dictionary.')\n\n return parser\n\n @classmethod\n def from_cli_args(cls, args: argparse.Namespace) -> 'EngineArgs':\n # Get the list of attributes of this dataclass.\n attrs = [attr.name for attr in dataclasses.fields(cls)]\n # Set the attributes from the parsed arguments.\n engine_args = cls(**{attr: getattr(args, attr) for attr in attrs})\n return engine_args\n\n def create_engine_config(self, ) -> EngineConfig:\n device_config = DeviceConfig(self.device)\n model_config = ModelConfig(\n self.model, self.tokenizer, self.tokenizer_mode,\n self.trust_remote_code, self.dtype, self.seed, self.revision,\n self.code_revision, self.tokenizer_revision, self.max_model_len,\n self.quantization, self.quantization_param_path,\n self.enforce_eager, self.max_context_len_to_capture,\n self.max_logprobs)\n cache_config = CacheConfig(self.block_size,\n self.gpu_memory_utilization,\n self.swap_space, self.kv_cache_dtype,\n self.num_gpu_blocks_override,\n model_config.get_sliding_window(),\n self.enable_prefix_caching)\n parallel_config = ParallelConfig(\n self.pipeline_parallel_size, self.tensor_parallel_size,\n self.worker_use_ray, self.max_parallel_loading_workers,\n self.disable_custom_all_reduce,\n TokenizerPoolConfig.create_config(\n self.tokenizer_pool_size,\n self.tokenizer_pool_type,\n self.tokenizer_pool_extra_config,\n ), self.ray_workers_use_nsight)\n\n speculative_config = SpeculativeConfig.maybe_create_spec_config(\n target_model_config=model_config,\n target_parallel_config=parallel_config,\n target_dtype=self.dtype,\n speculative_model=self.speculative_model,\n num_speculative_tokens=self.num_speculative_tokens,\n )\n\n scheduler_config = SchedulerConfig(\n self.max_num_batched_tokens,\n self.max_num_seqs,\n model_config.max_model_len,\n self.use_v2_block_manager,\n num_lookahead_slots=(self.num_lookahead_slots\n if speculative_config is None else\n speculative_config.num_lookahead_slots),\n delay_factor=self.scheduler_delay_factor,\n enable_chunked_prefill=self.enable_chunked_prefill,\n )\n lora_config = LoRAConfig(\n max_lora_rank=self.max_lora_rank,\n max_loras=self.max_loras,\n lora_extra_vocab_size=self.lora_extra_vocab_size,\n lora_dtype=self.lora_dtype,\n max_cpu_loras=self.max_cpu_loras if self.max_cpu_loras\n and self.max_cpu_loras > 0 else None) if self.enable_lora else None\n\n load_config = LoadConfig(\n load_format=self.load_format,\n download_dir=self.download_dir,\n model_loader_extra_config=self.model_loader_extra_config,\n )\n\n if self.image_input_type:\n if (not self.image_token_id or not self.image_input_shape\n or not self.image_feature_size):\n raise ValueError(\n 'Specify `image_token_id`, `image_input_shape` and '\n '`image_feature_size` together with `image_input_type`.')\n vision_language_config = VisionLanguageConfig(\n image_input_type=VisionLanguageConfig.\n get_image_input_enum_type(self.image_input_type),\n image_token_id=self.image_token_id,\n image_input_shape=str_to_int_tuple(self.image_input_shape),\n image_feature_size=self.image_feature_size,\n )\n else:\n vision_language_config = None\n\n decoding_config = DecodingConfig(\n guided_decoding_backend=self.guided_decoding_backend)\n\n return EngineConfig(model_config=model_config,\n cache_config=cache_config,\n parallel_config=parallel_config,\n scheduler_config=scheduler_config,\n device_config=device_config,\n lora_config=lora_config,\n vision_language_config=vision_language_config,\n speculative_config=speculative_config,\n load_config=load_config,\n decoding_config=decoding_config)\n\n\n@dataclass\nclass AsyncEngineArgs(EngineArgs):\n \"\"\"Arguments for asynchronous vLLM engine.\"\"\"\n engine_use_ray: bool = False\n disable_log_requests: bool = False\n max_log_len: Optional[int] = None\n\n @staticmethod\n def add_cli_args(parser: argparse.ArgumentParser,\n async_args_only: bool = False) -> argparse.ArgumentParser:\n if not async_args_only:\n parser = EngineArgs.add_cli_args(parser)\n parser.add_argument('--engine-use-ray',\n action='store_true',\n help='Use Ray to start the LLM engine in a '\n 'separate process as the server process.')\n parser.add_argument('--disable-log-requests',\n action='store_true',\n help='Disable logging requests.')\n parser.add_argument('--max-log-len',\n type=int,\n default=None,\n help='Max number of prompt characters or prompt '\n 'ID numbers being printed in log.'\n '\\n\\nDefault: Unlimited')\n return parser\n\n\n# These functions are used by sphinx to build the documentation\ndef _engine_args_parser():\n return EngineArgs.add_cli_args(argparse.ArgumentParser())\n\n\ndef _async_engine_args_parser():\n return AsyncEngineArgs.add_cli_args(argparse.ArgumentParser(),\n async_args_only=True)\n", "path": "vllm/engine/arg_utils.py" } ]
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 import AsyncLLMEngine\n# yapf: disable\nfrom vllm.entrypoints.openai.protocol import (CompletionLogProbs,\n CompletionRequest,\n CompletionResponse,\n CompletionResponseChoice,\n CompletionResponseStreamChoice,\n CompletionStreamResponse,\n UsageInfo)\n# yapf: enable\nfrom vllm.entrypoints.openai.serving_engine import (LoRAModulePath,\n OpenAIServing)\nfrom vllm.logger import init_logger\nfrom vllm.model_executor.guided_decoding import (\n get_guided_decoding_logits_processor)\nfrom vllm.outputs import RequestOutput\nfrom vllm.sequence import Logprob\nfrom vllm.utils import merge_async_iterators, random_uuid\n\nlogger = init_logger(__name__)\n\nTypeTokenIDs = List[int]\nTypeTopLogProbs = List[Optional[Dict[int, float]]]\nTypeCreateLogProbsFn = Callable[\n [TypeTokenIDs, TypeTopLogProbs, Optional[int], int], CompletionLogProbs]\n\n\ndef parse_prompt_format(prompt) -> Tuple[bool, list]:\n # get the prompt, openai supports the following\n # \"a string, array of strings, array of tokens, or array of token arrays.\"\n prompt_is_tokens = False\n prompts = [prompt] # case 1: a string\n if isinstance(prompt, list):\n if len(prompt) == 0:\n raise ValueError(\"please provide at least one prompt\")\n elif isinstance(prompt[0], str):\n prompt_is_tokens = False\n prompts = prompt # case 2: array of strings\n elif isinstance(prompt[0], int):\n prompt_is_tokens = True\n prompts = [prompt] # case 3: array of tokens\n elif isinstance(prompt[0], list) and isinstance(prompt[0][0], int):\n prompt_is_tokens = True\n prompts = prompt # case 4: array of token arrays\n else:\n raise ValueError(\"prompt must be a string, array of strings, \"\n \"array of tokens, or array of token arrays\")\n return prompt_is_tokens, prompts\n\n\nclass OpenAIServingCompletion(OpenAIServing):\n\n def __init__(self, engine: AsyncLLMEngine, model_config: ModelConfig,\n served_model_names: List[str],\n lora_modules: Optional[List[LoRAModulePath]]):\n super().__init__(engine=engine,\n model_config=model_config,\n served_model_names=served_model_names,\n lora_modules=lora_modules)\n\n async def create_completion(self, request: CompletionRequest,\n raw_request: Request):\n \"\"\"Completion API similar to OpenAI's API.\n\n See https://platform.openai.com/docs/api-reference/completions/create\n for the API specification. This API mimics the OpenAI Completion API.\n\n NOTE: Currently we do not support the following feature:\n - suffix (the language models we currently support do not support\n suffix)\n \"\"\"\n error_check_ret = await self._check_model(request)\n if error_check_ret is not None:\n return error_check_ret\n\n # Return error for unsupported features.\n if request.suffix is not None:\n return self.create_error_response(\n \"suffix is not currently supported\")\n\n model_name = self.served_model_names[0]\n request_id = f\"cmpl-{random_uuid()}\"\n created_time = int(time.time())\n\n # Schedule the request and get the result generator.\n generators: List[AsyncIterator[RequestOutput]] = []\n try:\n sampling_params = request.to_sampling_params()\n lora_request = self._maybe_get_lora(request)\n decoding_config = await self.engine.get_decoding_config()\n guided_decoding_backend = request.guided_decoding_backend \\\n or decoding_config.guided_decoding_backend\n guided_decode_logit_processor = (\n await get_guided_decoding_logits_processor(\n guided_decoding_backend, request, await\n self.engine.get_tokenizer()))\n if guided_decode_logit_processor is not None:\n if sampling_params.logits_processors is None:\n sampling_params.logits_processors = []\n sampling_params.logits_processors.append(\n guided_decode_logit_processor)\n prompt_is_tokens, prompts = parse_prompt_format(request.prompt)\n\n for i, prompt in enumerate(prompts):\n if prompt_is_tokens:\n prompt_formats = self._validate_prompt_and_tokenize(\n request,\n prompt_ids=prompt,\n truncate_prompt_tokens=sampling_params.\n truncate_prompt_tokens)\n else:\n prompt_formats = self._validate_prompt_and_tokenize(\n request,\n prompt=prompt,\n truncate_prompt_tokens=sampling_params.\n truncate_prompt_tokens)\n prompt_ids, prompt_text = prompt_formats\n\n generator = self.engine.generate(\n {\n \"prompt\": prompt_text,\n \"prompt_token_ids\": prompt_ids\n },\n sampling_params,\n f\"{request_id}-{i}\",\n lora_request=lora_request,\n )\n\n generators.append(generator)\n except ValueError as e:\n # TODO: Use a vllm-specific Validation Error\n return self.create_error_response(str(e))\n\n result_generator: AsyncIterator[Tuple[\n int, RequestOutput]] = merge_async_iterators(*generators)\n\n # Similar to the OpenAI API, when n != best_of, we do not stream the\n # results. In addition, we do not stream the results when use\n # beam search.\n stream = (request.stream\n and (request.best_of is None or request.n == request.best_of)\n and not request.use_beam_search)\n\n # Streaming response\n if stream:\n return self.completion_stream_generator(request,\n raw_request,\n result_generator,\n request_id,\n created_time,\n model_name,\n num_prompts=len(prompts))\n\n # Non-streaming response\n final_res_batch: List[Optional[RequestOutput]] = [None] * len(prompts)\n try:\n async for i, res in result_generator:\n if await raw_request.is_disconnected():\n # Abort the request if the client disconnects.\n await self.engine.abort(f\"{request_id}-{i}\")\n return self.create_error_response(\"Client disconnected\")\n final_res_batch[i] = res\n response = self.request_output_to_completion_response(\n final_res_batch, request, request_id, created_time, model_name)\n except ValueError as e:\n # TODO: Use a vllm-specific Validation Error\n return self.create_error_response(str(e))\n\n # When user requests streaming but we don't stream, we still need to\n # return a streaming response with a single event.\n if request.stream:\n response_json = response.model_dump_json()\n\n async def fake_stream_generator() -> AsyncGenerator[str, None]:\n yield f\"data: {response_json}\\n\\n\"\n yield \"data: [DONE]\\n\\n\"\n\n return fake_stream_generator()\n\n return response\n\n async def completion_stream_generator(\n self,\n request: CompletionRequest,\n raw_request: Request,\n result_generator: AsyncIterator[Tuple[int, RequestOutput]],\n request_id: str,\n created_time: int,\n model_name: str,\n num_prompts: int,\n ) -> AsyncGenerator[str, None]:\n assert request.n is not None\n previous_texts = [\"\"] * request.n * num_prompts\n previous_num_tokens = [0] * request.n * num_prompts\n has_echoed = [False] * request.n * num_prompts\n\n try:\n async for prompt_idx, res in result_generator:\n\n # Abort the request if the client disconnects.\n if await raw_request.is_disconnected():\n await self.engine.abort(f\"{request_id}-{prompt_idx}\")\n raise StopAsyncIteration()\n\n for output in res.outputs:\n i = output.index + prompt_idx * request.n\n # TODO(simon): optimize the performance by avoiding full\n # text O(n^2) sending.\n\n assert request.max_tokens is not None\n if request.echo and request.max_tokens == 0:\n # only return the prompt\n delta_text = res.prompt\n delta_token_ids = res.prompt_token_ids\n top_logprobs = res.prompt_logprobs\n has_echoed[i] = True\n elif (request.echo and request.max_tokens > 0\n and not has_echoed[i]):\n # echo the prompt and first token\n delta_text = res.prompt + output.text\n delta_token_ids = (res.prompt_token_ids +\n output.token_ids)\n top_logprobs = res.prompt_logprobs + (output.logprobs\n or [])\n has_echoed[i] = True\n else:\n # return just the delta\n delta_text = output.text[len(previous_texts[i]):]\n delta_token_ids = output.token_ids[\n previous_num_tokens[i]:]\n top_logprobs = output.logprobs[previous_num_tokens[\n i]:] if output.logprobs else None\n\n if request.logprobs is not None:\n logprobs = self._create_completion_logprobs(\n token_ids=delta_token_ids,\n top_logprobs=top_logprobs,\n num_output_top_logprobs=request.logprobs,\n initial_text_offset=len(previous_texts[i]),\n )\n else:\n logprobs = None\n\n previous_texts[i] = output.text\n previous_num_tokens[i] = len(output.token_ids)\n finish_reason = output.finish_reason\n stop_reason = output.stop_reason\n if output.finish_reason is not None: # return final usage\n prompt_tokens = len(res.prompt_token_ids)\n completion_tokens = len(output.token_ids)\n final_usage = UsageInfo(\n prompt_tokens=prompt_tokens,\n completion_tokens=completion_tokens,\n total_tokens=prompt_tokens + completion_tokens,\n )\n else:\n final_usage = None\n response_json = CompletionStreamResponse(\n id=request_id,\n created=created_time,\n model=model_name,\n choices=[\n CompletionResponseStreamChoice(\n index=i,\n text=delta_text,\n logprobs=logprobs,\n finish_reason=finish_reason,\n stop_reason=stop_reason,\n )\n ],\n usage=final_usage,\n ).model_dump_json(exclude_unset=True)\n yield f\"data: {response_json}\\n\\n\"\n except ValueError as e:\n # TODO: Use a vllm-specific Validation Error\n data = self.create_streaming_error_response(str(e))\n yield f\"data: {data}\\n\\n\"\n yield \"data: [DONE]\\n\\n\"\n\n def request_output_to_completion_response(\n self,\n final_res_batch: List[RequestOutput],\n request: CompletionRequest,\n request_id: str,\n created_time: int,\n model_name: str,\n ) -> CompletionResponse:\n choices: List[CompletionResponseChoice] = []\n num_prompt_tokens = 0\n num_generated_tokens = 0\n for final_res in final_res_batch:\n assert final_res is not None\n prompt_token_ids = final_res.prompt_token_ids\n prompt_logprobs = final_res.prompt_logprobs\n prompt_text = final_res.prompt\n\n for output in final_res.outputs:\n assert request.max_tokens is not None\n if request.echo and request.max_tokens == 0:\n token_ids = prompt_token_ids\n top_logprobs = prompt_logprobs\n output_text = prompt_text\n elif request.echo and request.max_tokens > 0:\n token_ids = prompt_token_ids + output.token_ids\n top_logprobs = (prompt_logprobs + output.logprobs\n if request.logprobs is not None else None)\n output_text = prompt_text + output.text\n else:\n token_ids = output.token_ids\n top_logprobs = output.logprobs\n output_text = output.text\n\n if request.logprobs is not None:\n assert top_logprobs is not None, (\n \"top_logprobs must be provided when logprobs \"\n \"is requested\")\n logprobs = self._create_completion_logprobs(\n token_ids=token_ids,\n top_logprobs=top_logprobs,\n num_output_top_logprobs=request.logprobs,\n )\n else:\n logprobs = None\n\n choice_data = CompletionResponseChoice(\n index=len(choices),\n text=output_text,\n logprobs=logprobs,\n finish_reason=output.finish_reason,\n stop_reason=output.stop_reason,\n )\n choices.append(choice_data)\n\n num_prompt_tokens += len(prompt_token_ids)\n num_generated_tokens += sum(\n len(output.token_ids) for output in final_res.outputs)\n\n usage = UsageInfo(\n prompt_tokens=num_prompt_tokens,\n completion_tokens=num_generated_tokens,\n total_tokens=num_prompt_tokens + num_generated_tokens,\n )\n\n return CompletionResponse(\n id=request_id,\n created=created_time,\n model=model_name,\n choices=choices,\n usage=usage,\n )\n\n def _create_completion_logprobs(\n self,\n token_ids: GenericSequence[int],\n top_logprobs: GenericSequence[Optional[Dict[int, Logprob]]],\n num_output_top_logprobs: int,\n initial_text_offset: int = 0,\n ) -> CompletionLogProbs:\n \"\"\"Create logprobs for OpenAI Completion API.\"\"\"\n out_text_offset: List[int] = []\n out_token_logprobs: List[Optional[float]] = []\n out_tokens: List[str] = []\n out_top_logprobs: List[Optional[Dict[str, float]]] = []\n\n last_token_len = 0\n\n for i, token_id in enumerate(token_ids):\n step_top_logprobs = top_logprobs[i]\n if step_top_logprobs is None:\n token = self.tokenizer.decode(token_id)\n out_tokens.append(token)\n out_token_logprobs.append(None)\n out_top_logprobs.append(None)\n else:\n token = self._get_decoded_token(step_top_logprobs[token_id],\n token_id)\n token_logprob = max(step_top_logprobs[token_id].logprob,\n -9999.0)\n out_tokens.append(token)\n out_token_logprobs.append(token_logprob)\n\n # makes sure to add the top num_output_top_logprobs + 1\n # logprobs, as defined in the openai API\n # (cf. https://github.com/openai/openai-openapi/blob/\n # 893ba52242dbd5387a97b96444ee1c742cfce9bd/openapi.yaml#L7153)\n out_top_logprobs.append({\n # Convert float(\"-inf\") to the\n # JSON-serializable float that OpenAI uses\n self._get_decoded_token(top_lp[1], top_lp[0]):\n max(top_lp[1].logprob, -9999.0)\n for i, top_lp in enumerate(step_top_logprobs.items())\n if num_output_top_logprobs >= i\n })\n\n if len(out_text_offset) == 0:\n out_text_offset.append(initial_text_offset)\n else:\n out_text_offset.append(out_text_offset[-1] + last_token_len)\n last_token_len = len(token)\n\n return CompletionLogProbs(\n text_offset=out_text_offset,\n token_logprobs=out_token_logprobs,\n tokens=out_tokens,\n top_logprobs=out_top_logprobs,\n )\n", "path": "vllm/entrypoints/openai/serving_completion.py" }, { "content": "import codecs\nimport time\nfrom dataclasses import dataclass, field\nfrom typing import (AsyncGenerator, AsyncIterator, Awaitable, Dict, Iterable,\n List, Optional)\nfrom typing import Sequence as GenericSequence\nfrom typing import TypedDict, Union, cast, final\n\nfrom fastapi import Request\nfrom openai.types.chat import (ChatCompletionContentPartImageParam,\n ChatCompletionContentPartTextParam)\n\nfrom vllm.config import ModelConfig, VisionLanguageConfig\nfrom vllm.engine.async_llm_engine import AsyncLLMEngine\nfrom vllm.entrypoints.openai.protocol import (\n ChatCompletionContentPartParam, ChatCompletionLogProb,\n ChatCompletionLogProbs, ChatCompletionLogProbsContent,\n ChatCompletionMessageParam, ChatCompletionNamedToolChoiceParam,\n ChatCompletionRequest, ChatCompletionResponse,\n ChatCompletionResponseChoice, ChatCompletionResponseStreamChoice,\n ChatCompletionStreamResponse, ChatMessage, DeltaMessage, ErrorResponse,\n FunctionCall, ToolCall, UsageInfo)\nfrom vllm.entrypoints.openai.serving_engine import (LoRAModulePath,\n OpenAIServing)\nfrom vllm.inputs import PromptInputs\nfrom vllm.logger import init_logger\nfrom vllm.model_executor.guided_decoding import (\n get_guided_decoding_logits_processor)\nfrom vllm.multimodal.image import ImagePixelData\nfrom vllm.multimodal.utils import (async_get_and_parse_image,\n get_full_image_text_prompt)\nfrom vllm.outputs import RequestOutput\nfrom vllm.sequence import Logprob\nfrom vllm.utils import random_uuid\n\nlogger = init_logger(__name__)\n\n\n@final # So that it should be compatible with Dict[str, str]\nclass ConversationMessage(TypedDict):\n role: str\n content: str\n\n\n@dataclass(frozen=True)\nclass ChatMessageParseResult:\n messages: List[ConversationMessage]\n image_futures: List[Awaitable[ImagePixelData]] = field(\n default_factory=list)\n\n\nclass OpenAIServingChat(OpenAIServing):\n\n def __init__(self,\n engine: AsyncLLMEngine,\n model_config: ModelConfig,\n served_model_names: List[str],\n response_role: str,\n lora_modules: Optional[List[LoRAModulePath]] = None,\n chat_template: Optional[str] = None):\n super().__init__(engine=engine,\n model_config=model_config,\n served_model_names=served_model_names,\n lora_modules=lora_modules)\n\n self.response_role = response_role\n self._load_chat_template(chat_template)\n\n def _load_chat_template(self, chat_template: Optional[str]):\n tokenizer = self.tokenizer\n\n if chat_template is not None:\n try:\n with open(chat_template, \"r\") as f:\n tokenizer.chat_template = f.read()\n except OSError as e:\n JINJA_CHARS = \"{}\\n\"\n if not any(c in chat_template for c in JINJA_CHARS):\n msg = (f\"The supplied chat template ({chat_template}) \"\n f\"looks like a file path, but it failed to be \"\n f\"opened. Reason: {e}\")\n raise ValueError(msg) from e\n\n # If opening a file fails, set chat template to be args to\n # ensure we decode so our escape are interpreted correctly\n tokenizer.chat_template = codecs.decode(\n chat_template, \"unicode_escape\")\n\n logger.info(\"Using supplied chat template:\\n%s\",\n tokenizer.chat_template)\n elif tokenizer.chat_template is not None:\n logger.info(\"Using default chat template:\\n%s\",\n tokenizer.chat_template)\n else:\n logger.warning(\n \"No chat template provided. Chat API will not work.\")\n\n def _parse_chat_message_content_parts(\n self,\n role: str,\n parts: Iterable[ChatCompletionContentPartParam],\n ) -> ChatMessageParseResult:\n texts: List[str] = []\n image_futures: List[Awaitable[ImagePixelData]] = []\n\n vlm_config: Optional[VisionLanguageConfig] = getattr(\n self.engine.engine, \"vision_language_config\", None)\n model_config = getattr(self.engine.engine, \"model_config\", None)\n\n for part in parts:\n part_type = part[\"type\"]\n if part_type == \"text\":\n text = cast(ChatCompletionContentPartTextParam, part)[\"text\"]\n\n texts.append(text)\n elif part_type == \"image_url\":\n if vlm_config is None:\n raise ValueError(\n \"'image_url' input is not supported as the loaded \"\n \"model is not multimodal.\")\n\n elif len(image_futures) == 0:\n assert self.tokenizer is not None\n image_url = cast(ChatCompletionContentPartImageParam,\n part)[\"image_url\"]\n\n if image_url.get(\"detail\", \"auto\") != \"auto\":\n logger.warning(\n \"'image_url.detail' is currently not supported and \"\n \"will be ignored.\")\n\n image_future = async_get_and_parse_image(image_url[\"url\"])\n image_futures.append(image_future)\n\n else:\n raise NotImplementedError(\n \"Multiple 'image_url' input is currently not supported.\"\n )\n\n else:\n raise NotImplementedError(f\"Unknown part type: {part_type}\")\n\n text_prompt = \"\\n\".join(texts)\n\n if vlm_config is not None and len(image_futures):\n\n (image_token_prompt,\n image_token_str) = vlm_config.get_image_token_text(self.tokenizer)\n\n # NOTE: If image token string (e.g, <image>) is already present\n # in the text prompt, we assume it follows the same format required\n # by the engine.\n if image_token_str in text_prompt:\n logger.warning(\n \"Detected image token string in the text prompt. \"\n \"Skipping prompt formatting.\")\n messages = [\n ConversationMessage(role=role, content=text_prompt)\n ]\n\n else:\n full_prompt = get_full_image_text_prompt(\n image_prompt=image_token_prompt,\n text_prompt=text_prompt,\n config=model_config)\n messages = [\n ConversationMessage(role=role, content=full_prompt)\n ]\n else:\n messages = [ConversationMessage(role=role, content=text_prompt)]\n\n return ChatMessageParseResult(messages=messages,\n image_futures=image_futures)\n\n def _parse_chat_message_content(\n self,\n message: ChatCompletionMessageParam,\n ) -> ChatMessageParseResult:\n role = message[\"role\"]\n content = message.get(\"content\")\n\n if content is None:\n return ChatMessageParseResult(messages=[], image_futures=[])\n if isinstance(content, str):\n messages = [ConversationMessage(role=role, content=content)]\n return ChatMessageParseResult(messages=messages, image_futures=[])\n\n return self._parse_chat_message_content_parts(role, content)\n\n async def create_chat_completion(\n self,\n request: ChatCompletionRequest,\n raw_request: Optional[Request] = None\n ) -> Union[ErrorResponse, AsyncGenerator[str, None],\n ChatCompletionResponse]:\n \"\"\"Completion API similar to OpenAI's API.\n\n See https://platform.openai.com/docs/api-reference/chat/create\n for the API specification. This API mimics the OpenAI\n ChatCompletion API.\n\n NOTE: Currently we do not support the following feature:\n - function_call (Users should implement this by themselves)\n \"\"\"\n error_check_ret = await self._check_model(request)\n if error_check_ret is not None:\n return error_check_ret\n\n try:\n conversation: List[ConversationMessage] = []\n image_futures: List[Awaitable[ImagePixelData]] = []\n\n for msg in request.messages:\n chat_parsed_result = self._parse_chat_message_content(msg)\n\n conversation.extend(chat_parsed_result.messages)\n image_futures.extend(chat_parsed_result.image_futures)\n\n prompt = self.tokenizer.apply_chat_template(\n conversation=conversation,\n tokenize=False,\n add_generation_prompt=request.add_generation_prompt,\n )\n except Exception as e:\n logger.error(\"Error in applying chat template from request: %s\", e)\n return self.create_error_response(str(e))\n\n # Fetch image data\n image_data: Optional[ImagePixelData] = None\n try:\n if len(image_futures):\n # since we support only single image currently\n assert len(image_futures) == 1\n image_data = await image_futures[0]\n except Exception as e:\n logger.error(\"Error in loading image data: %s\", e)\n return self.create_error_response(str(e))\n\n request_id = f\"cmpl-{random_uuid()}\"\n try:\n # Tokenize/detokenize depending on prompt format (string/token list)\n prompt_ids, prompt_text = self._validate_prompt_and_tokenize(\n request,\n prompt=prompt,\n add_special_tokens=request.add_special_tokens)\n sampling_params = request.to_sampling_params()\n lora_request = self._maybe_get_lora(request)\n decoding_config = await self.engine.get_decoding_config()\n guided_decoding_backend = request.guided_decoding_backend \\\n or decoding_config.guided_decoding_backend\n guided_decode_logits_processor = (\n await get_guided_decoding_logits_processor(\n guided_decoding_backend, request, await\n self.engine.get_tokenizer()))\n if guided_decode_logits_processor:\n if sampling_params.logits_processors is None:\n sampling_params.logits_processors = []\n sampling_params.logits_processors.append(\n guided_decode_logits_processor)\n except ValueError as e:\n return self.create_error_response(str(e))\n\n inputs: PromptInputs = {\n \"prompt\": prompt_text,\n \"prompt_token_ids\": prompt_ids,\n }\n if image_data is not None:\n inputs[\"multi_modal_data\"] = image_data\n\n result_generator = self.engine.generate(\n inputs,\n sampling_params,\n request_id,\n lora_request,\n )\n # Streaming response\n if request.stream:\n return self.chat_completion_stream_generator(\n request, result_generator, request_id, conversation)\n else:\n try:\n return await self.chat_completion_full_generator(\n request, raw_request, result_generator, request_id,\n conversation)\n except ValueError as e:\n # TODO: Use a vllm-specific Validation Error\n return self.create_error_response(str(e))\n\n def get_chat_request_role(self, request: ChatCompletionRequest) -> str:\n if request.add_generation_prompt:\n return self.response_role\n else:\n return request.messages[-1][\"role\"]\n\n async def chat_completion_stream_generator(\n self, request: ChatCompletionRequest,\n result_generator: AsyncIterator[RequestOutput], request_id: str,\n conversation: List[ConversationMessage]\n ) -> AsyncGenerator[str, None]:\n model_name = self.served_model_names[0]\n created_time = int(time.time())\n chunk_object_type = \"chat.completion.chunk\"\n first_iteration = True\n\n # Send response for each token for each request.n (index)\n assert request.n is not None\n previous_texts = [\"\"] * request.n\n previous_num_tokens = [0] * request.n\n finish_reason_sent = [False] * request.n\n try:\n async for res in result_generator:\n # We need to do it here, because if there are exceptions in\n # the result_generator, it needs to be sent as the FIRST\n # response (by the try...catch).\n if first_iteration:\n # Send first response for each request.n (index) with\n # the role\n role = self.get_chat_request_role(request)\n for i in range(request.n):\n choice_data = ChatCompletionResponseStreamChoice(\n index=i,\n delta=DeltaMessage(role=role),\n logprobs=None,\n finish_reason=None)\n chunk = ChatCompletionStreamResponse(\n id=request_id,\n object=chunk_object_type,\n created=created_time,\n choices=[choice_data],\n model=model_name)\n if (request.stream_options\n and request.stream_options.include_usage):\n chunk.usage = None\n data = chunk.model_dump_json(exclude_unset=True)\n yield f\"data: {data}\\n\\n\"\n\n # Send response to echo the input portion of the\n # last message\n if request.echo:\n last_msg_content = \"\"\n if conversation and conversation[-1].get(\n \"content\") and conversation[-1].get(\n \"role\") == role:\n last_msg_content = conversation[-1][\"content\"]\n\n if last_msg_content:\n for i in range(request.n):\n choice_data = (\n ChatCompletionResponseStreamChoice(\n index=i,\n delta=DeltaMessage(\n content=last_msg_content),\n finish_reason=None))\n chunk = ChatCompletionStreamResponse(\n id=request_id,\n object=chunk_object_type,\n created=created_time,\n choices=[choice_data],\n logprobs=None,\n model=model_name)\n if (request.stream_options and\n request.stream_options.include_usage):\n chunk.usage = None\n data = chunk.model_dump_json(\n exclude_unset=True)\n yield f\"data: {data}\\n\\n\"\n first_iteration = False\n\n for output in res.outputs:\n i = output.index\n\n if finish_reason_sent[i]:\n continue\n\n delta_token_ids = output.token_ids[previous_num_tokens[i]:]\n top_logprobs = output.logprobs[\n previous_num_tokens[i]:] if output.logprobs else None\n\n if request.logprobs:\n logprobs = self._create_chat_logprobs(\n token_ids=delta_token_ids,\n top_logprobs=top_logprobs,\n num_output_top_logprobs=request.top_logprobs,\n )\n else:\n logprobs = None\n\n delta_text = output.text[len(previous_texts[i]):]\n previous_texts[i] = output.text\n previous_num_tokens[i] = len(output.token_ids)\n\n if request.tool_choice and type(\n request.tool_choice\n ) is ChatCompletionNamedToolChoiceParam:\n delta_message = DeltaMessage(tool_calls=[\n ToolCall(function=FunctionCall(\n name=request.tool_choice.function.name,\n arguments=delta_text))\n ])\n else:\n delta_message = DeltaMessage(content=delta_text)\n\n if output.finish_reason is None:\n # Send token-by-token response for each request.n\n\n choice_data = ChatCompletionResponseStreamChoice(\n index=i,\n delta=delta_message,\n logprobs=logprobs,\n finish_reason=None)\n chunk = ChatCompletionStreamResponse(\n id=request_id,\n object=chunk_object_type,\n created=created_time,\n choices=[choice_data],\n model=model_name)\n if (request.stream_options\n and request.stream_options.include_usage):\n chunk.usage = None\n data = chunk.model_dump_json(exclude_unset=True)\n yield f\"data: {data}\\n\\n\"\n else:\n # Send the finish response for each request.n only once\n prompt_tokens = len(res.prompt_token_ids)\n choice_data = ChatCompletionResponseStreamChoice(\n index=i,\n delta=delta_message,\n logprobs=logprobs,\n finish_reason=output.finish_reason,\n stop_reason=output.stop_reason)\n chunk = ChatCompletionStreamResponse(\n id=request_id,\n object=chunk_object_type,\n created=created_time,\n choices=[choice_data],\n model=model_name)\n if (request.stream_options\n and request.stream_options.include_usage):\n chunk.usage = None\n data = chunk.model_dump_json(exclude_unset=True)\n yield f\"data: {data}\\n\\n\"\n finish_reason_sent[i] = True\n\n if (request.stream_options\n and request.stream_options.include_usage):\n final_usage = UsageInfo(\n prompt_tokens=prompt_tokens,\n completion_tokens=previous_num_tokens[i],\n total_tokens=prompt_tokens +\n previous_num_tokens[i],\n )\n\n final_usage_chunk = ChatCompletionStreamResponse(\n id=request_id,\n object=chunk_object_type,\n created=created_time,\n choices=[],\n model=model_name,\n usage=final_usage)\n final_usage_data = (final_usage_chunk.model_dump_json(\n exclude_unset=True, exclude_none=True))\n yield f\"data: {final_usage_data}\\n\\n\"\n\n except ValueError as e:\n # TODO: Use a vllm-specific Validation Error\n data = self.create_streaming_error_response(str(e))\n yield f\"data: {data}\\n\\n\"\n # Send the final done message after all response.n are finished\n yield \"data: [DONE]\\n\\n\"\n\n async def chat_completion_full_generator(\n self, request: ChatCompletionRequest, raw_request: Optional[Request],\n result_generator: AsyncIterator[RequestOutput], request_id: str,\n conversation: List[ConversationMessage]\n ) -> Union[ErrorResponse, ChatCompletionResponse]:\n\n model_name = self.served_model_names[0]\n created_time = int(time.time())\n final_res: Optional[RequestOutput] = None\n\n async for res in result_generator:\n if raw_request is not None and await raw_request.is_disconnected():\n # Abort the request if the client disconnects.\n await self.engine.abort(request_id)\n return self.create_error_response(\"Client disconnected\")\n final_res = res\n assert final_res is not None\n\n choices = []\n\n role = self.get_chat_request_role(request)\n for output in final_res.outputs:\n token_ids = output.token_ids\n top_logprobs = output.logprobs\n\n if request.logprobs:\n logprobs = self._create_chat_logprobs(\n token_ids=token_ids,\n top_logprobs=top_logprobs,\n num_output_top_logprobs=request.top_logprobs,\n )\n else:\n logprobs = None\n\n if request.tool_choice and type(\n request.tool_choice) is ChatCompletionNamedToolChoiceParam:\n message = ChatMessage(\n role=role,\n content=\"\",\n tool_calls=[\n ToolCall(function=FunctionCall(\n name=request.tool_choice.function.name,\n arguments=output.text))\n ])\n elif not request.tool_choice or request.tool_choice == \"none\":\n message = ChatMessage(role=role, content=output.text)\n\n choice_data = ChatCompletionResponseChoice(\n index=output.index,\n message=message,\n logprobs=logprobs,\n finish_reason=output.finish_reason,\n stop_reason=output.stop_reason)\n choices.append(choice_data)\n\n if request.echo:\n last_msg_content = \"\"\n if conversation and conversation[-1].get(\n \"content\") and conversation[-1].get(\"role\") == role:\n last_msg_content = conversation[-1][\"content\"]\n\n for choice in choices:\n full_message = last_msg_content + choice.message.content\n choice.message.content = full_message\n\n num_prompt_tokens = len(final_res.prompt_token_ids)\n num_generated_tokens = sum(\n len(output.token_ids) for output in final_res.outputs)\n usage = UsageInfo(\n prompt_tokens=num_prompt_tokens,\n completion_tokens=num_generated_tokens,\n total_tokens=num_prompt_tokens + num_generated_tokens,\n )\n response = ChatCompletionResponse(\n id=request_id,\n created=created_time,\n model=model_name,\n choices=choices,\n usage=usage,\n )\n\n return response\n\n def _get_top_logprobs(\n self, logprobs: Dict[int, Logprob],\n top_logprobs: Optional[int]) -> List[ChatCompletionLogProb]:\n return [\n ChatCompletionLogProb(\n token=self._get_decoded_token(p[1], p[0]),\n logprob=max(p[1].logprob, -9999.0),\n bytes=list(\n self._get_decoded_token(p[1],\n p[0]).encode(\"utf-8\",\n errors=\"replace\")))\n for i, p in enumerate(logprobs.items())\n if top_logprobs and i < top_logprobs\n ]\n\n def _create_chat_logprobs(\n self,\n token_ids: GenericSequence[int],\n top_logprobs: GenericSequence[Optional[Dict[int, Logprob]]],\n num_output_top_logprobs: Optional[int] = None,\n ) -> ChatCompletionLogProbs:\n \"\"\"Create OpenAI-style logprobs.\"\"\"\n\n logprobs_content = []\n\n for i, token_id in enumerate(token_ids):\n step_top_logprobs = top_logprobs[i]\n if step_top_logprobs is None:\n logprobs_content.append(\n ChatCompletionLogProbsContent(\n token=self.tokenizer.decode(token_id),\n bytes=list(\n self.tokenizer.decode(token_id).encode(\n \"utf-8\", errors=\"replace\"))))\n else:\n logprobs_content.append(\n ChatCompletionLogProbsContent(\n token=step_top_logprobs[token_id].decoded_token,\n logprob=max(step_top_logprobs[token_id].logprob,\n -9999.0),\n bytes=list(\n step_top_logprobs[token_id].decoded_token.encode(\n \"utf-8\", errors=\"replace\")),\n top_logprobs=self._get_top_logprobs(\n step_top_logprobs, num_output_top_logprobs)))\n\n return ChatCompletionLogProbs(content=logprobs_content)\n", "path": "vllm/entrypoints/openai/serving_chat.py" }, { "content": "# Adapted from\n# https://github.com/lm-sys/FastChat/blob/168ccc29d3f7edc50823016105c024fe2282732a/fastchat/protocol/openai_api_protocol.py\nimport time\nfrom typing import Any, Dict, List, Literal, Optional, Union\n\nimport openai.types.chat\nimport torch\nfrom pydantic import BaseModel, ConfigDict, Field, model_validator\n# pydantic needs the TypedDict from typing_extensions\nfrom typing_extensions import Annotated, Required, TypedDict\n\nfrom vllm.pooling_params import PoolingParams\nfrom vllm.sampling_params import SamplingParams\nfrom vllm.utils import random_uuid\n\n\nclass CustomChatCompletionContentPartParam(TypedDict, total=False):\n __pydantic_config__ = ConfigDict(extra=\"allow\") # type: ignore\n\n type: Required[str]\n \"\"\"The type of the content part.\"\"\"\n\n\nChatCompletionContentPartParam = Union[\n openai.types.chat.ChatCompletionContentPartParam,\n CustomChatCompletionContentPartParam]\n\n\nclass CustomChatCompletionMessageParam(TypedDict, total=False):\n \"\"\"Enables custom roles in the Chat Completion API.\"\"\"\n role: Required[str]\n \"\"\"The role of the message's author.\"\"\"\n\n content: Union[str, List[ChatCompletionContentPartParam]]\n \"\"\"The contents of the message.\"\"\"\n\n name: str\n \"\"\"An optional name for the participant.\n\n Provides the model information to differentiate between participants of the\n same role.\n \"\"\"\n\n\nChatCompletionMessageParam = Union[\n openai.types.chat.ChatCompletionMessageParam,\n CustomChatCompletionMessageParam]\n\n\nclass OpenAIBaseModel(BaseModel):\n # OpenAI API does not allow extra fields\n model_config = ConfigDict(extra=\"forbid\")\n\n\nclass ErrorResponse(OpenAIBaseModel):\n object: str = \"error\"\n message: str\n type: str\n param: Optional[str] = None\n code: int\n\n\nclass ModelPermission(OpenAIBaseModel):\n id: str = Field(default_factory=lambda: f\"modelperm-{random_uuid()}\")\n object: str = \"model_permission\"\n created: int = Field(default_factory=lambda: int(time.time()))\n allow_create_engine: bool = False\n allow_sampling: bool = True\n allow_logprobs: bool = True\n allow_search_indices: bool = False\n allow_view: bool = True\n allow_fine_tuning: bool = False\n organization: str = \"*\"\n group: Optional[str] = None\n is_blocking: bool = False\n\n\nclass ModelCard(OpenAIBaseModel):\n id: str\n object: str = \"model\"\n created: int = Field(default_factory=lambda: int(time.time()))\n owned_by: str = \"vllm\"\n root: Optional[str] = None\n parent: Optional[str] = None\n max_model_len: Optional[int] = None\n permission: List[ModelPermission] = Field(default_factory=list)\n\n\nclass ModelList(OpenAIBaseModel):\n object: str = \"list\"\n data: List[ModelCard] = Field(default_factory=list)\n\n\nclass UsageInfo(OpenAIBaseModel):\n prompt_tokens: int = 0\n total_tokens: int = 0\n completion_tokens: Optional[int] = 0\n\n\nclass ResponseFormat(OpenAIBaseModel):\n # type must be \"json_object\" or \"text\"\n type: Literal[\"text\", \"json_object\"]\n\n\nclass StreamOptions(OpenAIBaseModel):\n include_usage: Optional[bool]\n\n\nclass FunctionDefinition(OpenAIBaseModel):\n name: str\n description: Optional[str] = None\n parameters: Optional[Dict[str, Any]] = None\n\n\nclass ChatCompletionToolsParam(OpenAIBaseModel):\n type: Literal[\"function\"] = \"function\"\n function: FunctionDefinition\n\n\nclass ChatCompletionNamedFunction(OpenAIBaseModel):\n name: str\n\n\nclass ChatCompletionNamedToolChoiceParam(OpenAIBaseModel):\n function: ChatCompletionNamedFunction\n type: Literal[\"function\"] = \"function\"\n\n\nclass ChatCompletionRequest(OpenAIBaseModel):\n # Ordered by official OpenAI API documentation\n # https://platform.openai.com/docs/api-reference/chat/create\n messages: List[ChatCompletionMessageParam]\n model: str\n frequency_penalty: Optional[float] = 0.0\n logit_bias: Optional[Dict[str, float]] = None\n logprobs: Optional[bool] = False\n top_logprobs: Optional[int] = 0\n max_tokens: Optional[int] = None\n n: Optional[int] = 1\n presence_penalty: Optional[float] = 0.0\n response_format: Optional[ResponseFormat] = None\n seed: Optional[int] = Field(None,\n ge=torch.iinfo(torch.long).min,\n le=torch.iinfo(torch.long).max)\n stop: Optional[Union[str, List[str]]] = Field(default_factory=list)\n stream: Optional[bool] = False\n stream_options: Optional[StreamOptions] = None\n temperature: Optional[float] = 0.7\n top_p: Optional[float] = 1.0\n tools: Optional[List[ChatCompletionToolsParam]] = None\n tool_choice: Optional[Union[Literal[\"none\"],\n ChatCompletionNamedToolChoiceParam]] = \"none\"\n user: Optional[str] = None\n\n # doc: begin-chat-completion-sampling-params\n best_of: Optional[int] = None\n use_beam_search: Optional[bool] = False\n top_k: Optional[int] = -1\n min_p: Optional[float] = 0.0\n repetition_penalty: Optional[float] = 1.0\n length_penalty: Optional[float] = 1.0\n early_stopping: Optional[bool] = False\n ignore_eos: Optional[bool] = False\n min_tokens: Optional[int] = 0\n stop_token_ids: Optional[List[int]] = Field(default_factory=list)\n skip_special_tokens: Optional[bool] = True\n spaces_between_special_tokens: Optional[bool] = True\n # doc: end-chat-completion-sampling-params\n\n # doc: begin-chat-completion-extra-params\n echo: Optional[bool] = Field(\n default=False,\n description=(\n \"If true, the new message will be prepended with the last message \"\n \"if they belong to the same role.\"),\n )\n add_generation_prompt: Optional[bool] = Field(\n default=True,\n description=\n (\"If true, the generation prompt will be added to the chat template. \"\n \"This is a parameter used by chat template in tokenizer config of the \"\n \"model.\"),\n )\n add_special_tokens: Optional[bool] = Field(\n default=False,\n description=(\n \"If true, special tokens (e.g. BOS) will be added to the prompt \"\n \"on top of what is added by the chat template. \"\n \"For most models, the chat template takes care of adding the \"\n \"special tokens so this should be set to False (as is the \"\n \"default).\"),\n )\n include_stop_str_in_output: Optional[bool] = Field(\n default=False,\n description=(\n \"Whether to include the stop string in the output. \"\n \"This is only applied when the stop or stop_token_ids is set.\"),\n )\n guided_json: Optional[Union[str, dict, BaseModel]] = Field(\n default=None,\n description=(\"If specified, the output will follow the JSON schema.\"),\n )\n guided_regex: Optional[str] = Field(\n default=None,\n description=(\n \"If specified, the output will follow the regex pattern.\"),\n )\n guided_choice: Optional[List[str]] = Field(\n default=None,\n description=(\n \"If specified, the output will be exactly one of the choices.\"),\n )\n guided_grammar: Optional[str] = Field(\n default=None,\n description=(\n \"If specified, the output will follow the context free grammar.\"),\n )\n guided_decoding_backend: Optional[str] = Field(\n default=None,\n description=(\n \"If specified, will override the default guided decoding backend \"\n \"of the server for this specific request. If set, must be either \"\n \"'outlines' / 'lm-format-enforcer'\"))\n guided_whitespace_pattern: Optional[str] = Field(\n default=None,\n description=(\n \"If specified, will override the default whitespace pattern \"\n \"for guided json decoding.\"))\n\n # doc: end-chat-completion-extra-params\n\n def to_sampling_params(self) -> SamplingParams:\n # We now allow logprobs being true without top_logrobs.\n\n logits_processors = None\n if self.logit_bias:\n\n def logit_bias_logits_processor(\n token_ids: List[int],\n logits: torch.Tensor) -> torch.Tensor:\n assert self.logit_bias is not None\n for token_id, bias in self.logit_bias.items():\n # Clamp the bias between -100 and 100 per OpenAI API spec\n bias = min(100, max(-100, bias))\n logits[int(token_id)] += bias\n return logits\n\n logits_processors = [logit_bias_logits_processor]\n\n return SamplingParams(\n n=self.n,\n presence_penalty=self.presence_penalty,\n frequency_penalty=self.frequency_penalty,\n repetition_penalty=self.repetition_penalty,\n temperature=self.temperature,\n top_p=self.top_p,\n min_p=self.min_p,\n seed=self.seed,\n stop=self.stop,\n stop_token_ids=self.stop_token_ids,\n max_tokens=self.max_tokens,\n min_tokens=self.min_tokens,\n logprobs=self.top_logprobs if self.logprobs else None,\n prompt_logprobs=self.top_logprobs if self.echo else None,\n best_of=self.best_of,\n top_k=self.top_k,\n ignore_eos=self.ignore_eos,\n use_beam_search=self.use_beam_search,\n early_stopping=self.early_stopping,\n skip_special_tokens=self.skip_special_tokens,\n spaces_between_special_tokens=self.spaces_between_special_tokens,\n include_stop_str_in_output=self.include_stop_str_in_output,\n length_penalty=self.length_penalty,\n logits_processors=logits_processors,\n )\n\n @model_validator(mode='before')\n @classmethod\n def validate_stream_options(cls, values):\n if (values.get('stream_options') is not None\n and not values.get('stream')):\n raise ValueError(\n \"stream_options can only be set if stream is true\")\n return values\n\n @model_validator(mode=\"before\")\n @classmethod\n def check_guided_decoding_count(cls, data):\n guide_count = sum([\n \"guided_json\" in data and data[\"guided_json\"] is not None,\n \"guided_regex\" in data and data[\"guided_regex\"] is not None,\n \"guided_choice\" in data and data[\"guided_choice\"] is not None\n ])\n # you can only use one kind of guided decoding\n if guide_count > 1:\n raise ValueError(\n \"You can only use one kind of guided decoding \"\n \"('guided_json', 'guided_regex' or 'guided_choice').\")\n # you can only either use guided decoding or tools, not both\n if guide_count > 1 and \"tool_choice\" in data and data[\n \"tool_choice\"] != \"none\":\n raise ValueError(\n \"You can only either use guided decoding or tools, not both.\")\n return data\n\n @model_validator(mode=\"before\")\n @classmethod\n def check_tool_choice(cls, data):\n if \"tool_choice\" in data and data[\"tool_choice\"] != \"none\":\n if not isinstance(data[\"tool_choice\"], dict):\n raise ValueError(\"Currently only named tools are supported.\")\n if \"tools\" not in data or data[\"tools\"] is None:\n raise ValueError(\n \"When using `tool_choice`, `tools` must be set.\")\n return data\n\n @model_validator(mode=\"before\")\n @classmethod\n def check_logprobs(cls, data):\n if \"top_logprobs\" in data and data[\"top_logprobs\"] is not None:\n if \"logprobs\" not in data or data[\"logprobs\"] is False:\n raise ValueError(\n \"when using `top_logprobs`, `logprobs` must be set to true.\"\n )\n elif not 0 <= data[\"top_logprobs\"] <= 20:\n raise ValueError(\n \"`top_logprobs` must be a value in the interval [0, 20].\")\n return data\n\n\nclass CompletionRequest(OpenAIBaseModel):\n # Ordered by official OpenAI API documentation\n # https://platform.openai.com/docs/api-reference/completions/create\n model: str\n prompt: Union[List[int], List[List[int]], str, List[str]]\n best_of: Optional[int] = None\n echo: Optional[bool] = False\n frequency_penalty: Optional[float] = 0.0\n logit_bias: Optional[Dict[str, float]] = None\n logprobs: Optional[int] = None\n max_tokens: Optional[int] = 16\n n: int = 1\n presence_penalty: Optional[float] = 0.0\n seed: Optional[int] = Field(None,\n ge=torch.iinfo(torch.long).min,\n le=torch.iinfo(torch.long).max)\n stop: Optional[Union[str, List[str]]] = Field(default_factory=list)\n stream: Optional[bool] = False\n suffix: Optional[str] = None\n temperature: Optional[float] = 1.0\n top_p: Optional[float] = 1.0\n user: Optional[str] = None\n\n # doc: begin-completion-sampling-params\n use_beam_search: Optional[bool] = False\n top_k: Optional[int] = -1\n min_p: Optional[float] = 0.0\n repetition_penalty: Optional[float] = 1.0\n length_penalty: Optional[float] = 1.0\n early_stopping: Optional[bool] = False\n stop_token_ids: Optional[List[int]] = Field(default_factory=list)\n ignore_eos: Optional[bool] = False\n min_tokens: Optional[int] = 0\n skip_special_tokens: Optional[bool] = True\n spaces_between_special_tokens: Optional[bool] = True\n truncate_prompt_tokens: Optional[Annotated[int, Field(ge=1)]] = None\n # doc: end-completion-sampling-params\n\n # doc: begin-completion-extra-params\n include_stop_str_in_output: Optional[bool] = Field(\n default=False,\n description=(\n \"Whether to include the stop string in the output. \"\n \"This is only applied when the stop or stop_token_ids is set.\"),\n )\n response_format: Optional[ResponseFormat] = Field(\n default=None,\n description=\n (\"Similar to chat completion, this parameter specifies the format of \"\n \"output. Only {'type': 'json_object'} or {'type': 'text' } is \"\n \"supported.\"),\n )\n guided_json: Optional[Union[str, dict, BaseModel]] = Field(\n default=None,\n description=(\"If specified, the output will follow the JSON schema.\"),\n )\n guided_regex: Optional[str] = Field(\n default=None,\n description=(\n \"If specified, the output will follow the regex pattern.\"),\n )\n guided_choice: Optional[List[str]] = Field(\n default=None,\n description=(\n \"If specified, the output will be exactly one of the choices.\"),\n )\n guided_grammar: Optional[str] = Field(\n default=None,\n description=(\n \"If specified, the output will follow the context free grammar.\"),\n )\n guided_decoding_backend: Optional[str] = Field(\n default=None,\n description=(\n \"If specified, will override the default guided decoding backend \"\n \"of the server for this specific request. If set, must be one of \"\n \"'outlines' / 'lm-format-enforcer'\"))\n guided_whitespace_pattern: Optional[str] = Field(\n default=None,\n description=(\n \"If specified, will override the default whitespace pattern \"\n \"for guided json decoding.\"))\n\n # doc: end-completion-extra-params\n\n def to_sampling_params(self):\n echo_without_generation = self.echo and self.max_tokens == 0\n\n logits_processors = None\n if self.logit_bias:\n\n def logit_bias_logits_processor(\n token_ids: List[int],\n logits: torch.Tensor) -> torch.Tensor:\n assert self.logit_bias is not None\n for token_id, bias in self.logit_bias.items():\n # Clamp the bias between -100 and 100 per OpenAI API spec\n bias = min(100, max(-100, bias))\n logits[int(token_id)] += bias\n return logits\n\n logits_processors = [logit_bias_logits_processor]\n\n return SamplingParams(\n n=self.n,\n best_of=self.best_of,\n presence_penalty=self.presence_penalty,\n frequency_penalty=self.frequency_penalty,\n repetition_penalty=self.repetition_penalty,\n temperature=self.temperature,\n top_p=self.top_p,\n top_k=self.top_k,\n min_p=self.min_p,\n seed=self.seed,\n stop=self.stop,\n stop_token_ids=self.stop_token_ids,\n ignore_eos=self.ignore_eos,\n max_tokens=self.max_tokens if not echo_without_generation else 1,\n min_tokens=self.min_tokens,\n logprobs=self.logprobs,\n use_beam_search=self.use_beam_search,\n early_stopping=self.early_stopping,\n prompt_logprobs=self.logprobs if self.echo else None,\n skip_special_tokens=self.skip_special_tokens,\n spaces_between_special_tokens=(self.spaces_between_special_tokens),\n include_stop_str_in_output=self.include_stop_str_in_output,\n length_penalty=self.length_penalty,\n logits_processors=logits_processors,\n truncate_prompt_tokens=self.truncate_prompt_tokens,\n )\n\n @model_validator(mode=\"before\")\n @classmethod\n def check_guided_decoding_count(cls, data):\n guide_count = sum([\n \"guided_json\" in data and data[\"guided_json\"] is not None,\n \"guided_regex\" in data and data[\"guided_regex\"] is not None,\n \"guided_choice\" in data and data[\"guided_choice\"] is not None\n ])\n if guide_count > 1:\n raise ValueError(\n \"You can only use one kind of guided decoding \"\n \"('guided_json', 'guided_regex' or 'guided_choice').\")\n return data\n\n @model_validator(mode=\"before\")\n @classmethod\n def check_logprobs(cls, data):\n if \"logprobs\" in data and data[\n \"logprobs\"] is not None and not 0 <= data[\"logprobs\"] <= 5:\n raise ValueError((\"if passed, `logprobs` must be a value\",\n \" in the interval [0, 5].\"))\n return data\n\n\nclass EmbeddingRequest(BaseModel):\n # Ordered by official OpenAI API documentation\n # https://platform.openai.com/docs/api-reference/embeddings\n model: str\n input: Union[List[int], List[List[int]], str, List[str]]\n encoding_format: Optional[str] = Field('float', pattern='^(float|base64)$')\n dimensions: Optional[int] = None\n user: Optional[str] = None\n\n # doc: begin-embedding-pooling-params\n additional_data: Optional[Any] = None\n\n # doc: end-embedding-pooling-params\n\n def to_pooling_params(self):\n return PoolingParams(additional_data=self.additional_data)\n\n\nclass CompletionLogProbs(OpenAIBaseModel):\n text_offset: List[int] = Field(default_factory=list)\n token_logprobs: List[Optional[float]] = Field(default_factory=list)\n tokens: List[str] = Field(default_factory=list)\n top_logprobs: Optional[List[Optional[Dict[str, float]]]] = None\n\n\nclass CompletionResponseChoice(OpenAIBaseModel):\n index: int\n text: str\n logprobs: Optional[CompletionLogProbs] = None\n finish_reason: Optional[str] = None\n stop_reason: Optional[Union[int, str]] = Field(\n default=None,\n description=(\n \"The stop string or token id that caused the completion \"\n \"to stop, None if the completion finished for some other reason \"\n \"including encountering the EOS token\"),\n )\n\n\nclass CompletionResponse(OpenAIBaseModel):\n id: str = Field(default_factory=lambda: f\"cmpl-{random_uuid()}\")\n object: str = \"text_completion\"\n created: int = Field(default_factory=lambda: int(time.time()))\n model: str\n choices: List[CompletionResponseChoice]\n usage: UsageInfo\n\n\nclass CompletionResponseStreamChoice(OpenAIBaseModel):\n index: int\n text: str\n logprobs: Optional[CompletionLogProbs] = None\n finish_reason: Optional[str] = None\n stop_reason: Optional[Union[int, str]] = Field(\n default=None,\n description=(\n \"The stop string or token id that caused the completion \"\n \"to stop, None if the completion finished for some other reason \"\n \"including encountering the EOS token\"),\n )\n\n\nclass CompletionStreamResponse(OpenAIBaseModel):\n id: str = Field(default_factory=lambda: f\"cmpl-{random_uuid()}\")\n object: str = \"text_completion\"\n created: int = Field(default_factory=lambda: int(time.time()))\n model: str\n choices: List[CompletionResponseStreamChoice]\n usage: Optional[UsageInfo] = Field(default=None)\n\n\nclass EmbeddingResponseData(BaseModel):\n index: int\n object: str = \"embedding\"\n embedding: List[float]\n\n\nclass EmbeddingResponse(BaseModel):\n id: str = Field(default_factory=lambda: f\"cmpl-{random_uuid()}\")\n object: str = \"list\"\n created: int = Field(default_factory=lambda: int(time.time()))\n model: str\n data: List[EmbeddingResponseData]\n usage: UsageInfo\n\n\nclass FunctionCall(OpenAIBaseModel):\n name: str\n arguments: str\n\n\nclass ToolCall(OpenAIBaseModel):\n id: str = Field(default_factory=lambda: f\"chatcmpl-tool-{random_uuid()}\")\n type: Literal[\"function\"] = \"function\"\n function: FunctionCall\n\n\nclass ChatMessage(OpenAIBaseModel):\n role: str\n content: str\n tool_calls: List[ToolCall] = Field(default_factory=list)\n\n\nclass ChatCompletionLogProb(OpenAIBaseModel):\n token: str\n logprob: float = -9999.0\n bytes: Optional[List[int]] = None\n\n\nclass ChatCompletionLogProbsContent(ChatCompletionLogProb):\n top_logprobs: List[ChatCompletionLogProb] = Field(default_factory=list)\n\n\nclass ChatCompletionLogProbs(OpenAIBaseModel):\n content: Optional[List[ChatCompletionLogProbsContent]] = None\n\n\nclass ChatCompletionResponseChoice(OpenAIBaseModel):\n index: int\n message: ChatMessage\n logprobs: Optional[ChatCompletionLogProbs] = None\n finish_reason: Optional[Literal[\"stop\", \"length\", \"tool_calls\"]] = None\n stop_reason: Optional[Union[int, str]] = None\n\n\nclass ChatCompletionResponse(OpenAIBaseModel):\n id: str = Field(default_factory=lambda: f\"chatcmpl-{random_uuid()}\")\n object: Literal[\"chat.completion\"] = \"chat.completion\"\n created: int = Field(default_factory=lambda: int(time.time()))\n model: str\n choices: List[ChatCompletionResponseChoice]\n usage: UsageInfo\n\n\nclass DeltaMessage(OpenAIBaseModel):\n role: Optional[str] = None\n content: Optional[str] = None\n tool_calls: List[ToolCall] = Field(default_factory=list)\n\n\nclass ChatCompletionResponseStreamChoice(OpenAIBaseModel):\n index: int\n delta: DeltaMessage\n logprobs: Optional[ChatCompletionLogProbs] = None\n finish_reason: Optional[Literal[\"stop\", \"length\", \"tool_calls\"]] = None\n stop_reason: Optional[Union[int, str]] = None\n\n\nclass ChatCompletionStreamResponse(OpenAIBaseModel):\n id: str = Field(default_factory=lambda: f\"chatcmpl-{random_uuid()}\")\n object: Literal[\"chat.completion.chunk\"] = \"chat.completion.chunk\"\n created: int = Field(default_factory=lambda: int(time.time()))\n model: str\n choices: List[ChatCompletionResponseStreamChoice]\n usage: Optional[UsageInfo] = Field(default=None)\n\n\nclass BatchRequestInput(OpenAIBaseModel):\n \"\"\"\n The per-line object of the batch input file.\n\n NOTE: Currently only the `/v1/chat/completions` endpoint is supported.\n \"\"\"\n\n # A developer-provided per-request id that will be used to match outputs to\n # inputs. Must be unique for each request in a batch.\n custom_id: str\n\n # The HTTP method to be used for the request. Currently only POST is\n # supported.\n method: str\n\n # The OpenAI API relative URL to be used for the request. Currently\n # /v1/chat/completions is supported.\n url: str\n\n # The parameteters of the request.\n body: Union[ChatCompletionRequest, ]\n\n\nclass BatchRequestOutput(OpenAIBaseModel):\n \"\"\"\n The per-line object of the batch output and error files\n \"\"\"\n\n id: str\n\n # A developer-provided per-request id that will be used to match outputs to\n # inputs.\n custom_id: str\n\n response: Optional[ChatCompletionResponse]\n\n # For requests that failed with a non-HTTP error, this will contain more\n # information on the cause of the failure.\n error: Optional[Any]\n", "path": "vllm/entrypoints/openai/protocol.py" } ]
[ { "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 import AsyncLLMEngine\n# yapf: disable\nfrom vllm.entrypoints.openai.protocol import (CompletionLogProbs,\n CompletionRequest,\n CompletionResponse,\n CompletionResponseChoice,\n CompletionResponseStreamChoice,\n CompletionStreamResponse,\n UsageInfo)\n# yapf: enable\nfrom vllm.entrypoints.openai.serving_engine import (LoRAModulePath,\n OpenAIServing)\nfrom vllm.logger import init_logger\nfrom vllm.model_executor.guided_decoding import (\n get_guided_decoding_logits_processor)\nfrom vllm.outputs import RequestOutput\nfrom vllm.sequence import Logprob\nfrom vllm.utils import merge_async_iterators, random_uuid\n\nlogger = init_logger(__name__)\n\nTypeTokenIDs = List[int]\nTypeTopLogProbs = List[Optional[Dict[int, float]]]\nTypeCreateLogProbsFn = Callable[\n [TypeTokenIDs, TypeTopLogProbs, Optional[int], int], CompletionLogProbs]\n\n\ndef parse_prompt_format(prompt) -> Tuple[bool, list]:\n # get the prompt, openai supports the following\n # \"a string, array of strings, array of tokens, or array of token arrays.\"\n prompt_is_tokens = False\n prompts = [prompt] # case 1: a string\n if isinstance(prompt, list):\n if len(prompt) == 0:\n raise ValueError(\"please provide at least one prompt\")\n elif isinstance(prompt[0], str):\n prompt_is_tokens = False\n prompts = prompt # case 2: array of strings\n elif isinstance(prompt[0], int):\n prompt_is_tokens = True\n prompts = [prompt] # case 3: array of tokens\n elif isinstance(prompt[0], list) and isinstance(prompt[0][0], int):\n prompt_is_tokens = True\n prompts = prompt # case 4: array of token arrays\n else:\n raise ValueError(\"prompt must be a string, array of strings, \"\n \"array of tokens, or array of token arrays\")\n return prompt_is_tokens, prompts\n\n\nclass OpenAIServingCompletion(OpenAIServing):\n\n def __init__(self, engine: AsyncLLMEngine, model_config: ModelConfig,\n served_model_names: List[str],\n lora_modules: Optional[List[LoRAModulePath]]):\n super().__init__(engine=engine,\n model_config=model_config,\n served_model_names=served_model_names,\n lora_modules=lora_modules)\n\n async def create_completion(self, request: CompletionRequest,\n raw_request: Request):\n \"\"\"Completion API similar to OpenAI's API.\n\n See https://platform.openai.com/docs/api-reference/completions/create\n for the API specification. This API mimics the OpenAI Completion API.\n\n NOTE: Currently we do not support the following feature:\n - suffix (the language models we currently support do not support\n suffix)\n \"\"\"\n error_check_ret = await self._check_model(request)\n if error_check_ret is not None:\n return error_check_ret\n\n # Return error for unsupported features.\n if request.suffix is not None:\n return self.create_error_response(\n \"suffix is not currently supported\")\n\n model_name = self.served_model_names[0]\n request_id = f\"cmpl-{random_uuid()}\"\n created_time = int(time.time())\n\n # Schedule the request and get the result generator.\n generators: List[AsyncIterator[RequestOutput]] = []\n try:\n sampling_params = request.to_sampling_params()\n lora_request = self._maybe_get_lora(request)\n decoding_config = await self.engine.get_decoding_config()\n guided_decoding_backend = request.guided_decoding_backend \\\n or decoding_config.guided_decoding_backend\n guided_decode_logit_processor = (\n await get_guided_decoding_logits_processor(\n guided_decoding_backend, request, await\n self.engine.get_tokenizer()))\n if guided_decode_logit_processor is not None:\n if sampling_params.logits_processors is None:\n sampling_params.logits_processors = []\n sampling_params.logits_processors.append(\n guided_decode_logit_processor)\n prompt_is_tokens, prompts = parse_prompt_format(request.prompt)\n\n for i, prompt in enumerate(prompts):\n if prompt_is_tokens:\n prompt_formats = self._validate_prompt_and_tokenize(\n request,\n prompt_ids=prompt,\n truncate_prompt_tokens=sampling_params.\n truncate_prompt_tokens)\n else:\n prompt_formats = self._validate_prompt_and_tokenize(\n request,\n prompt=prompt,\n truncate_prompt_tokens=sampling_params.\n truncate_prompt_tokens)\n prompt_ids, prompt_text = prompt_formats\n\n generator = self.engine.generate(\n {\n \"prompt\": prompt_text,\n \"prompt_token_ids\": prompt_ids\n },\n sampling_params,\n f\"{request_id}-{i}\",\n lora_request=lora_request,\n )\n\n generators.append(generator)\n except ValueError as e:\n # TODO: Use a vllm-specific Validation Error\n return self.create_error_response(str(e))\n\n result_generator: AsyncIterator[Tuple[\n int, RequestOutput]] = merge_async_iterators(*generators)\n\n # Similar to the OpenAI API, when n != best_of, we do not stream the\n # results. In addition, we do not stream the results when use\n # beam search.\n stream = (request.stream\n and (request.best_of is None or request.n == request.best_of)\n and not request.use_beam_search)\n\n # Streaming response\n if stream:\n return self.completion_stream_generator(request,\n raw_request,\n result_generator,\n request_id,\n created_time,\n model_name,\n num_prompts=len(prompts))\n\n # Non-streaming response\n final_res_batch: List[Optional[RequestOutput]] = [None] * len(prompts)\n try:\n async for i, res in result_generator:\n if await raw_request.is_disconnected():\n # Abort the request if the client disconnects.\n await self.engine.abort(f\"{request_id}-{i}\")\n return self.create_error_response(\"Client disconnected\")\n final_res_batch[i] = res\n response = self.request_output_to_completion_response(\n final_res_batch, request, request_id, created_time, model_name)\n except ValueError as e:\n # TODO: Use a vllm-specific Validation Error\n return self.create_error_response(str(e))\n\n # When user requests streaming but we don't stream, we still need to\n # return a streaming response with a single event.\n if request.stream:\n response_json = response.model_dump_json()\n\n async def fake_stream_generator() -> AsyncGenerator[str, None]:\n yield f\"data: {response_json}\\n\\n\"\n yield \"data: [DONE]\\n\\n\"\n\n return fake_stream_generator()\n\n return response\n\n async def completion_stream_generator(\n self,\n request: CompletionRequest,\n raw_request: Request,\n result_generator: AsyncIterator[Tuple[int, RequestOutput]],\n request_id: str,\n created_time: int,\n model_name: str,\n num_prompts: int,\n ) -> AsyncGenerator[str, None]:\n assert request.n is not None\n previous_texts = [\"\"] * request.n * num_prompts\n previous_num_tokens = [0] * request.n * num_prompts\n has_echoed = [False] * request.n * num_prompts\n\n try:\n async for prompt_idx, res in result_generator:\n\n # Abort the request if the client disconnects.\n if await raw_request.is_disconnected():\n await self.engine.abort(f\"{request_id}-{prompt_idx}\")\n raise StopAsyncIteration()\n\n for output in res.outputs:\n i = output.index + prompt_idx * request.n\n # TODO(simon): optimize the performance by avoiding full\n # text O(n^2) sending.\n\n assert request.max_tokens is not None\n if request.echo and request.max_tokens == 0:\n # only return the prompt\n delta_text = res.prompt\n delta_token_ids = res.prompt_token_ids\n top_logprobs = res.prompt_logprobs\n has_echoed[i] = True\n elif (request.echo and request.max_tokens > 0\n and not has_echoed[i]):\n # echo the prompt and first token\n delta_text = res.prompt + output.text\n delta_token_ids = (res.prompt_token_ids +\n output.token_ids)\n top_logprobs = res.prompt_logprobs + (output.logprobs\n or [])\n has_echoed[i] = True\n else:\n # return just the delta\n delta_text = output.text[len(previous_texts[i]):]\n delta_token_ids = output.token_ids[\n previous_num_tokens[i]:]\n top_logprobs = output.logprobs[previous_num_tokens[\n i]:] if output.logprobs else None\n\n if request.logprobs is not None:\n logprobs = self._create_completion_logprobs(\n token_ids=delta_token_ids,\n top_logprobs=top_logprobs,\n num_output_top_logprobs=request.logprobs,\n initial_text_offset=len(previous_texts[i]),\n )\n else:\n logprobs = None\n\n previous_texts[i] = output.text\n previous_num_tokens[i] = len(output.token_ids)\n finish_reason = output.finish_reason\n stop_reason = output.stop_reason\n if output.finish_reason is not None: # return final usage\n prompt_tokens = len(res.prompt_token_ids)\n completion_tokens = len(output.token_ids)\n final_usage = UsageInfo(\n prompt_tokens=prompt_tokens,\n completion_tokens=completion_tokens,\n total_tokens=prompt_tokens + completion_tokens,\n )\n else:\n final_usage = None\n\n chunk = CompletionStreamResponse(\n id=request_id,\n created=created_time,\n model=model_name,\n choices=[\n CompletionResponseStreamChoice(\n index=i,\n text=delta_text,\n logprobs=logprobs,\n finish_reason=finish_reason,\n stop_reason=stop_reason,\n )\n ])\n if (request.stream_options\n and request.stream_options.include_usage):\n chunk.usage = None\n\n response_json = chunk.model_dump_json(exclude_unset=True)\n yield f\"data: {response_json}\\n\\n\"\n\n if (request.stream_options\n and request.stream_options.include_usage):\n final_usage_chunk = CompletionStreamResponse(\n id=request_id,\n created=created_time,\n model=model_name,\n choices=[],\n usage=final_usage,\n )\n final_usage_data = (final_usage_chunk.model_dump_json(\n exclude_unset=True, exclude_none=True))\n yield f\"data: {final_usage_data}\\n\\n\"\n\n except ValueError as e:\n # TODO: Use a vllm-specific Validation Error\n data = self.create_streaming_error_response(str(e))\n yield f\"data: {data}\\n\\n\"\n yield \"data: [DONE]\\n\\n\"\n\n def request_output_to_completion_response(\n self,\n final_res_batch: List[RequestOutput],\n request: CompletionRequest,\n request_id: str,\n created_time: int,\n model_name: str,\n ) -> CompletionResponse:\n choices: List[CompletionResponseChoice] = []\n num_prompt_tokens = 0\n num_generated_tokens = 0\n for final_res in final_res_batch:\n assert final_res is not None\n prompt_token_ids = final_res.prompt_token_ids\n prompt_logprobs = final_res.prompt_logprobs\n prompt_text = final_res.prompt\n\n for output in final_res.outputs:\n assert request.max_tokens is not None\n if request.echo and request.max_tokens == 0:\n token_ids = prompt_token_ids\n top_logprobs = prompt_logprobs\n output_text = prompt_text\n elif request.echo and request.max_tokens > 0:\n token_ids = prompt_token_ids + output.token_ids\n top_logprobs = (prompt_logprobs + output.logprobs\n if request.logprobs is not None else None)\n output_text = prompt_text + output.text\n else:\n token_ids = output.token_ids\n top_logprobs = output.logprobs\n output_text = output.text\n\n if request.logprobs is not None:\n assert top_logprobs is not None, (\n \"top_logprobs must be provided when logprobs \"\n \"is requested\")\n logprobs = self._create_completion_logprobs(\n token_ids=token_ids,\n top_logprobs=top_logprobs,\n num_output_top_logprobs=request.logprobs,\n )\n else:\n logprobs = None\n\n choice_data = CompletionResponseChoice(\n index=len(choices),\n text=output_text,\n logprobs=logprobs,\n finish_reason=output.finish_reason,\n stop_reason=output.stop_reason,\n )\n choices.append(choice_data)\n\n num_prompt_tokens += len(prompt_token_ids)\n num_generated_tokens += sum(\n len(output.token_ids) for output in final_res.outputs)\n\n usage = UsageInfo(\n prompt_tokens=num_prompt_tokens,\n completion_tokens=num_generated_tokens,\n total_tokens=num_prompt_tokens + num_generated_tokens,\n )\n\n return CompletionResponse(\n id=request_id,\n created=created_time,\n model=model_name,\n choices=choices,\n usage=usage,\n )\n\n def _create_completion_logprobs(\n self,\n token_ids: GenericSequence[int],\n top_logprobs: GenericSequence[Optional[Dict[int, Logprob]]],\n num_output_top_logprobs: int,\n initial_text_offset: int = 0,\n ) -> CompletionLogProbs:\n \"\"\"Create logprobs for OpenAI Completion API.\"\"\"\n out_text_offset: List[int] = []\n out_token_logprobs: List[Optional[float]] = []\n out_tokens: List[str] = []\n out_top_logprobs: List[Optional[Dict[str, float]]] = []\n\n last_token_len = 0\n\n for i, token_id in enumerate(token_ids):\n step_top_logprobs = top_logprobs[i]\n if step_top_logprobs is None:\n token = self.tokenizer.decode(token_id)\n out_tokens.append(token)\n out_token_logprobs.append(None)\n out_top_logprobs.append(None)\n else:\n token = self._get_decoded_token(step_top_logprobs[token_id],\n token_id)\n token_logprob = max(step_top_logprobs[token_id].logprob,\n -9999.0)\n out_tokens.append(token)\n out_token_logprobs.append(token_logprob)\n\n # makes sure to add the top num_output_top_logprobs + 1\n # logprobs, as defined in the openai API\n # (cf. https://github.com/openai/openai-openapi/blob/\n # 893ba52242dbd5387a97b96444ee1c742cfce9bd/openapi.yaml#L7153)\n out_top_logprobs.append({\n # Convert float(\"-inf\") to the\n # JSON-serializable float that OpenAI uses\n self._get_decoded_token(top_lp[1], top_lp[0]):\n max(top_lp[1].logprob, -9999.0)\n for i, top_lp in enumerate(step_top_logprobs.items())\n if num_output_top_logprobs >= i\n })\n\n if len(out_text_offset) == 0:\n out_text_offset.append(initial_text_offset)\n else:\n out_text_offset.append(out_text_offset[-1] + last_token_len)\n last_token_len = len(token)\n\n return CompletionLogProbs(\n text_offset=out_text_offset,\n token_logprobs=out_token_logprobs,\n tokens=out_tokens,\n top_logprobs=out_top_logprobs,\n )\n", "path": "vllm/entrypoints/openai/serving_completion.py" }, { "content": "import codecs\nimport time\nfrom dataclasses import dataclass, field\nfrom typing import (AsyncGenerator, AsyncIterator, Awaitable, Dict, Iterable,\n List, Optional)\nfrom typing import Sequence as GenericSequence\nfrom typing import TypedDict, Union, cast, final\n\nfrom fastapi import Request\nfrom openai.types.chat import (ChatCompletionContentPartImageParam,\n ChatCompletionContentPartTextParam)\n\nfrom vllm.config import ModelConfig, VisionLanguageConfig\nfrom vllm.engine.async_llm_engine import AsyncLLMEngine\nfrom vllm.entrypoints.openai.protocol import (\n ChatCompletionContentPartParam, ChatCompletionLogProb,\n ChatCompletionLogProbs, ChatCompletionLogProbsContent,\n ChatCompletionMessageParam, ChatCompletionNamedToolChoiceParam,\n ChatCompletionRequest, ChatCompletionResponse,\n ChatCompletionResponseChoice, ChatCompletionResponseStreamChoice,\n ChatCompletionStreamResponse, ChatMessage, DeltaMessage, ErrorResponse,\n FunctionCall, ToolCall, UsageInfo)\nfrom vllm.entrypoints.openai.serving_engine import (LoRAModulePath,\n OpenAIServing)\nfrom vllm.inputs import PromptInputs\nfrom vllm.logger import init_logger\nfrom vllm.model_executor.guided_decoding import (\n get_guided_decoding_logits_processor)\nfrom vllm.multimodal.image import ImagePixelData\nfrom vllm.multimodal.utils import (async_get_and_parse_image,\n get_full_image_text_prompt)\nfrom vllm.outputs import RequestOutput\nfrom vllm.sequence import Logprob\nfrom vllm.utils import random_uuid\n\nlogger = init_logger(__name__)\n\n\n@final # So that it should be compatible with Dict[str, str]\nclass ConversationMessage(TypedDict):\n role: str\n content: str\n\n\n@dataclass(frozen=True)\nclass ChatMessageParseResult:\n messages: List[ConversationMessage]\n image_futures: List[Awaitable[ImagePixelData]] = field(\n default_factory=list)\n\n\nclass OpenAIServingChat(OpenAIServing):\n\n def __init__(self,\n engine: AsyncLLMEngine,\n model_config: ModelConfig,\n served_model_names: List[str],\n response_role: str,\n lora_modules: Optional[List[LoRAModulePath]] = None,\n chat_template: Optional[str] = None):\n super().__init__(engine=engine,\n model_config=model_config,\n served_model_names=served_model_names,\n lora_modules=lora_modules)\n\n self.response_role = response_role\n self._load_chat_template(chat_template)\n\n def _load_chat_template(self, chat_template: Optional[str]):\n tokenizer = self.tokenizer\n\n if chat_template is not None:\n try:\n with open(chat_template, \"r\") as f:\n tokenizer.chat_template = f.read()\n except OSError as e:\n JINJA_CHARS = \"{}\\n\"\n if not any(c in chat_template for c in JINJA_CHARS):\n msg = (f\"The supplied chat template ({chat_template}) \"\n f\"looks like a file path, but it failed to be \"\n f\"opened. Reason: {e}\")\n raise ValueError(msg) from e\n\n # If opening a file fails, set chat template to be args to\n # ensure we decode so our escape are interpreted correctly\n tokenizer.chat_template = codecs.decode(\n chat_template, \"unicode_escape\")\n\n logger.info(\"Using supplied chat template:\\n%s\",\n tokenizer.chat_template)\n elif tokenizer.chat_template is not None:\n logger.info(\"Using default chat template:\\n%s\",\n tokenizer.chat_template)\n else:\n logger.warning(\n \"No chat template provided. Chat API will not work.\")\n\n def _parse_chat_message_content_parts(\n self,\n role: str,\n parts: Iterable[ChatCompletionContentPartParam],\n ) -> ChatMessageParseResult:\n texts: List[str] = []\n image_futures: List[Awaitable[ImagePixelData]] = []\n\n vlm_config: Optional[VisionLanguageConfig] = getattr(\n self.engine.engine, \"vision_language_config\", None)\n model_config = getattr(self.engine.engine, \"model_config\", None)\n\n for part in parts:\n part_type = part[\"type\"]\n if part_type == \"text\":\n text = cast(ChatCompletionContentPartTextParam, part)[\"text\"]\n\n texts.append(text)\n elif part_type == \"image_url\":\n if vlm_config is None:\n raise ValueError(\n \"'image_url' input is not supported as the loaded \"\n \"model is not multimodal.\")\n\n elif len(image_futures) == 0:\n assert self.tokenizer is not None\n image_url = cast(ChatCompletionContentPartImageParam,\n part)[\"image_url\"]\n\n if image_url.get(\"detail\", \"auto\") != \"auto\":\n logger.warning(\n \"'image_url.detail' is currently not supported and \"\n \"will be ignored.\")\n\n image_future = async_get_and_parse_image(image_url[\"url\"])\n image_futures.append(image_future)\n\n else:\n raise NotImplementedError(\n \"Multiple 'image_url' input is currently not supported.\"\n )\n\n else:\n raise NotImplementedError(f\"Unknown part type: {part_type}\")\n\n text_prompt = \"\\n\".join(texts)\n\n if vlm_config is not None and len(image_futures):\n\n (image_token_prompt,\n image_token_str) = vlm_config.get_image_token_text(self.tokenizer)\n\n # NOTE: If image token string (e.g, <image>) is already present\n # in the text prompt, we assume it follows the same format required\n # by the engine.\n if image_token_str in text_prompt:\n logger.warning(\n \"Detected image token string in the text prompt. \"\n \"Skipping prompt formatting.\")\n messages = [\n ConversationMessage(role=role, content=text_prompt)\n ]\n\n else:\n full_prompt = get_full_image_text_prompt(\n image_prompt=image_token_prompt,\n text_prompt=text_prompt,\n config=model_config)\n messages = [\n ConversationMessage(role=role, content=full_prompt)\n ]\n else:\n messages = [ConversationMessage(role=role, content=text_prompt)]\n\n return ChatMessageParseResult(messages=messages,\n image_futures=image_futures)\n\n def _parse_chat_message_content(\n self,\n message: ChatCompletionMessageParam,\n ) -> ChatMessageParseResult:\n role = message[\"role\"]\n content = message.get(\"content\")\n\n if content is None:\n return ChatMessageParseResult(messages=[], image_futures=[])\n if isinstance(content, str):\n messages = [ConversationMessage(role=role, content=content)]\n return ChatMessageParseResult(messages=messages, image_futures=[])\n\n return self._parse_chat_message_content_parts(role, content)\n\n async def create_chat_completion(\n self,\n request: ChatCompletionRequest,\n raw_request: Optional[Request] = None\n ) -> Union[ErrorResponse, AsyncGenerator[str, None],\n ChatCompletionResponse]:\n \"\"\"Completion API similar to OpenAI's API.\n\n See https://platform.openai.com/docs/api-reference/chat/create\n for the API specification. This API mimics the OpenAI\n ChatCompletion API.\n\n NOTE: Currently we do not support the following feature:\n - function_call (Users should implement this by themselves)\n \"\"\"\n error_check_ret = await self._check_model(request)\n if error_check_ret is not None:\n return error_check_ret\n\n try:\n conversation: List[ConversationMessage] = []\n image_futures: List[Awaitable[ImagePixelData]] = []\n\n for msg in request.messages:\n chat_parsed_result = self._parse_chat_message_content(msg)\n\n conversation.extend(chat_parsed_result.messages)\n image_futures.extend(chat_parsed_result.image_futures)\n\n prompt = self.tokenizer.apply_chat_template(\n conversation=conversation,\n tokenize=False,\n add_generation_prompt=request.add_generation_prompt,\n )\n except Exception as e:\n logger.error(\"Error in applying chat template from request: %s\", e)\n return self.create_error_response(str(e))\n\n # Fetch image data\n image_data: Optional[ImagePixelData] = None\n try:\n if len(image_futures):\n # since we support only single image currently\n assert len(image_futures) == 1\n image_data = await image_futures[0]\n except Exception as e:\n logger.error(\"Error in loading image data: %s\", e)\n return self.create_error_response(str(e))\n\n request_id = f\"cmpl-{random_uuid()}\"\n try:\n # Tokenize/detokenize depending on prompt format (string/token list)\n prompt_ids, prompt_text = self._validate_prompt_and_tokenize(\n request,\n prompt=prompt,\n add_special_tokens=request.add_special_tokens)\n sampling_params = request.to_sampling_params()\n lora_request = self._maybe_get_lora(request)\n decoding_config = await self.engine.get_decoding_config()\n guided_decoding_backend = request.guided_decoding_backend \\\n or decoding_config.guided_decoding_backend\n guided_decode_logits_processor = (\n await get_guided_decoding_logits_processor(\n guided_decoding_backend, request, await\n self.engine.get_tokenizer()))\n if guided_decode_logits_processor:\n if sampling_params.logits_processors is None:\n sampling_params.logits_processors = []\n sampling_params.logits_processors.append(\n guided_decode_logits_processor)\n except ValueError as e:\n return self.create_error_response(str(e))\n\n inputs: PromptInputs = {\n \"prompt\": prompt_text,\n \"prompt_token_ids\": prompt_ids,\n }\n if image_data is not None:\n inputs[\"multi_modal_data\"] = image_data\n\n result_generator = self.engine.generate(\n inputs,\n sampling_params,\n request_id,\n lora_request,\n )\n # Streaming response\n if request.stream:\n return self.chat_completion_stream_generator(\n request, result_generator, request_id, conversation)\n else:\n try:\n return await self.chat_completion_full_generator(\n request, raw_request, result_generator, request_id,\n conversation)\n except ValueError as e:\n # TODO: Use a vllm-specific Validation Error\n return self.create_error_response(str(e))\n\n def get_chat_request_role(self, request: ChatCompletionRequest) -> str:\n if request.add_generation_prompt:\n return self.response_role\n else:\n return request.messages[-1][\"role\"]\n\n async def chat_completion_stream_generator(\n self, request: ChatCompletionRequest,\n result_generator: AsyncIterator[RequestOutput], request_id: str,\n conversation: List[ConversationMessage]\n ) -> AsyncGenerator[str, None]:\n model_name = self.served_model_names[0]\n created_time = int(time.time())\n chunk_object_type = \"chat.completion.chunk\"\n first_iteration = True\n\n # Send response for each token for each request.n (index)\n assert request.n is not None\n previous_texts = [\"\"] * request.n\n previous_num_tokens = [0] * request.n\n finish_reason_sent = [False] * request.n\n try:\n async for res in result_generator:\n # We need to do it here, because if there are exceptions in\n # the result_generator, it needs to be sent as the FIRST\n # response (by the try...catch).\n if first_iteration:\n # Send first response for each request.n (index) with\n # the role\n role = self.get_chat_request_role(request)\n for i in range(request.n):\n choice_data = ChatCompletionResponseStreamChoice(\n index=i,\n delta=DeltaMessage(role=role),\n logprobs=None,\n finish_reason=None)\n chunk = ChatCompletionStreamResponse(\n id=request_id,\n object=chunk_object_type,\n created=created_time,\n choices=[choice_data],\n model=model_name)\n if (request.stream_options\n and request.stream_options.include_usage):\n chunk.usage = None\n data = chunk.model_dump_json(exclude_unset=True)\n yield f\"data: {data}\\n\\n\"\n\n # Send response to echo the input portion of the\n # last message\n if request.echo:\n last_msg_content = \"\"\n if conversation and conversation[-1].get(\n \"content\") and conversation[-1].get(\n \"role\") == role:\n last_msg_content = conversation[-1][\"content\"]\n\n if last_msg_content:\n for i in range(request.n):\n choice_data = (\n ChatCompletionResponseStreamChoice(\n index=i,\n delta=DeltaMessage(\n content=last_msg_content),\n finish_reason=None))\n chunk = ChatCompletionStreamResponse(\n id=request_id,\n object=chunk_object_type,\n created=created_time,\n choices=[choice_data],\n logprobs=None,\n model=model_name)\n if (request.stream_options and\n request.stream_options.include_usage):\n chunk.usage = None\n data = chunk.model_dump_json(\n exclude_unset=True)\n yield f\"data: {data}\\n\\n\"\n first_iteration = False\n\n for output in res.outputs:\n i = output.index\n\n if finish_reason_sent[i]:\n continue\n\n delta_token_ids = output.token_ids[previous_num_tokens[i]:]\n top_logprobs = output.logprobs[\n previous_num_tokens[i]:] if output.logprobs else None\n\n if request.logprobs:\n logprobs = self._create_chat_logprobs(\n token_ids=delta_token_ids,\n top_logprobs=top_logprobs,\n num_output_top_logprobs=request.top_logprobs,\n )\n else:\n logprobs = None\n\n delta_text = output.text[len(previous_texts[i]):]\n previous_texts[i] = output.text\n previous_num_tokens[i] = len(output.token_ids)\n\n if request.tool_choice and type(\n request.tool_choice\n ) is ChatCompletionNamedToolChoiceParam:\n delta_message = DeltaMessage(tool_calls=[\n ToolCall(function=FunctionCall(\n name=request.tool_choice.function.name,\n arguments=delta_text))\n ])\n else:\n delta_message = DeltaMessage(content=delta_text)\n\n if output.finish_reason is None:\n # Send token-by-token response for each request.n\n\n choice_data = ChatCompletionResponseStreamChoice(\n index=i,\n delta=delta_message,\n logprobs=logprobs,\n finish_reason=None)\n chunk = ChatCompletionStreamResponse(\n id=request_id,\n object=chunk_object_type,\n created=created_time,\n choices=[choice_data],\n model=model_name)\n if (request.stream_options\n and request.stream_options.include_usage):\n chunk.usage = None\n data = chunk.model_dump_json(exclude_unset=True)\n yield f\"data: {data}\\n\\n\"\n else:\n # Send the finish response for each request.n only once\n prompt_tokens = len(res.prompt_token_ids)\n choice_data = ChatCompletionResponseStreamChoice(\n index=i,\n delta=delta_message,\n logprobs=logprobs,\n finish_reason=output.finish_reason,\n stop_reason=output.stop_reason)\n chunk = ChatCompletionStreamResponse(\n id=request_id,\n object=chunk_object_type,\n created=created_time,\n choices=[choice_data],\n model=model_name)\n if (request.stream_options\n and request.stream_options.include_usage):\n chunk.usage = None\n data = chunk.model_dump_json(exclude_unset=True)\n yield f\"data: {data}\\n\\n\"\n finish_reason_sent[i] = True\n\n if (request.stream_options\n and request.stream_options.include_usage):\n final_usage = UsageInfo(\n prompt_tokens=prompt_tokens,\n completion_tokens=previous_num_tokens[i],\n total_tokens=prompt_tokens + previous_num_tokens[i],\n )\n\n final_usage_chunk = ChatCompletionStreamResponse(\n id=request_id,\n object=chunk_object_type,\n created=created_time,\n choices=[],\n model=model_name,\n usage=final_usage)\n final_usage_data = (final_usage_chunk.model_dump_json(\n exclude_unset=True, exclude_none=True))\n yield f\"data: {final_usage_data}\\n\\n\"\n\n except ValueError as e:\n # TODO: Use a vllm-specific Validation Error\n data = self.create_streaming_error_response(str(e))\n yield f\"data: {data}\\n\\n\"\n # Send the final done message after all response.n are finished\n yield \"data: [DONE]\\n\\n\"\n\n async def chat_completion_full_generator(\n self, request: ChatCompletionRequest, raw_request: Optional[Request],\n result_generator: AsyncIterator[RequestOutput], request_id: str,\n conversation: List[ConversationMessage]\n ) -> Union[ErrorResponse, ChatCompletionResponse]:\n\n model_name = self.served_model_names[0]\n created_time = int(time.time())\n final_res: Optional[RequestOutput] = None\n\n async for res in result_generator:\n if raw_request is not None and await raw_request.is_disconnected():\n # Abort the request if the client disconnects.\n await self.engine.abort(request_id)\n return self.create_error_response(\"Client disconnected\")\n final_res = res\n assert final_res is not None\n\n choices = []\n\n role = self.get_chat_request_role(request)\n for output in final_res.outputs:\n token_ids = output.token_ids\n top_logprobs = output.logprobs\n\n if request.logprobs:\n logprobs = self._create_chat_logprobs(\n token_ids=token_ids,\n top_logprobs=top_logprobs,\n num_output_top_logprobs=request.top_logprobs,\n )\n else:\n logprobs = None\n\n if request.tool_choice and type(\n request.tool_choice) is ChatCompletionNamedToolChoiceParam:\n message = ChatMessage(\n role=role,\n content=\"\",\n tool_calls=[\n ToolCall(function=FunctionCall(\n name=request.tool_choice.function.name,\n arguments=output.text))\n ])\n elif not request.tool_choice or request.tool_choice == \"none\":\n message = ChatMessage(role=role, content=output.text)\n\n choice_data = ChatCompletionResponseChoice(\n index=output.index,\n message=message,\n logprobs=logprobs,\n finish_reason=output.finish_reason,\n stop_reason=output.stop_reason)\n choices.append(choice_data)\n\n if request.echo:\n last_msg_content = \"\"\n if conversation and conversation[-1].get(\n \"content\") and conversation[-1].get(\"role\") == role:\n last_msg_content = conversation[-1][\"content\"]\n\n for choice in choices:\n full_message = last_msg_content + choice.message.content\n choice.message.content = full_message\n\n num_prompt_tokens = len(final_res.prompt_token_ids)\n num_generated_tokens = sum(\n len(output.token_ids) for output in final_res.outputs)\n usage = UsageInfo(\n prompt_tokens=num_prompt_tokens,\n completion_tokens=num_generated_tokens,\n total_tokens=num_prompt_tokens + num_generated_tokens,\n )\n response = ChatCompletionResponse(\n id=request_id,\n created=created_time,\n model=model_name,\n choices=choices,\n usage=usage,\n )\n\n return response\n\n def _get_top_logprobs(\n self, logprobs: Dict[int, Logprob],\n top_logprobs: Optional[int]) -> List[ChatCompletionLogProb]:\n return [\n ChatCompletionLogProb(\n token=self._get_decoded_token(p[1], p[0]),\n logprob=max(p[1].logprob, -9999.0),\n bytes=list(\n self._get_decoded_token(p[1],\n p[0]).encode(\"utf-8\",\n errors=\"replace\")))\n for i, p in enumerate(logprobs.items())\n if top_logprobs and i < top_logprobs\n ]\n\n def _create_chat_logprobs(\n self,\n token_ids: GenericSequence[int],\n top_logprobs: GenericSequence[Optional[Dict[int, Logprob]]],\n num_output_top_logprobs: Optional[int] = None,\n ) -> ChatCompletionLogProbs:\n \"\"\"Create OpenAI-style logprobs.\"\"\"\n\n logprobs_content = []\n\n for i, token_id in enumerate(token_ids):\n step_top_logprobs = top_logprobs[i]\n if step_top_logprobs is None:\n logprobs_content.append(\n ChatCompletionLogProbsContent(\n token=self.tokenizer.decode(token_id),\n bytes=list(\n self.tokenizer.decode(token_id).encode(\n \"utf-8\", errors=\"replace\"))))\n else:\n logprobs_content.append(\n ChatCompletionLogProbsContent(\n token=step_top_logprobs[token_id].decoded_token,\n logprob=max(step_top_logprobs[token_id].logprob,\n -9999.0),\n bytes=list(\n step_top_logprobs[token_id].decoded_token.encode(\n \"utf-8\", errors=\"replace\")),\n top_logprobs=self._get_top_logprobs(\n step_top_logprobs, num_output_top_logprobs)))\n\n return ChatCompletionLogProbs(content=logprobs_content)\n", "path": "vllm/entrypoints/openai/serving_chat.py" }, { "content": "# Adapted from\n# https://github.com/lm-sys/FastChat/blob/168ccc29d3f7edc50823016105c024fe2282732a/fastchat/protocol/openai_api_protocol.py\nimport time\nfrom typing import Any, Dict, List, Literal, Optional, Union\n\nimport openai.types.chat\nimport torch\nfrom pydantic import BaseModel, ConfigDict, Field, model_validator\n# pydantic needs the TypedDict from typing_extensions\nfrom typing_extensions import Annotated, Required, TypedDict\n\nfrom vllm.pooling_params import PoolingParams\nfrom vllm.sampling_params import SamplingParams\nfrom vllm.utils import random_uuid\n\n\nclass CustomChatCompletionContentPartParam(TypedDict, total=False):\n __pydantic_config__ = ConfigDict(extra=\"allow\") # type: ignore\n\n type: Required[str]\n \"\"\"The type of the content part.\"\"\"\n\n\nChatCompletionContentPartParam = Union[\n openai.types.chat.ChatCompletionContentPartParam,\n CustomChatCompletionContentPartParam]\n\n\nclass CustomChatCompletionMessageParam(TypedDict, total=False):\n \"\"\"Enables custom roles in the Chat Completion API.\"\"\"\n role: Required[str]\n \"\"\"The role of the message's author.\"\"\"\n\n content: Union[str, List[ChatCompletionContentPartParam]]\n \"\"\"The contents of the message.\"\"\"\n\n name: str\n \"\"\"An optional name for the participant.\n\n Provides the model information to differentiate between participants of the\n same role.\n \"\"\"\n\n\nChatCompletionMessageParam = Union[\n openai.types.chat.ChatCompletionMessageParam,\n CustomChatCompletionMessageParam]\n\n\nclass OpenAIBaseModel(BaseModel):\n # OpenAI API does not allow extra fields\n model_config = ConfigDict(extra=\"forbid\")\n\n\nclass ErrorResponse(OpenAIBaseModel):\n object: str = \"error\"\n message: str\n type: str\n param: Optional[str] = None\n code: int\n\n\nclass ModelPermission(OpenAIBaseModel):\n id: str = Field(default_factory=lambda: f\"modelperm-{random_uuid()}\")\n object: str = \"model_permission\"\n created: int = Field(default_factory=lambda: int(time.time()))\n allow_create_engine: bool = False\n allow_sampling: bool = True\n allow_logprobs: bool = True\n allow_search_indices: bool = False\n allow_view: bool = True\n allow_fine_tuning: bool = False\n organization: str = \"*\"\n group: Optional[str] = None\n is_blocking: bool = False\n\n\nclass ModelCard(OpenAIBaseModel):\n id: str\n object: str = \"model\"\n created: int = Field(default_factory=lambda: int(time.time()))\n owned_by: str = \"vllm\"\n root: Optional[str] = None\n parent: Optional[str] = None\n max_model_len: Optional[int] = None\n permission: List[ModelPermission] = Field(default_factory=list)\n\n\nclass ModelList(OpenAIBaseModel):\n object: str = \"list\"\n data: List[ModelCard] = Field(default_factory=list)\n\n\nclass UsageInfo(OpenAIBaseModel):\n prompt_tokens: int = 0\n total_tokens: int = 0\n completion_tokens: Optional[int] = 0\n\n\nclass ResponseFormat(OpenAIBaseModel):\n # type must be \"json_object\" or \"text\"\n type: Literal[\"text\", \"json_object\"]\n\n\nclass StreamOptions(OpenAIBaseModel):\n include_usage: Optional[bool]\n\n\nclass FunctionDefinition(OpenAIBaseModel):\n name: str\n description: Optional[str] = None\n parameters: Optional[Dict[str, Any]] = None\n\n\nclass ChatCompletionToolsParam(OpenAIBaseModel):\n type: Literal[\"function\"] = \"function\"\n function: FunctionDefinition\n\n\nclass ChatCompletionNamedFunction(OpenAIBaseModel):\n name: str\n\n\nclass ChatCompletionNamedToolChoiceParam(OpenAIBaseModel):\n function: ChatCompletionNamedFunction\n type: Literal[\"function\"] = \"function\"\n\n\nclass ChatCompletionRequest(OpenAIBaseModel):\n # Ordered by official OpenAI API documentation\n # https://platform.openai.com/docs/api-reference/chat/create\n messages: List[ChatCompletionMessageParam]\n model: str\n frequency_penalty: Optional[float] = 0.0\n logit_bias: Optional[Dict[str, float]] = None\n logprobs: Optional[bool] = False\n top_logprobs: Optional[int] = 0\n max_tokens: Optional[int] = None\n n: Optional[int] = 1\n presence_penalty: Optional[float] = 0.0\n response_format: Optional[ResponseFormat] = None\n seed: Optional[int] = Field(None,\n ge=torch.iinfo(torch.long).min,\n le=torch.iinfo(torch.long).max)\n stop: Optional[Union[str, List[str]]] = Field(default_factory=list)\n stream: Optional[bool] = False\n stream_options: Optional[StreamOptions] = None\n temperature: Optional[float] = 0.7\n top_p: Optional[float] = 1.0\n tools: Optional[List[ChatCompletionToolsParam]] = None\n tool_choice: Optional[Union[Literal[\"none\"],\n ChatCompletionNamedToolChoiceParam]] = \"none\"\n user: Optional[str] = None\n\n # doc: begin-chat-completion-sampling-params\n best_of: Optional[int] = None\n use_beam_search: Optional[bool] = False\n top_k: Optional[int] = -1\n min_p: Optional[float] = 0.0\n repetition_penalty: Optional[float] = 1.0\n length_penalty: Optional[float] = 1.0\n early_stopping: Optional[bool] = False\n ignore_eos: Optional[bool] = False\n min_tokens: Optional[int] = 0\n stop_token_ids: Optional[List[int]] = Field(default_factory=list)\n skip_special_tokens: Optional[bool] = True\n spaces_between_special_tokens: Optional[bool] = True\n # doc: end-chat-completion-sampling-params\n\n # doc: begin-chat-completion-extra-params\n echo: Optional[bool] = Field(\n default=False,\n description=(\n \"If true, the new message will be prepended with the last message \"\n \"if they belong to the same role.\"),\n )\n add_generation_prompt: Optional[bool] = Field(\n default=True,\n description=\n (\"If true, the generation prompt will be added to the chat template. \"\n \"This is a parameter used by chat template in tokenizer config of the \"\n \"model.\"),\n )\n add_special_tokens: Optional[bool] = Field(\n default=False,\n description=(\n \"If true, special tokens (e.g. BOS) will be added to the prompt \"\n \"on top of what is added by the chat template. \"\n \"For most models, the chat template takes care of adding the \"\n \"special tokens so this should be set to False (as is the \"\n \"default).\"),\n )\n include_stop_str_in_output: Optional[bool] = Field(\n default=False,\n description=(\n \"Whether to include the stop string in the output. \"\n \"This is only applied when the stop or stop_token_ids is set.\"),\n )\n guided_json: Optional[Union[str, dict, BaseModel]] = Field(\n default=None,\n description=(\"If specified, the output will follow the JSON schema.\"),\n )\n guided_regex: Optional[str] = Field(\n default=None,\n description=(\n \"If specified, the output will follow the regex pattern.\"),\n )\n guided_choice: Optional[List[str]] = Field(\n default=None,\n description=(\n \"If specified, the output will be exactly one of the choices.\"),\n )\n guided_grammar: Optional[str] = Field(\n default=None,\n description=(\n \"If specified, the output will follow the context free grammar.\"),\n )\n guided_decoding_backend: Optional[str] = Field(\n default=None,\n description=(\n \"If specified, will override the default guided decoding backend \"\n \"of the server for this specific request. If set, must be either \"\n \"'outlines' / 'lm-format-enforcer'\"))\n guided_whitespace_pattern: Optional[str] = Field(\n default=None,\n description=(\n \"If specified, will override the default whitespace pattern \"\n \"for guided json decoding.\"))\n\n # doc: end-chat-completion-extra-params\n\n def to_sampling_params(self) -> SamplingParams:\n # We now allow logprobs being true without top_logrobs.\n\n logits_processors = None\n if self.logit_bias:\n\n def logit_bias_logits_processor(\n token_ids: List[int],\n logits: torch.Tensor) -> torch.Tensor:\n assert self.logit_bias is not None\n for token_id, bias in self.logit_bias.items():\n # Clamp the bias between -100 and 100 per OpenAI API spec\n bias = min(100, max(-100, bias))\n logits[int(token_id)] += bias\n return logits\n\n logits_processors = [logit_bias_logits_processor]\n\n return SamplingParams(\n n=self.n,\n presence_penalty=self.presence_penalty,\n frequency_penalty=self.frequency_penalty,\n repetition_penalty=self.repetition_penalty,\n temperature=self.temperature,\n top_p=self.top_p,\n min_p=self.min_p,\n seed=self.seed,\n stop=self.stop,\n stop_token_ids=self.stop_token_ids,\n max_tokens=self.max_tokens,\n min_tokens=self.min_tokens,\n logprobs=self.top_logprobs if self.logprobs else None,\n prompt_logprobs=self.top_logprobs if self.echo else None,\n best_of=self.best_of,\n top_k=self.top_k,\n ignore_eos=self.ignore_eos,\n use_beam_search=self.use_beam_search,\n early_stopping=self.early_stopping,\n skip_special_tokens=self.skip_special_tokens,\n spaces_between_special_tokens=self.spaces_between_special_tokens,\n include_stop_str_in_output=self.include_stop_str_in_output,\n length_penalty=self.length_penalty,\n logits_processors=logits_processors,\n )\n\n @model_validator(mode='before')\n @classmethod\n def validate_stream_options(cls, values):\n if (values.get('stream_options') is not None\n and not values.get('stream')):\n raise ValueError(\n \"stream_options can only be set if stream is true\")\n return values\n\n @model_validator(mode=\"before\")\n @classmethod\n def check_guided_decoding_count(cls, data):\n guide_count = sum([\n \"guided_json\" in data and data[\"guided_json\"] is not None,\n \"guided_regex\" in data and data[\"guided_regex\"] is not None,\n \"guided_choice\" in data and data[\"guided_choice\"] is not None\n ])\n # you can only use one kind of guided decoding\n if guide_count > 1:\n raise ValueError(\n \"You can only use one kind of guided decoding \"\n \"('guided_json', 'guided_regex' or 'guided_choice').\")\n # you can only either use guided decoding or tools, not both\n if guide_count > 1 and \"tool_choice\" in data and data[\n \"tool_choice\"] != \"none\":\n raise ValueError(\n \"You can only either use guided decoding or tools, not both.\")\n return data\n\n @model_validator(mode=\"before\")\n @classmethod\n def check_tool_choice(cls, data):\n if \"tool_choice\" in data and data[\"tool_choice\"] != \"none\":\n if not isinstance(data[\"tool_choice\"], dict):\n raise ValueError(\"Currently only named tools are supported.\")\n if \"tools\" not in data or data[\"tools\"] is None:\n raise ValueError(\n \"When using `tool_choice`, `tools` must be set.\")\n return data\n\n @model_validator(mode=\"before\")\n @classmethod\n def check_logprobs(cls, data):\n if \"top_logprobs\" in data and data[\"top_logprobs\"] is not None:\n if \"logprobs\" not in data or data[\"logprobs\"] is False:\n raise ValueError(\n \"when using `top_logprobs`, `logprobs` must be set to true.\"\n )\n elif not 0 <= data[\"top_logprobs\"] <= 20:\n raise ValueError(\n \"`top_logprobs` must be a value in the interval [0, 20].\")\n return data\n\n\nclass CompletionRequest(OpenAIBaseModel):\n # Ordered by official OpenAI API documentation\n # https://platform.openai.com/docs/api-reference/completions/create\n model: str\n prompt: Union[List[int], List[List[int]], str, List[str]]\n best_of: Optional[int] = None\n echo: Optional[bool] = False\n frequency_penalty: Optional[float] = 0.0\n logit_bias: Optional[Dict[str, float]] = None\n logprobs: Optional[int] = None\n max_tokens: Optional[int] = 16\n n: int = 1\n presence_penalty: Optional[float] = 0.0\n seed: Optional[int] = Field(None,\n ge=torch.iinfo(torch.long).min,\n le=torch.iinfo(torch.long).max)\n stop: Optional[Union[str, List[str]]] = Field(default_factory=list)\n stream: Optional[bool] = False\n stream_options: Optional[StreamOptions] = None\n suffix: Optional[str] = None\n temperature: Optional[float] = 1.0\n top_p: Optional[float] = 1.0\n user: Optional[str] = None\n\n # doc: begin-completion-sampling-params\n use_beam_search: Optional[bool] = False\n top_k: Optional[int] = -1\n min_p: Optional[float] = 0.0\n repetition_penalty: Optional[float] = 1.0\n length_penalty: Optional[float] = 1.0\n early_stopping: Optional[bool] = False\n stop_token_ids: Optional[List[int]] = Field(default_factory=list)\n ignore_eos: Optional[bool] = False\n min_tokens: Optional[int] = 0\n skip_special_tokens: Optional[bool] = True\n spaces_between_special_tokens: Optional[bool] = True\n truncate_prompt_tokens: Optional[Annotated[int, Field(ge=1)]] = None\n # doc: end-completion-sampling-params\n\n # doc: begin-completion-extra-params\n include_stop_str_in_output: Optional[bool] = Field(\n default=False,\n description=(\n \"Whether to include the stop string in the output. \"\n \"This is only applied when the stop or stop_token_ids is set.\"),\n )\n response_format: Optional[ResponseFormat] = Field(\n default=None,\n description=\n (\"Similar to chat completion, this parameter specifies the format of \"\n \"output. Only {'type': 'json_object'} or {'type': 'text' } is \"\n \"supported.\"),\n )\n guided_json: Optional[Union[str, dict, BaseModel]] = Field(\n default=None,\n description=(\"If specified, the output will follow the JSON schema.\"),\n )\n guided_regex: Optional[str] = Field(\n default=None,\n description=(\n \"If specified, the output will follow the regex pattern.\"),\n )\n guided_choice: Optional[List[str]] = Field(\n default=None,\n description=(\n \"If specified, the output will be exactly one of the choices.\"),\n )\n guided_grammar: Optional[str] = Field(\n default=None,\n description=(\n \"If specified, the output will follow the context free grammar.\"),\n )\n guided_decoding_backend: Optional[str] = Field(\n default=None,\n description=(\n \"If specified, will override the default guided decoding backend \"\n \"of the server for this specific request. If set, must be one of \"\n \"'outlines' / 'lm-format-enforcer'\"))\n guided_whitespace_pattern: Optional[str] = Field(\n default=None,\n description=(\n \"If specified, will override the default whitespace pattern \"\n \"for guided json decoding.\"))\n\n # doc: end-completion-extra-params\n\n def to_sampling_params(self):\n echo_without_generation = self.echo and self.max_tokens == 0\n\n logits_processors = None\n if self.logit_bias:\n\n def logit_bias_logits_processor(\n token_ids: List[int],\n logits: torch.Tensor) -> torch.Tensor:\n assert self.logit_bias is not None\n for token_id, bias in self.logit_bias.items():\n # Clamp the bias between -100 and 100 per OpenAI API spec\n bias = min(100, max(-100, bias))\n logits[int(token_id)] += bias\n return logits\n\n logits_processors = [logit_bias_logits_processor]\n\n return SamplingParams(\n n=self.n,\n best_of=self.best_of,\n presence_penalty=self.presence_penalty,\n frequency_penalty=self.frequency_penalty,\n repetition_penalty=self.repetition_penalty,\n temperature=self.temperature,\n top_p=self.top_p,\n top_k=self.top_k,\n min_p=self.min_p,\n seed=self.seed,\n stop=self.stop,\n stop_token_ids=self.stop_token_ids,\n ignore_eos=self.ignore_eos,\n max_tokens=self.max_tokens if not echo_without_generation else 1,\n min_tokens=self.min_tokens,\n logprobs=self.logprobs,\n use_beam_search=self.use_beam_search,\n early_stopping=self.early_stopping,\n prompt_logprobs=self.logprobs if self.echo else None,\n skip_special_tokens=self.skip_special_tokens,\n spaces_between_special_tokens=(self.spaces_between_special_tokens),\n include_stop_str_in_output=self.include_stop_str_in_output,\n length_penalty=self.length_penalty,\n logits_processors=logits_processors,\n truncate_prompt_tokens=self.truncate_prompt_tokens,\n )\n\n @model_validator(mode=\"before\")\n @classmethod\n def check_guided_decoding_count(cls, data):\n guide_count = sum([\n \"guided_json\" in data and data[\"guided_json\"] is not None,\n \"guided_regex\" in data and data[\"guided_regex\"] is not None,\n \"guided_choice\" in data and data[\"guided_choice\"] is not None\n ])\n if guide_count > 1:\n raise ValueError(\n \"You can only use one kind of guided decoding \"\n \"('guided_json', 'guided_regex' or 'guided_choice').\")\n return data\n\n @model_validator(mode=\"before\")\n @classmethod\n def check_logprobs(cls, data):\n if \"logprobs\" in data and data[\n \"logprobs\"] is not None and not 0 <= data[\"logprobs\"] <= 5:\n raise ValueError((\"if passed, `logprobs` must be a value\",\n \" in the interval [0, 5].\"))\n return data\n\n @model_validator(mode=\"before\")\n @classmethod\n def validate_stream_options(cls, data):\n if data.get(\"stream_options\") and not data.get(\"stream\"):\n raise ValueError(\n \"Stream options can only be defined when stream is True.\")\n return data\n\n\nclass EmbeddingRequest(BaseModel):\n # Ordered by official OpenAI API documentation\n # https://platform.openai.com/docs/api-reference/embeddings\n model: str\n input: Union[List[int], List[List[int]], str, List[str]]\n encoding_format: Optional[str] = Field('float', pattern='^(float|base64)$')\n dimensions: Optional[int] = None\n user: Optional[str] = None\n\n # doc: begin-embedding-pooling-params\n additional_data: Optional[Any] = None\n\n # doc: end-embedding-pooling-params\n\n def to_pooling_params(self):\n return PoolingParams(additional_data=self.additional_data)\n\n\nclass CompletionLogProbs(OpenAIBaseModel):\n text_offset: List[int] = Field(default_factory=list)\n token_logprobs: List[Optional[float]] = Field(default_factory=list)\n tokens: List[str] = Field(default_factory=list)\n top_logprobs: Optional[List[Optional[Dict[str, float]]]] = None\n\n\nclass CompletionResponseChoice(OpenAIBaseModel):\n index: int\n text: str\n logprobs: Optional[CompletionLogProbs] = None\n finish_reason: Optional[str] = None\n stop_reason: Optional[Union[int, str]] = Field(\n default=None,\n description=(\n \"The stop string or token id that caused the completion \"\n \"to stop, None if the completion finished for some other reason \"\n \"including encountering the EOS token\"),\n )\n\n\nclass CompletionResponse(OpenAIBaseModel):\n id: str = Field(default_factory=lambda: f\"cmpl-{random_uuid()}\")\n object: str = \"text_completion\"\n created: int = Field(default_factory=lambda: int(time.time()))\n model: str\n choices: List[CompletionResponseChoice]\n usage: UsageInfo\n\n\nclass CompletionResponseStreamChoice(OpenAIBaseModel):\n index: int\n text: str\n logprobs: Optional[CompletionLogProbs] = None\n finish_reason: Optional[str] = None\n stop_reason: Optional[Union[int, str]] = Field(\n default=None,\n description=(\n \"The stop string or token id that caused the completion \"\n \"to stop, None if the completion finished for some other reason \"\n \"including encountering the EOS token\"),\n )\n\n\nclass CompletionStreamResponse(OpenAIBaseModel):\n id: str = Field(default_factory=lambda: f\"cmpl-{random_uuid()}\")\n object: str = \"text_completion\"\n created: int = Field(default_factory=lambda: int(time.time()))\n model: str\n choices: List[CompletionResponseStreamChoice]\n usage: Optional[UsageInfo] = Field(default=None)\n\n\nclass EmbeddingResponseData(BaseModel):\n index: int\n object: str = \"embedding\"\n embedding: List[float]\n\n\nclass EmbeddingResponse(BaseModel):\n id: str = Field(default_factory=lambda: f\"cmpl-{random_uuid()}\")\n object: str = \"list\"\n created: int = Field(default_factory=lambda: int(time.time()))\n model: str\n data: List[EmbeddingResponseData]\n usage: UsageInfo\n\n\nclass FunctionCall(OpenAIBaseModel):\n name: str\n arguments: str\n\n\nclass ToolCall(OpenAIBaseModel):\n id: str = Field(default_factory=lambda: f\"chatcmpl-tool-{random_uuid()}\")\n type: Literal[\"function\"] = \"function\"\n function: FunctionCall\n\n\nclass ChatMessage(OpenAIBaseModel):\n role: str\n content: str\n tool_calls: List[ToolCall] = Field(default_factory=list)\n\n\nclass ChatCompletionLogProb(OpenAIBaseModel):\n token: str\n logprob: float = -9999.0\n bytes: Optional[List[int]] = None\n\n\nclass ChatCompletionLogProbsContent(ChatCompletionLogProb):\n top_logprobs: List[ChatCompletionLogProb] = Field(default_factory=list)\n\n\nclass ChatCompletionLogProbs(OpenAIBaseModel):\n content: Optional[List[ChatCompletionLogProbsContent]] = None\n\n\nclass ChatCompletionResponseChoice(OpenAIBaseModel):\n index: int\n message: ChatMessage\n logprobs: Optional[ChatCompletionLogProbs] = None\n finish_reason: Optional[Literal[\"stop\", \"length\", \"tool_calls\"]] = None\n stop_reason: Optional[Union[int, str]] = None\n\n\nclass ChatCompletionResponse(OpenAIBaseModel):\n id: str = Field(default_factory=lambda: f\"chatcmpl-{random_uuid()}\")\n object: Literal[\"chat.completion\"] = \"chat.completion\"\n created: int = Field(default_factory=lambda: int(time.time()))\n model: str\n choices: List[ChatCompletionResponseChoice]\n usage: UsageInfo\n\n\nclass DeltaMessage(OpenAIBaseModel):\n role: Optional[str] = None\n content: Optional[str] = None\n tool_calls: List[ToolCall] = Field(default_factory=list)\n\n\nclass ChatCompletionResponseStreamChoice(OpenAIBaseModel):\n index: int\n delta: DeltaMessage\n logprobs: Optional[ChatCompletionLogProbs] = None\n finish_reason: Optional[Literal[\"stop\", \"length\", \"tool_calls\"]] = None\n stop_reason: Optional[Union[int, str]] = None\n\n\nclass ChatCompletionStreamResponse(OpenAIBaseModel):\n id: str = Field(default_factory=lambda: f\"chatcmpl-{random_uuid()}\")\n object: Literal[\"chat.completion.chunk\"] = \"chat.completion.chunk\"\n created: int = Field(default_factory=lambda: int(time.time()))\n model: str\n choices: List[ChatCompletionResponseStreamChoice]\n usage: Optional[UsageInfo] = Field(default=None)\n\n\nclass BatchRequestInput(OpenAIBaseModel):\n \"\"\"\n The per-line object of the batch input file.\n\n NOTE: Currently only the `/v1/chat/completions` endpoint is supported.\n \"\"\"\n\n # A developer-provided per-request id that will be used to match outputs to\n # inputs. Must be unique for each request in a batch.\n custom_id: str\n\n # The HTTP method to be used for the request. Currently only POST is\n # supported.\n method: str\n\n # The OpenAI API relative URL to be used for the request. Currently\n # /v1/chat/completions is supported.\n url: str\n\n # The parameteters of the request.\n body: Union[ChatCompletionRequest, ]\n\n\nclass BatchRequestOutput(OpenAIBaseModel):\n \"\"\"\n The per-line object of the batch output and error files\n \"\"\"\n\n id: str\n\n # A developer-provided per-request id that will be used to match outputs to\n # inputs.\n custom_id: str\n\n response: Optional[ChatCompletionResponse]\n\n # For requests that failed with a non-HTTP error, this will contain more\n # information on the cause of the failure.\n error: Optional[Any]\n", "path": "vllm/entrypoints/openai/protocol.py" } ]
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 [email protected] [email protected]( + "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}) + + [email protected] [email protected]( + "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 [email protected]( - "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 jax.numpy as jnp\nfrom jax.scipy.linalg import solve_triangular\nfrom jax.util import partial\n\n# Parameters for Transformed Rejection with Squeeze (TRS) algorithm - page 3.\n_tr_params = namedtuple('tr_params', ['c', 'b', 'a', 'alpha', 'u_r', 'v_r', 'm', 'log_p', 'log1_p', 'log_h'])\n\n\ndef _get_tr_params(n, p):\n # See Table 1. Additionally, we pre-compute log(p), log1(-p) and the\n # constant terms, that depend only on (n, p, m) in log(f(k)) (bottom of page 5).\n mu = n * p\n spq = jnp.sqrt(mu * (1 - p))\n c = mu + 0.5\n b = 1.15 + 2.53 * spq\n a = -0.0873 + 0.0248 * b + 0.01 * p\n alpha = (2.83 + 5.1 / b) * spq\n u_r = 0.43\n v_r = 0.92 - 4.2 / b\n m = jnp.floor((n + 1) * p).astype(n.dtype)\n log_p = jnp.log(p)\n log1_p = jnp.log1p(-p)\n log_h = (m + 0.5) * (jnp.log((m + 1.) / (n - m + 1.)) + log1_p - log_p) + \\\n (stirling_approx_tail(m) + stirling_approx_tail(n - m))\n return _tr_params(c, b, a, alpha, u_r, v_r, m, log_p, log1_p, log_h)\n\n\ndef stirling_approx_tail(k):\n precomputed = jnp.array([\n 0.08106146679532726,\n 0.04134069595540929,\n 0.02767792568499834,\n 0.02079067210376509,\n 0.01664469118982119,\n 0.01387612882307075,\n 0.01189670994589177,\n 0.01041126526197209,\n 0.009255462182712733,\n 0.008330563433362871,\n ])\n kp1 = k + 1\n kp1sq = (k + 1) ** 2\n return jnp.where(k < 10,\n precomputed[k],\n (1. / 12 - (1. / 360 - (1. / 1260) / kp1sq) / kp1sq) / kp1)\n\n\ndef _binomial_btrs(key, p, n):\n \"\"\"\n Based on the transformed rejection sampling algorithm (BTRS) from the\n following reference:\n\n Hormann, \"The Generation of Binonmial Random Variates\"\n (https://core.ac.uk/download/pdf/11007254.pdf)\n \"\"\"\n\n def _btrs_body_fn(val):\n _, key, _, _ = val\n key, key_u, key_v = random.split(key, 3)\n u = random.uniform(key_u)\n v = random.uniform(key_v)\n u = u - 0.5\n k = jnp.floor((2 * tr_params.a / (0.5 - jnp.abs(u)) + tr_params.b) * u + tr_params.c).astype(n.dtype)\n return k, key, u, v\n\n def _btrs_cond_fn(val):\n def accept_fn(k, u, v):\n # See acceptance condition in Step 3. (Page 3) of TRS algorithm\n # v <= f(k) * g_grad(u) / alpha\n\n m = tr_params.m\n log_p = tr_params.log_p\n log1_p = tr_params.log1_p\n # See: formula for log(f(k)) at bottom of Page 5.\n log_f = (n + 1.) * jnp.log((n - m + 1.) / (n - k + 1.)) + \\\n (k + 0.5) * (jnp.log((n - k + 1.) / (k + 1.)) + log_p - log1_p) + \\\n (stirling_approx_tail(k) - stirling_approx_tail(n - k)) + tr_params.log_h\n g = (tr_params.a / (0.5 - jnp.abs(u)) ** 2) + tr_params.b\n return jnp.log((v * tr_params.alpha) / g) <= log_f\n\n k, key, u, v = val\n early_accept = (jnp.abs(u) <= tr_params.u_r) & (v <= tr_params.v_r)\n early_reject = (k < 0) | (k > n)\n return lax.cond(early_accept | early_reject,\n (),\n lambda _: ~early_accept,\n (k, u, v),\n lambda x: ~accept_fn(*x))\n\n tr_params = _get_tr_params(n, p)\n ret = lax.while_loop(_btrs_cond_fn, _btrs_body_fn,\n (-1, key, 1., 1.)) # use k=-1 initially so that cond_fn returns True\n return ret[0]\n\n\ndef _binomial_inversion(key, p, n):\n def _binom_inv_body_fn(val):\n i, key, geom_acc = val\n key, key_u = random.split(key)\n u = random.uniform(key_u)\n geom = jnp.floor(jnp.log1p(-u) / log1_p) + 1\n geom_acc = geom_acc + geom\n return i + 1, key, geom_acc\n\n def _binom_inv_cond_fn(val):\n i, _, geom_acc = val\n return geom_acc <= n\n\n log1_p = jnp.log1p(-p)\n ret = lax.while_loop(_binom_inv_cond_fn, _binom_inv_body_fn,\n (-1, key, 0.))\n return ret[0]\n\n\ndef _binomial_dispatch(key, p, n):\n def dispatch(key, p, n):\n is_le_mid = p <= 0.5\n pq = jnp.where(is_le_mid, p, 1 - p)\n mu = n * pq\n k = lax.cond(mu < 10,\n (key, pq, n),\n lambda x: _binomial_inversion(*x),\n (key, pq, n),\n lambda x: _binomial_btrs(*x))\n return jnp.where(is_le_mid, k, n - k)\n\n # Return 0 for nan `p` or negative `n`, since nan values are not allowed for integer types\n cond0 = jnp.isfinite(p) & (n > 0) & (p > 0)\n return lax.cond(cond0 & (p < 1),\n (key, p, n),\n lambda x: dispatch(*x),\n (),\n lambda _: jnp.where(cond0, n, 0))\n\n\n@partial(jit, static_argnums=(3,))\ndef _binomial(key, p, n, shape):\n shape = shape or lax.broadcast_shapes(jnp.shape(p), jnp.shape(n))\n # reshape to map over axis 0\n p = jnp.reshape(jnp.broadcast_to(p, shape), -1)\n n = jnp.reshape(jnp.broadcast_to(n, shape), -1)\n key = random.split(key, jnp.size(p))\n if xla_bridge.get_backend().platform == 'cpu':\n ret = lax.map(lambda x: _binomial_dispatch(*x),\n (key, p, n))\n else:\n ret = vmap(lambda *x: _binomial_dispatch(*x))(key, p, n)\n return jnp.reshape(ret, shape)\n\n\ndef binomial(key, p, n=1, shape=()):\n return _binomial(key, p, n, shape)\n\n\n@partial(jit, static_argnums=(2,))\ndef _categorical(key, p, shape):\n # this implementation is fast when event shape is small, and slow otherwise\n # Ref: https://stackoverflow.com/a/34190035\n shape = shape or p.shape[:-1]\n s = jnp.cumsum(p, axis=-1)\n r = random.uniform(key, shape=shape + (1,))\n # FIXME: replace this computation by using binary search as suggested in the above\n # reference. A while_loop + vmap for a reshaped 2D array would be enough.\n return jnp.sum(s < r, axis=-1)\n\n\ndef categorical(key, p, shape=()):\n return _categorical(key, p, shape)\n\n\ndef _scatter_add_one(operand, indices, updates):\n return lax.scatter_add(operand, indices, updates,\n lax.ScatterDimensionNumbers(update_window_dims=(),\n inserted_window_dims=(0,),\n scatter_dims_to_operand_dims=(0,)))\n\n\n@partial(jit, static_argnums=(3, 4))\ndef _multinomial(key, p, n, n_max, shape=()):\n if jnp.shape(n) != jnp.shape(p)[:-1]:\n broadcast_shape = lax.broadcast_shapes(jnp.shape(n), jnp.shape(p)[:-1])\n n = jnp.broadcast_to(n, broadcast_shape)\n p = jnp.broadcast_to(p, broadcast_shape + jnp.shape(p)[-1:])\n shape = shape or p.shape[:-1]\n # get indices from categorical distribution then gather the result\n indices = categorical(key, p, (n_max,) + shape)\n # mask out values when counts is heterogeneous\n if jnp.ndim(n) > 0:\n mask = promote_shapes(jnp.arange(n_max) < jnp.expand_dims(n, -1), shape=shape + (n_max,))[0]\n mask = jnp.moveaxis(mask, -1, 0).astype(indices.dtype)\n excess = jnp.concatenate([jnp.expand_dims(n_max - n, -1), jnp.zeros(jnp.shape(n) + (p.shape[-1] - 1,))], -1)\n else:\n mask = 1\n excess = 0\n # NB: we transpose to move batch shape to the front\n indices_2D = (jnp.reshape(indices * mask, (n_max, -1,))).T\n samples_2D = vmap(_scatter_add_one, (0, 0, 0))(jnp.zeros((indices_2D.shape[0], p.shape[-1]),\n dtype=indices.dtype),\n jnp.expand_dims(indices_2D, axis=-1),\n jnp.ones(indices_2D.shape, dtype=indices.dtype))\n return jnp.reshape(samples_2D, shape + p.shape[-1:]) - excess\n\n\ndef multinomial(key, p, n, shape=()):\n n_max = int(jnp.max(n))\n return _multinomial(key, p, n, n_max, shape)\n\n\ndef cholesky_of_inverse(matrix):\n # This formulation only takes the inverse of a triangular matrix\n # which is more numerically stable.\n # Refer to:\n # https://nbviewer.jupyter.org/gist/fehiepsi/5ef8e09e61604f10607380467eb82006#Precision-to-scale_tril\n tril_inv = jnp.swapaxes(jnp.linalg.cholesky(matrix[..., ::-1, ::-1])[..., ::-1, ::-1], -2, -1)\n identity = jnp.broadcast_to(jnp.identity(matrix.shape[-1]), tril_inv.shape)\n return solve_triangular(tril_inv, identity, lower=True)\n\n\n# TODO: move upstream to jax.nn\ndef binary_cross_entropy_with_logits(x, y):\n # compute -y * log(sigmoid(x)) - (1 - y) * log(1 - sigmoid(x))\n # Ref: https://www.tensorflow.org/api_docs/python/tf/nn/sigmoid_cross_entropy_with_logits\n return jnp.clip(x, 0) + jnp.log1p(jnp.exp(-jnp.abs(x))) - x * y\n\n\ndef promote_shapes(*args, shape=()):\n # adapted from lax.lax_numpy\n if len(args) < 2 and not shape:\n return args\n else:\n shapes = [jnp.shape(arg) for arg in args]\n num_dims = len(lax.broadcast_shapes(shape, *shapes))\n return [lax.reshape(arg, (1,) * (num_dims - len(s)) + s)\n if len(s) < num_dims else arg for arg, s in zip(args, shapes)]\n\n\ndef get_dtype(x):\n return canonicalize_dtype(lax.dtype(x))\n\n\ndef sum_rightmost(x, dim):\n \"\"\"\n Sum out ``dim`` many rightmost dimensions of a given tensor.\n \"\"\"\n out_dim = jnp.ndim(x) - dim\n x = jnp.reshape(x[..., jnp.newaxis], jnp.shape(x)[:out_dim] + (-1,))\n return jnp.sum(x, axis=-1)\n\n\ndef matrix_to_tril_vec(x, diagonal=0):\n idxs = jnp.tril_indices(x.shape[-1], diagonal)\n return x[..., idxs[0], idxs[1]]\n\n\ndef vec_to_tril_matrix(t, diagonal=0):\n # NB: the following formula only works for diagonal <= 0\n n = round((math.sqrt(1 + 8 * t.shape[-1]) - 1) / 2) - diagonal\n n2 = n * n\n idx = jnp.reshape(jnp.arange(n2), (n, n))[jnp.tril_indices(n, diagonal)]\n x = lax.scatter_add(jnp.zeros(t.shape[:-1] + (n2,)), jnp.expand_dims(idx, axis=-1), t,\n lax.ScatterDimensionNumbers(update_window_dims=range(t.ndim - 1),\n inserted_window_dims=(t.ndim - 1,),\n scatter_dims_to_operand_dims=(t.ndim - 1,)))\n return jnp.reshape(x, x.shape[:-1] + (n, n))\n\n\ndef cholesky_update(L, x, coef=1):\n \"\"\"\n Finds cholesky of L @ L.T + coef * x @ x.T.\n\n **References;**\n\n 1. A more efficient rank-one covariance matrix update for evolution strategies,\n Oswin Krause and Christian Igel\n \"\"\"\n batch_shape = lax.broadcast_shapes(L.shape[:-2], x.shape[:-1])\n L = jnp.broadcast_to(L, batch_shape + L.shape[-2:])\n x = jnp.broadcast_to(x, batch_shape + x.shape[-1:])\n diag = jnp.diagonal(L, axis1=-2, axis2=-1)\n # convert to unit diagonal triangular matrix: L @ D @ T.t\n L = L / diag[..., None, :]\n D = jnp.square(diag)\n\n def scan_fn(carry, val):\n b, w = carry\n j, Dj, L_j = val\n wj = w[..., j]\n gamma = b * Dj + coef * jnp.square(wj)\n Dj_new = gamma / b\n b = gamma / Dj_new\n\n # update vectors w and L_j\n w = w - wj[..., None] * L_j\n L_j = L_j + (coef * wj / gamma)[..., None] * w\n return (b, w), (Dj_new, L_j)\n\n D, L = jnp.moveaxis(D, -1, 0), jnp.moveaxis(L, -1, 0) # move scan dim to front\n _, (D, L) = lax.scan(scan_fn, (jnp.ones(batch_shape), x), (jnp.arange(D.shape[0]), D, L))\n D, L = jnp.moveaxis(D, 0, -1), jnp.moveaxis(L, 0, -1) # move scan dim back\n return L * jnp.sqrt(D)[..., None, :]\n\n\ndef signed_stick_breaking_tril(t):\n # make sure that t in (-1, 1)\n eps = jnp.finfo(t.dtype).eps\n t = jnp.clip(t, a_min=(-1 + eps), a_max=(1 - eps))\n # transform t to tril matrix with identity diagonal\n r = vec_to_tril_matrix(t, diagonal=-1)\n\n # apply stick-breaking on the squared values;\n # we omit the step of computing s = z * z_cumprod by using the fact:\n # y = sign(r) * s = sign(r) * sqrt(z * z_cumprod) = r * sqrt(z_cumprod)\n z = r ** 2\n z1m_cumprod = jnp.cumprod(1 - z, axis=-1)\n z1m_cumprod_sqrt = jnp.sqrt(z1m_cumprod)\n\n pad_width = [(0, 0)] * z.ndim\n pad_width[-1] = (1, 0)\n z1m_cumprod_sqrt_shifted = jnp.pad(z1m_cumprod_sqrt[..., :-1], pad_width,\n mode=\"constant\", constant_values=1.)\n y = (r + jnp.identity(r.shape[-1])) * z1m_cumprod_sqrt_shifted\n return y\n\n\ndef logmatmulexp(x, y):\n \"\"\"\n Numerically stable version of ``(x.log() @ y.log()).exp()``.\n \"\"\"\n x_shift = lax.stop_gradient(jnp.amax(x, -1, keepdims=True))\n y_shift = lax.stop_gradient(jnp.amax(y, -2, keepdims=True))\n xy = jnp.log(jnp.matmul(jnp.exp(x - x_shift), jnp.exp(y - y_shift)))\n return xy + x_shift + y_shift\n\n\ndef clamp_probs(probs):\n finfo = jnp.finfo(get_dtype(probs))\n return jnp.clip(probs, a_min=finfo.tiny, a_max=1. - finfo.eps)\n\n\ndef is_identically_one(x):\n \"\"\"\n Check if argument is exactly the number one. True for the number one;\n false for other numbers; false for ndarrays.\n \"\"\"\n if isinstance(x, (int, float)):\n return x == 1\n else:\n return False\n\n\ndef von_mises_centered(key, concentration, shape=(), dtype=jnp.float64):\n \"\"\" Compute centered von Mises samples using rejection sampling from [1] with wrapped Cauchy proposal.\n\n *** References ***\n [1] Luc Devroye \"Non-Uniform Random Variate Generation\", Springer-Verlag, 1986;\n Chapter 9, p. 473-476. http://www.nrbook.com/devroye/Devroye_files/chapter_nine.pdf\n\n\n :param key: random number generator key\n :param concentration: concentration of distribution\n :param shape: shape of samples\n :param dtype: float precesions for choosing correct s cutfoff\n :return: centered samples from von Mises\n \"\"\"\n shape = shape or jnp.shape(concentration)\n dtype = canonicalize_dtype(dtype)\n concentration = lax.convert_element_type(concentration, dtype)\n concentration = jnp.broadcast_to(concentration, shape)\n return _von_mises_centered(key, concentration, shape, dtype)\n\n\n@partial(jit, static_argnums=(2, 3))\ndef _von_mises_centered(key, concentration, shape, dtype):\n # Cutoff from TensorFlow probability\n # (https://github.com/tensorflow/probability/blob/f051e03dd3cc847d31061803c2b31c564562a993/tensorflow_probability/python/distributions/von_mises.py#L567-L570)\n s_cutoff_map = {jnp.dtype(jnp.float16): 1.8e-1,\n jnp.dtype(jnp.float32): 2e-2,\n jnp.dtype(jnp.float64): 1.2e-4}\n s_cutoff = s_cutoff_map.get(dtype)\n\n r = 1. + jnp.sqrt(1. + 4. * concentration ** 2)\n rho = (r - jnp.sqrt(2. * r)) / (2. * concentration)\n s_exact = (1. + rho ** 2) / (2. * rho)\n\n s_approximate = 1. / concentration\n\n s = jnp.where(concentration > s_cutoff, s_exact, s_approximate)\n\n def cond_fn(*args):\n \"\"\" check if all are done or reached max number of iterations \"\"\"\n i, _, done, _, _ = args[0]\n return jnp.bitwise_and(i < 100, jnp.logical_not(jnp.all(done)))\n\n def body_fn(*args):\n i, key, done, _, w = args[0]\n uni_ukey, uni_vkey, key = random.split(key, 3)\n\n u = random.uniform(key=uni_ukey, shape=shape, dtype=concentration.dtype, minval=-1., maxval=1.)\n z = jnp.cos(jnp.pi * u)\n w = jnp.where(done, w, (1. + s * z) / (s + z)) # Update where not done\n\n y = concentration * (s - w)\n v = random.uniform(key=uni_vkey, shape=shape, dtype=concentration.dtype, minval=-1., maxval=1.)\n\n accept = (y * (2. - y) >= v) | (jnp.log(y / v) + 1. >= y)\n\n return i+1, key, accept | done, u, w\n\n init_done = jnp.zeros(shape, dtype=bool)\n init_u = jnp.zeros(shape)\n init_w = jnp.zeros(shape)\n\n _, _, done, u, w = lax.while_loop(\n cond_fun=cond_fn,\n body_fun=body_fn,\n init_val=(jnp.array(0), key, init_done, init_u, init_w)\n )\n\n return jnp.sign(u) * jnp.arccos(w)\n\n\n# The is sourced from: torch.distributions.util.py\n#\n# Copyright (c) 2016- Facebook, Inc (Adam Paszke)\n# Copyright (c) 2014- Facebook, Inc (Soumith Chintala)\n# Copyright (c) 2011-2014 Idiap Research Institute (Ronan Collobert)\n# Copyright (c) 2012-2014 Deepmind Technologies (Koray Kavukcuoglu)\n# Copyright (c) 2011-2012 NEC Laboratories America (Koray Kavukcuoglu)\n# Copyright (c) 2011-2013 NYU (Clement Farabet)\n# Copyright (c) 2006-2010 NEC Laboratories America (Ronan Collobert, Leon Bottou, Iain Melvin, Jason Weston)\n# Copyright (c) 2006 Idiap Research Institute (Samy Bengio)\n# Copyright (c) 2001-2004 Idiap Research Institute (Ronan Collobert, Samy Bengio, Johnny Mariethoz)\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\nclass lazy_property(object):\n r\"\"\"\n Used as a decorator for lazy loading of class attributes. This uses a\n non-data descriptor that calls the wrapped method to compute the property on\n first call; thereafter replacing the wrapped method into an instance\n attribute.\n \"\"\"\n\n def __init__(self, wrapped):\n self.wrapped = wrapped\n update_wrapper(self, wrapped)\n\n # This is to prevent warnings from sphinx\n def __call__(self, *args, **kwargs):\n return self.wrapped(*args, **kwargs)\n\n def __get__(self, instance, obj_type=None):\n if instance is None:\n return self\n value = self.wrapped(instance)\n setattr(instance, self.wrapped.__name__, value)\n return value\n\n\ndef validate_sample(log_prob_fn):\n def wrapper(self, *args, **kwargs):\n log_prob = log_prob_fn(self, *args, *kwargs)\n if self._validate_args:\n value = kwargs['value'] if 'value' in kwargs else args[0]\n mask = self._validate_sample(value)\n log_prob = jnp.where(mask, log_prob, -jnp.inf)\n return log_prob\n\n return wrapper\n", "path": "numpyro/distributions/util.py" }, { "content": "# Copyright Contributors to the Pyro project.\n# SPDX-License-Identifier: Apache-2.0\n\n# Adapted from pyro.infer.autoguide\nfrom abc import ABC, abstractmethod\nimport warnings\n\nfrom jax import hessian, lax, random, tree_map\nfrom jax.experimental import stax\nfrom jax.flatten_util import ravel_pytree\nimport jax.numpy as jnp\n\nimport numpyro\nfrom numpyro import handlers\nimport numpyro.distributions as dist\nfrom numpyro.distributions import constraints\nfrom numpyro.distributions.flows import BlockNeuralAutoregressiveTransform, InverseAutoregressiveTransform\nfrom numpyro.distributions.transforms import (\n AffineTransform,\n ComposeTransform,\n LowerCholeskyAffine,\n PermuteTransform,\n UnpackTransform,\n biject_to\n)\nfrom numpyro.distributions.util import cholesky_of_inverse, sum_rightmost\nfrom numpyro.infer.elbo import ELBO\nfrom numpyro.infer.util import init_to_uniform, initialize_model\nfrom numpyro.nn.auto_reg_nn import AutoregressiveNN\nfrom numpyro.nn.block_neural_arn import BlockNeuralAutoregressiveNN\nfrom numpyro.util import not_jax_tracer\n\n__all__ = [\n 'AutoContinuous',\n 'AutoGuide',\n 'AutoDiagonalNormal',\n 'AutoLaplaceApproximation',\n 'AutoLowRankMultivariateNormal',\n 'AutoMultivariateNormal',\n 'AutoBNAFNormal',\n 'AutoIAFNormal',\n]\n\n\nclass AutoGuide(ABC):\n \"\"\"\n Base class for automatic guides.\n\n Derived classes must implement the :meth:`__call__` method.\n\n :param callable model: a pyro model\n :param str prefix: a prefix that will be prefixed to all param internal sites\n \"\"\"\n\n def __init__(self, model, prefix='auto'):\n assert isinstance(prefix, str)\n self.model = model\n self.prefix = prefix\n self.prototype_trace = None\n\n @abstractmethod\n def __call__(self, *args, **kwargs):\n \"\"\"\n A guide with the same ``*args, **kwargs`` as the base ``model``.\n\n :return: A dict mapping sample site name to sampled value.\n :rtype: dict\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def sample_posterior(self, rng_key, params, *args, **kwargs):\n \"\"\"\n Generate samples from the approximate posterior over the latent\n sites in the model.\n\n :param jax.random.PRNGKey rng_key: PRNG seed.\n :param params: Current parameters of model and autoguide.\n :param sample_shape: (keyword argument) shape of samples to be drawn.\n :return: batch of samples from the approximate posterior.\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def _sample_latent(self, *args, **kwargs):\n \"\"\"\n Samples an encoded latent given the same ``*args, **kwargs`` as the\n base ``model``.\n \"\"\"\n raise NotImplementedError\n\n def _setup_prototype(self, *args, **kwargs):\n # run the model so we can inspect its structure\n rng_key = numpyro.sample(\"_{}_rng_key_setup\".format(self.prefix), dist.PRNGIdentity())\n model = handlers.seed(self.model, rng_key)\n self.prototype_trace = handlers.block(handlers.trace(model).get_trace)(*args, **kwargs)\n\n\nclass AutoContinuous(AutoGuide):\n \"\"\"\n Base class for implementations of continuous-valued Automatic\n Differentiation Variational Inference [1].\n\n Each derived class implements its own :meth:`_get_posterior` method.\n\n Assumes model structure and latent dimension are fixed, and all latent\n variables are continuous.\n\n **Reference:**\n\n 1. *Automatic Differentiation Variational Inference*,\n Alp Kucukelbir, Dustin Tran, Rajesh Ranganath, Andrew Gelman, David M.\n Blei\n\n :param callable model: A NumPyro model.\n :param str prefix: a prefix that will be prefixed to all param internal sites.\n :param callable init_strategy: A per-site initialization function.\n See :ref:`init_strategy` section for available functions.\n \"\"\"\n def __init__(self, model, prefix=\"auto\", init_strategy=init_to_uniform):\n self.init_strategy = init_strategy\n super(AutoContinuous, self).__init__(model, prefix=prefix)\n\n def _setup_prototype(self, *args, **kwargs):\n rng_key = numpyro.sample(\"_{}_rng_key_setup\".format(self.prefix), dist.PRNGIdentity())\n with handlers.block():\n init_params, _, self._postprocess_fn, self.prototype_trace = initialize_model(\n rng_key, self.model,\n init_strategy=self.init_strategy,\n dynamic_args=False,\n model_args=args,\n model_kwargs=kwargs)\n\n self._init_latent, unpack_latent = ravel_pytree(init_params[0])\n # this is to match the behavior of Pyro, where we can apply\n # unpack_latent for a batch of samples\n self._unpack_latent = UnpackTransform(unpack_latent)\n self.latent_dim = jnp.size(self._init_latent)\n if self.latent_dim == 0:\n raise RuntimeError('{} found no latent variables; Use an empty guide instead'\n .format(type(self).__name__))\n\n @abstractmethod\n def _get_posterior(self):\n raise NotImplementedError\n\n def _sample_latent(self, *args, **kwargs):\n sample_shape = kwargs.pop('sample_shape', ())\n posterior = self._get_posterior()\n return numpyro.sample(\"_{}_latent\".format(self.prefix), posterior, sample_shape=sample_shape)\n\n def __call__(self, *args, **kwargs):\n \"\"\"\n An automatic guide with the same ``*args, **kwargs`` as the base ``model``.\n\n :return: A dict mapping sample site name to sampled value.\n :rtype: dict\n \"\"\"\n if self.prototype_trace is None:\n # run model to inspect the model structure\n self._setup_prototype(*args, **kwargs)\n\n latent = self._sample_latent(*args, **kwargs)\n\n # unpack continuous latent samples\n result = {}\n\n for name, unconstrained_value in self._unpack_latent(latent).items():\n site = self.prototype_trace[name]\n transform = biject_to(site['fn'].support)\n value = transform(unconstrained_value)\n log_density = - transform.log_abs_det_jacobian(unconstrained_value, value)\n event_ndim = len(site['fn'].event_shape)\n log_density = sum_rightmost(log_density,\n jnp.ndim(log_density) - jnp.ndim(value) + event_ndim)\n delta_dist = dist.Delta(value, log_density=log_density, event_dim=event_ndim)\n result[name] = numpyro.sample(name, delta_dist)\n\n return result\n\n def _unpack_and_constrain(self, latent_sample, params):\n def unpack_single_latent(latent):\n unpacked_samples = self._unpack_latent(latent)\n # add param sites in model\n unpacked_samples.update({k: v for k, v in params.items() if k in self.prototype_trace\n and self.prototype_trace[k]['type'] == 'param'})\n return self._postprocess_fn(unpacked_samples)\n\n sample_shape = jnp.shape(latent_sample)[:-1]\n if sample_shape:\n latent_sample = jnp.reshape(latent_sample, (-1, jnp.shape(latent_sample)[-1]))\n unpacked_samples = lax.map(unpack_single_latent, latent_sample)\n return tree_map(lambda x: jnp.reshape(x, sample_shape + jnp.shape(x)[1:]),\n unpacked_samples)\n else:\n return unpack_single_latent(latent_sample)\n\n def get_base_dist(self):\n \"\"\"\n Returns the base distribution of the posterior when reparameterized\n as a :class:`~numpyro.distributions.distribution.TransformedDistribution`. This\n should not depend on the model's `*args, **kwargs`.\n \"\"\"\n raise NotImplementedError\n\n def get_transform(self, params):\n \"\"\"\n Returns the transformation learned by the guide to generate samples from the unconstrained\n (approximate) posterior.\n\n :param dict params: Current parameters of model and autoguide.\n The parameters can be obtained using :meth:`~numpyro.infer.svi.SVI.get_params`\n method from :class:`~numpyro.infer.svi.SVI`.\n :return: the transform of posterior distribution\n :rtype: :class:`~numpyro.distributions.transforms.Transform`\n \"\"\"\n posterior = handlers.substitute(self._get_posterior, params)()\n assert isinstance(posterior, dist.TransformedDistribution), \\\n \"posterior is not a transformed distribution\"\n if len(posterior.transforms) > 0:\n return ComposeTransform(posterior.transforms)\n else:\n return posterior.transforms[0]\n\n def get_posterior(self, params):\n \"\"\"\n Returns the posterior distribution.\n\n :param dict params: Current parameters of model and autoguide.\n The parameters can be obtained using :meth:`~numpyro.infer.svi.SVI.get_params`\n method from :class:`~numpyro.infer.svi.SVI`.\n \"\"\"\n base_dist = self.get_base_dist()\n transform = self.get_transform(params)\n return dist.TransformedDistribution(base_dist, transform)\n\n def sample_posterior(self, rng_key, params, sample_shape=()):\n \"\"\"\n Get samples from the learned posterior.\n\n :param jax.random.PRNGKey rng_key: random key to be used draw samples.\n :param dict params: Current parameters of model and autoguide.\n The parameters can be obtained using :meth:`~numpyro.infer.svi.SVI.get_params`\n method from :class:`~numpyro.infer.svi.SVI`.\n :param tuple sample_shape: batch shape of each latent sample, defaults to ().\n :return: a dict containing samples drawn the this guide.\n :rtype: dict\n \"\"\"\n latent_sample = handlers.substitute(\n handlers.seed(self._sample_latent, rng_key), params)(sample_shape=sample_shape)\n return self._unpack_and_constrain(latent_sample, params)\n\n def median(self, params):\n \"\"\"\n Returns the posterior median value of each latent variable.\n\n :param dict params: A dict containing parameter values.\n The parameters can be obtained using :meth:`~numpyro.infer.svi.SVI.get_params`\n method from :class:`~numpyro.infer.svi.SVI`.\n :return: A dict mapping sample site name to median tensor.\n :rtype: dict\n \"\"\"\n raise NotImplementedError\n\n def quantiles(self, params, quantiles):\n \"\"\"\n Returns posterior quantiles each latent variable. Example::\n\n print(guide.quantiles(opt_state, [0.05, 0.5, 0.95]))\n\n :param dict params: A dict containing parameter values.\n The parameters can be obtained using :meth:`~numpyro.infer.svi.SVI.get_params`\n method from :class:`~numpyro.infer.svi.SVI`.\n :param list quantiles: A list of requested quantiles between 0 and 1.\n :return: A dict mapping sample site name to a list of quantile values.\n :rtype: dict\n \"\"\"\n raise NotImplementedError\n\n\nclass AutoDiagonalNormal(AutoContinuous):\n \"\"\"\n This implementation of :class:`AutoContinuous` uses a Normal distribution\n with a diagonal covariance matrix to construct a guide over the entire\n latent space. The guide does not depend on the model's ``*args, **kwargs``.\n\n Usage::\n\n guide = AutoDiagonalNormal(model, ...)\n svi = SVI(model, guide, ...)\n \"\"\"\n def __init__(self, model, prefix=\"auto\", init_strategy=init_to_uniform, init_scale=0.1):\n if init_scale <= 0:\n raise ValueError(\"Expected init_scale > 0. but got {}\".format(init_scale))\n self._init_scale = init_scale\n super().__init__(model, prefix, init_strategy)\n\n def _get_posterior(self):\n loc = numpyro.param('{}_loc'.format(self.prefix), self._init_latent)\n scale = numpyro.param('{}_scale'.format(self.prefix),\n jnp.full(self.latent_dim, self._init_scale),\n constraint=constraints.positive)\n return dist.Normal(loc, scale)\n\n def get_base_dist(self):\n return dist.Normal(jnp.zeros(self.latent_dim), 1).to_event(1)\n\n def get_transform(self, params):\n loc = params['{}_loc'.format(self.prefix)]\n scale = params['{}_scale'.format(self.prefix)]\n return AffineTransform(loc, scale, domain=constraints.real_vector)\n\n def get_posterior(self, params):\n \"\"\"\n Returns a diagonal Normal posterior distribution.\n \"\"\"\n transform = self.get_transform(params)\n return dist.Normal(transform.loc, transform.scale)\n\n def median(self, params):\n loc = params['{}_loc'.format(self.prefix)]\n return self._unpack_and_constrain(loc, params)\n\n def quantiles(self, params, quantiles):\n quantiles = jnp.array(quantiles)[..., None]\n latent = self.get_posterior(params).icdf(quantiles)\n return self._unpack_and_constrain(latent, params)\n\n\nclass AutoMultivariateNormal(AutoContinuous):\n \"\"\"\n This implementation of :class:`AutoContinuous` uses a MultivariateNormal\n distribution to construct a guide over the entire latent space.\n The guide does not depend on the model's ``*args, **kwargs``.\n\n Usage::\n\n guide = AutoMultivariateNormal(model, ...)\n svi = SVI(model, guide, ...)\n \"\"\"\n def __init__(self, model, prefix=\"auto\", init_strategy=init_to_uniform, init_scale=0.1):\n if init_scale <= 0:\n raise ValueError(\"Expected init_scale > 0. but got {}\".format(init_scale))\n self._init_scale = init_scale\n super().__init__(model, prefix, init_strategy)\n\n def _get_posterior(self):\n loc = numpyro.param('{}_loc'.format(self.prefix), self._init_latent)\n scale_tril = numpyro.param('{}_scale_tril'.format(self.prefix),\n jnp.identity(self.latent_dim) * self._init_scale,\n constraint=constraints.lower_cholesky)\n return dist.MultivariateNormal(loc, scale_tril=scale_tril)\n\n def get_base_dist(self):\n return dist.Normal(jnp.zeros(self.latent_dim), 1).to_event(1)\n\n def get_transform(self, params):\n loc = params['{}_loc'.format(self.prefix)]\n scale_tril = params['{}_scale_tril'.format(self.prefix)]\n return LowerCholeskyAffine(loc, scale_tril)\n\n def get_posterior(self, params):\n \"\"\"\n Returns a multivariate Normal posterior distribution.\n \"\"\"\n transform = self.get_transform(params)\n return dist.MultivariateNormal(transform.loc, transform.scale_tril)\n\n def median(self, params):\n loc = params['{}_loc'.format(self.prefix)]\n return self._unpack_and_constrain(loc, params)\n\n def quantiles(self, params, quantiles):\n transform = self.get_transform(params)\n quantiles = jnp.array(quantiles)[..., None]\n latent = dist.Normal(transform.loc, jnp.diagonal(transform.scale_tril)).icdf(quantiles)\n return self._unpack_and_constrain(latent, params)\n\n\nclass AutoLowRankMultivariateNormal(AutoContinuous):\n \"\"\"\n This implementation of :class:`AutoContinuous` uses a LowRankMultivariateNormal\n distribution to construct a guide over the entire latent space.\n The guide does not depend on the model's ``*args, **kwargs``.\n\n Usage::\n\n guide = AutoLowRankMultivariateNormal(model, rank=2, ...)\n svi = SVI(model, guide, ...)\n \"\"\"\n def __init__(self, model, prefix=\"auto\", init_strategy=init_to_uniform, init_scale=0.1, rank=None):\n if init_scale <= 0:\n raise ValueError(\"Expected init_scale > 0. but got {}\".format(init_scale))\n self._init_scale = init_scale\n self.rank = rank\n super(AutoLowRankMultivariateNormal, self).__init__(\n model, prefix=prefix, init_strategy=init_strategy)\n\n def _get_posterior(self, *args, **kwargs):\n rank = int(round(self.latent_dim ** 0.5)) if self.rank is None else self.rank\n loc = numpyro.param('{}_loc'.format(self.prefix), self._init_latent)\n cov_factor = numpyro.param('{}_cov_factor'.format(self.prefix), jnp.zeros((self.latent_dim, rank)))\n scale = numpyro.param('{}_scale'.format(self.prefix),\n jnp.full(self.latent_dim, self._init_scale),\n constraint=constraints.positive)\n cov_diag = scale * scale\n cov_factor = cov_factor * scale[..., None]\n return dist.LowRankMultivariateNormal(loc, cov_factor, cov_diag)\n\n def get_base_dist(self):\n return dist.Normal(jnp.zeros(self.latent_dim), 1).to_event(1)\n\n def get_transform(self, params):\n posterior = self.get_posterior(params)\n return LowerCholeskyAffine(posterior.loc, posterior.scale_tril)\n\n def get_posterior(self, params):\n \"\"\"\n Returns a lowrank multivariate Normal posterior distribution.\n \"\"\"\n loc = params['{}_loc'.format(self.prefix)]\n cov_factor = params['{}_cov_factor'.format(self.prefix)]\n scale = params['{}_scale'.format(self.prefix)]\n cov_diag = scale * scale\n cov_factor = cov_factor * scale[..., None]\n return dist.LowRankMultivariateNormal(loc, cov_factor, cov_diag)\n\n def median(self, params):\n loc = params['{}_loc'.format(self.prefix)]\n return self._unpack_and_constrain(loc, params)\n\n def quantiles(self, params, quantiles):\n transform = self.get_transform(params)\n quantiles = jnp.array(quantiles)[..., None]\n latent = dist.Normal(transform.loc, jnp.diagonal(transform.scale_tril)).icdf(quantiles)\n return self._unpack_and_constrain(latent, params)\n\n\nclass AutoLaplaceApproximation(AutoContinuous):\n r\"\"\"\n Laplace approximation (quadratic approximation) approximates the posterior\n :math:`\\log p(z | x)` by a multivariate normal distribution in the\n unconstrained space. Under the hood, it uses Delta distributions to\n construct a MAP guide over the entire (unconstrained) latent space. Its\n covariance is given by the inverse of the hessian of :math:`-\\log p(x, z)`\n at the MAP point of `z`.\n\n Usage::\n\n guide = AutoLaplaceApproximation(model, ...)\n svi = SVI(model, guide, ...)\n \"\"\"\n def _setup_prototype(self, *args, **kwargs):\n super(AutoLaplaceApproximation, self)._setup_prototype(*args, **kwargs)\n\n def loss_fn(params):\n # we are doing maximum likelihood, so only require `num_particles=1` and an arbitrary rng_key.\n return ELBO().loss(random.PRNGKey(0), params, self.model, self, *args, **kwargs)\n\n self._loss_fn = loss_fn\n\n def _get_posterior(self, *args, **kwargs):\n # sample from Delta guide\n loc = numpyro.param('{}_loc'.format(self.prefix), self._init_latent)\n return dist.Delta(loc, event_dim=1)\n\n def get_base_dist(self):\n return dist.Normal(jnp.zeros(self.latent_dim), 1).to_event(1)\n\n def get_transform(self, params):\n def loss_fn(z):\n params1 = params.copy()\n params1['{}_loc'.format(self.prefix)] = z\n return self._loss_fn(params1)\n\n loc = params['{}_loc'.format(self.prefix)]\n precision = hessian(loss_fn)(loc)\n scale_tril = cholesky_of_inverse(precision)\n if not_jax_tracer(scale_tril):\n if jnp.any(jnp.isnan(scale_tril)):\n warnings.warn(\"Hessian of log posterior at the MAP point is singular. Posterior\"\n \" samples from AutoLaplaceApproxmiation will be constant (equal to\"\n \" the MAP point).\")\n scale_tril = jnp.where(jnp.isnan(scale_tril), 0., scale_tril)\n return LowerCholeskyAffine(loc, scale_tril)\n\n def get_posterior(self, params):\n \"\"\"\n Returns a multivariate Normal posterior distribution.\n \"\"\"\n transform = self.get_transform(params)\n return dist.MultivariateNormal(transform.loc, scale_tril=transform.scale_tril)\n\n def sample_posterior(self, rng_key, params, sample_shape=()):\n latent_sample = self.get_posterior(params).sample(rng_key, sample_shape)\n return self._unpack_and_constrain(latent_sample, params)\n\n def median(self, params):\n loc = params['{}_loc'.format(self.prefix)]\n return self._unpack_and_constrain(loc, params)\n\n def quantiles(self, params, quantiles):\n transform = self.get_transform(params)\n quantiles = jnp.array(quantiles)[..., None]\n latent = dist.Normal(transform.loc, jnp.diagonal(transform.scale_tril)).icdf(quantiles)\n return self._unpack_and_constrain(latent, params)\n\n\nclass AutoIAFNormal(AutoContinuous):\n \"\"\"\n This implementation of :class:`AutoContinuous` uses a Diagonal Normal\n distribution transformed via a\n :class:`~numpyro.distributions.flows.InverseAutoregressiveTransform`\n to construct a guide over the entire latent space. The guide does not\n depend on the model's ``*args, **kwargs``.\n\n Usage::\n\n guide = AutoIAFNormal(model, hidden_dims=[20], skip_connections=True, ...)\n svi = SVI(model, guide, ...)\n\n :param callable model: a generative model.\n :param str prefix: a prefix that will be prefixed to all param internal sites.\n :param callable init_strategy: A per-site initialization function.\n :param int num_flows: the number of flows to be used, defaults to 3.\n :param list hidden_dims: the dimensionality of the hidden units per layer.\n Defaults to ``[latent_dim, latent_dim]``.\n :param bool skip_connections: whether to add skip connections from the input to the\n output of each flow. Defaults to False.\n :param callable nonlinearity: the nonlinearity to use in the feedforward network.\n Defaults to :func:`jax.experimental.stax.Elu`.\n \"\"\"\n def __init__(self, model, prefix=\"auto\", init_strategy=init_to_uniform,\n num_flows=3, hidden_dims=None, skip_connections=False, nonlinearity=stax.Elu):\n self.num_flows = num_flows\n # 2-layer, stax.Elu, skip_connections=False by default following the experiments in\n # IAF paper (https://arxiv.org/abs/1606.04934)\n # and Neutra paper (https://arxiv.org/abs/1903.03704)\n self._hidden_dims = hidden_dims\n self._skip_connections = skip_connections\n self._nonlinearity = nonlinearity\n super(AutoIAFNormal, self).__init__(model, prefix=prefix, init_strategy=init_strategy)\n\n def _get_posterior(self):\n if self.latent_dim == 1:\n raise ValueError('latent dim = 1. Consider using AutoDiagonalNormal instead')\n hidden_dims = [self.latent_dim, self.latent_dim] if self._hidden_dims is None else self._hidden_dims\n flows = []\n for i in range(self.num_flows):\n if i > 0:\n flows.append(PermuteTransform(jnp.arange(self.latent_dim)[::-1]))\n arn = AutoregressiveNN(self.latent_dim, hidden_dims,\n permutation=jnp.arange(self.latent_dim),\n skip_connections=self._skip_connections,\n nonlinearity=self._nonlinearity)\n arnn = numpyro.module('{}_arn__{}'.format(self.prefix, i), arn, (self.latent_dim,))\n flows.append(InverseAutoregressiveTransform(arnn))\n return dist.TransformedDistribution(self.get_base_dist(), flows)\n\n def get_base_dist(self):\n return dist.Normal(jnp.zeros(self.latent_dim), 1).to_event(1)\n\n\nclass AutoBNAFNormal(AutoContinuous):\n \"\"\"\n This implementation of :class:`AutoContinuous` uses a Diagonal Normal\n distribution transformed via a\n :class:`~numpyro.distributions.flows.BlockNeuralAutoregressiveTransform`\n to construct a guide over the entire latent space. The guide does not\n depend on the model's ``*args, **kwargs``.\n\n Usage::\n\n guide = AutoBNAFNormal(model, num_flows=1, hidden_factors=[50, 50], ...)\n svi = SVI(model, guide, ...)\n\n **References**\n\n 1. *Block Neural Autoregressive Flow*,\n Nicola De Cao, Ivan Titov, Wilker Aziz\n\n :param callable model: a generative model.\n :param str prefix: a prefix that will be prefixed to all param internal sites.\n :param callable init_strategy: A per-site initialization function.\n :param int num_flows: the number of flows to be used, defaults to 3.\n :param list hidden_factors: Hidden layer i has ``hidden_factors[i]`` hidden units per\n input dimension. This corresponds to both :math:`a` and :math:`b` in reference [1].\n The elements of hidden_factors must be integers.\n \"\"\"\n def __init__(self, model, prefix=\"auto\", init_strategy=init_to_uniform, num_flows=1,\n hidden_factors=[8, 8]):\n self.num_flows = num_flows\n self._hidden_factors = hidden_factors\n super(AutoBNAFNormal, self).__init__(model, prefix=prefix, init_strategy=init_strategy)\n\n def _get_posterior(self):\n if self.latent_dim == 1:\n raise ValueError('latent dim = 1. Consider using AutoDiagonalNormal instead')\n flows = []\n for i in range(self.num_flows):\n if i > 0:\n flows.append(PermuteTransform(jnp.arange(self.latent_dim)[::-1]))\n residual = \"gated\" if i < (self.num_flows - 1) else None\n arn = BlockNeuralAutoregressiveNN(self.latent_dim, self._hidden_factors, residual)\n arnn = numpyro.module('{}_arn__{}'.format(self.prefix, i), arn, (self.latent_dim,))\n flows.append(BlockNeuralAutoregressiveTransform(arnn))\n return dist.TransformedDistribution(self.get_base_dist(), flows)\n\n def get_base_dist(self):\n return dist.Normal(jnp.zeros(self.latent_dim), 1).to_event(1)\n", "path": "numpyro/infer/autoguide.py" } ]
[ { "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 jax.numpy as jnp\nfrom jax.scipy.linalg import solve_triangular\nfrom jax.util import partial\n\n# Parameters for Transformed Rejection with Squeeze (TRS) algorithm - page 3.\n_tr_params = namedtuple('tr_params', ['c', 'b', 'a', 'alpha', 'u_r', 'v_r', 'm', 'log_p', 'log1_p', 'log_h'])\n\n\ndef _get_tr_params(n, p):\n # See Table 1. Additionally, we pre-compute log(p), log1(-p) and the\n # constant terms, that depend only on (n, p, m) in log(f(k)) (bottom of page 5).\n mu = n * p\n spq = jnp.sqrt(mu * (1 - p))\n c = mu + 0.5\n b = 1.15 + 2.53 * spq\n a = -0.0873 + 0.0248 * b + 0.01 * p\n alpha = (2.83 + 5.1 / b) * spq\n u_r = 0.43\n v_r = 0.92 - 4.2 / b\n m = jnp.floor((n + 1) * p).astype(n.dtype)\n log_p = jnp.log(p)\n log1_p = jnp.log1p(-p)\n log_h = (m + 0.5) * (jnp.log((m + 1.) / (n - m + 1.)) + log1_p - log_p) + \\\n (stirling_approx_tail(m) + stirling_approx_tail(n - m))\n return _tr_params(c, b, a, alpha, u_r, v_r, m, log_p, log1_p, log_h)\n\n\ndef stirling_approx_tail(k):\n precomputed = jnp.array([\n 0.08106146679532726,\n 0.04134069595540929,\n 0.02767792568499834,\n 0.02079067210376509,\n 0.01664469118982119,\n 0.01387612882307075,\n 0.01189670994589177,\n 0.01041126526197209,\n 0.009255462182712733,\n 0.008330563433362871,\n ])\n kp1 = k + 1\n kp1sq = (k + 1) ** 2\n return jnp.where(k < 10,\n precomputed[k],\n (1. / 12 - (1. / 360 - (1. / 1260) / kp1sq) / kp1sq) / kp1)\n\n\ndef _binomial_btrs(key, p, n):\n \"\"\"\n Based on the transformed rejection sampling algorithm (BTRS) from the\n following reference:\n\n Hormann, \"The Generation of Binonmial Random Variates\"\n (https://core.ac.uk/download/pdf/11007254.pdf)\n \"\"\"\n\n def _btrs_body_fn(val):\n _, key, _, _ = val\n key, key_u, key_v = random.split(key, 3)\n u = random.uniform(key_u)\n v = random.uniform(key_v)\n u = u - 0.5\n k = jnp.floor((2 * tr_params.a / (0.5 - jnp.abs(u)) + tr_params.b) * u + tr_params.c).astype(n.dtype)\n return k, key, u, v\n\n def _btrs_cond_fn(val):\n def accept_fn(k, u, v):\n # See acceptance condition in Step 3. (Page 3) of TRS algorithm\n # v <= f(k) * g_grad(u) / alpha\n\n m = tr_params.m\n log_p = tr_params.log_p\n log1_p = tr_params.log1_p\n # See: formula for log(f(k)) at bottom of Page 5.\n log_f = (n + 1.) * jnp.log((n - m + 1.) / (n - k + 1.)) + \\\n (k + 0.5) * (jnp.log((n - k + 1.) / (k + 1.)) + log_p - log1_p) + \\\n (stirling_approx_tail(k) - stirling_approx_tail(n - k)) + tr_params.log_h\n g = (tr_params.a / (0.5 - jnp.abs(u)) ** 2) + tr_params.b\n return jnp.log((v * tr_params.alpha) / g) <= log_f\n\n k, key, u, v = val\n early_accept = (jnp.abs(u) <= tr_params.u_r) & (v <= tr_params.v_r)\n early_reject = (k < 0) | (k > n)\n return lax.cond(early_accept | early_reject,\n (),\n lambda _: ~early_accept,\n (k, u, v),\n lambda x: ~accept_fn(*x))\n\n tr_params = _get_tr_params(n, p)\n ret = lax.while_loop(_btrs_cond_fn, _btrs_body_fn,\n (-1, key, 1., 1.)) # use k=-1 initially so that cond_fn returns True\n return ret[0]\n\n\ndef _binomial_inversion(key, p, n):\n def _binom_inv_body_fn(val):\n i, key, geom_acc = val\n key, key_u = random.split(key)\n u = random.uniform(key_u)\n geom = jnp.floor(jnp.log1p(-u) / log1_p) + 1\n geom_acc = geom_acc + geom\n return i + 1, key, geom_acc\n\n def _binom_inv_cond_fn(val):\n i, _, geom_acc = val\n return geom_acc <= n\n\n log1_p = jnp.log1p(-p)\n ret = lax.while_loop(_binom_inv_cond_fn, _binom_inv_body_fn,\n (-1, key, 0.))\n return ret[0]\n\n\ndef _binomial_dispatch(key, p, n):\n def dispatch(key, p, n):\n is_le_mid = p <= 0.5\n pq = jnp.where(is_le_mid, p, 1 - p)\n mu = n * pq\n k = lax.cond(mu < 10,\n (key, pq, n),\n lambda x: _binomial_inversion(*x),\n (key, pq, n),\n lambda x: _binomial_btrs(*x))\n return jnp.where(is_le_mid, k, n - k)\n\n # Return 0 for nan `p` or negative `n`, since nan values are not allowed for integer types\n cond0 = jnp.isfinite(p) & (n > 0) & (p > 0)\n return lax.cond(cond0 & (p < 1),\n (key, p, n),\n lambda x: dispatch(*x),\n (),\n lambda _: jnp.where(cond0, n, 0))\n\n\n@partial(jit, static_argnums=(3,))\ndef _binomial(key, p, n, shape):\n shape = shape or lax.broadcast_shapes(jnp.shape(p), jnp.shape(n))\n # reshape to map over axis 0\n p = jnp.reshape(jnp.broadcast_to(p, shape), -1)\n n = jnp.reshape(jnp.broadcast_to(n, shape), -1)\n key = random.split(key, jnp.size(p))\n if xla_bridge.get_backend().platform == 'cpu':\n ret = lax.map(lambda x: _binomial_dispatch(*x),\n (key, p, n))\n else:\n ret = vmap(lambda *x: _binomial_dispatch(*x))(key, p, n)\n return jnp.reshape(ret, shape)\n\n\ndef binomial(key, p, n=1, shape=()):\n return _binomial(key, p, n, shape)\n\n\n@partial(jit, static_argnums=(2,))\ndef _categorical(key, p, shape):\n # this implementation is fast when event shape is small, and slow otherwise\n # Ref: https://stackoverflow.com/a/34190035\n shape = shape or p.shape[:-1]\n s = jnp.cumsum(p, axis=-1)\n r = random.uniform(key, shape=shape + (1,))\n # FIXME: replace this computation by using binary search as suggested in the above\n # reference. A while_loop + vmap for a reshaped 2D array would be enough.\n return jnp.sum(s < r, axis=-1)\n\n\ndef categorical(key, p, shape=()):\n return _categorical(key, p, shape)\n\n\ndef _scatter_add_one(operand, indices, updates):\n return lax.scatter_add(operand, indices, updates,\n lax.ScatterDimensionNumbers(update_window_dims=(),\n inserted_window_dims=(0,),\n scatter_dims_to_operand_dims=(0,)))\n\n\n@partial(jit, static_argnums=(3, 4))\ndef _multinomial(key, p, n, n_max, shape=()):\n if jnp.shape(n) != jnp.shape(p)[:-1]:\n broadcast_shape = lax.broadcast_shapes(jnp.shape(n), jnp.shape(p)[:-1])\n n = jnp.broadcast_to(n, broadcast_shape)\n p = jnp.broadcast_to(p, broadcast_shape + jnp.shape(p)[-1:])\n shape = shape or p.shape[:-1]\n # get indices from categorical distribution then gather the result\n indices = categorical(key, p, (n_max,) + shape)\n # mask out values when counts is heterogeneous\n if jnp.ndim(n) > 0:\n mask = promote_shapes(jnp.arange(n_max) < jnp.expand_dims(n, -1), shape=shape + (n_max,))[0]\n mask = jnp.moveaxis(mask, -1, 0).astype(indices.dtype)\n excess = jnp.concatenate([jnp.expand_dims(n_max - n, -1), jnp.zeros(jnp.shape(n) + (p.shape[-1] - 1,))], -1)\n else:\n mask = 1\n excess = 0\n # NB: we transpose to move batch shape to the front\n indices_2D = (jnp.reshape(indices * mask, (n_max, -1,))).T\n samples_2D = vmap(_scatter_add_one, (0, 0, 0))(jnp.zeros((indices_2D.shape[0], p.shape[-1]),\n dtype=indices.dtype),\n jnp.expand_dims(indices_2D, axis=-1),\n jnp.ones(indices_2D.shape, dtype=indices.dtype))\n return jnp.reshape(samples_2D, shape + p.shape[-1:]) - excess\n\n\ndef multinomial(key, p, n, shape=()):\n n_max = int(jnp.max(n))\n return _multinomial(key, p, n, n_max, shape)\n\n\ndef cholesky_of_inverse(matrix):\n # This formulation only takes the inverse of a triangular matrix\n # which is more numerically stable.\n # Refer to:\n # https://nbviewer.jupyter.org/gist/fehiepsi/5ef8e09e61604f10607380467eb82006#Precision-to-scale_tril\n tril_inv = jnp.swapaxes(jnp.linalg.cholesky(matrix[..., ::-1, ::-1])[..., ::-1, ::-1], -2, -1)\n identity = jnp.broadcast_to(jnp.identity(matrix.shape[-1]), tril_inv.shape)\n return solve_triangular(tril_inv, identity, lower=True)\n\n\n# TODO: move upstream to jax.nn\ndef binary_cross_entropy_with_logits(x, y):\n # compute -y * log(sigmoid(x)) - (1 - y) * log(1 - sigmoid(x))\n # Ref: https://www.tensorflow.org/api_docs/python/tf/nn/sigmoid_cross_entropy_with_logits\n return jnp.clip(x, 0) + jnp.log1p(jnp.exp(-jnp.abs(x))) - x * y\n\n\ndef promote_shapes(*args, shape=()):\n # adapted from lax.lax_numpy\n if len(args) < 2 and not shape:\n return args\n else:\n shapes = [jnp.shape(arg) for arg in args]\n num_dims = len(lax.broadcast_shapes(shape, *shapes))\n return [lax.reshape(arg, (1,) * (num_dims - len(s)) + s)\n if len(s) < num_dims else arg for arg, s in zip(args, shapes)]\n\n\ndef get_dtype(x):\n return canonicalize_dtype(lax.dtype(x))\n\n\ndef sum_rightmost(x, dim):\n \"\"\"\n Sum out ``dim`` many rightmost dimensions of a given tensor.\n \"\"\"\n out_dim = jnp.ndim(x) - dim\n x = jnp.reshape(x[..., jnp.newaxis], jnp.shape(x)[:out_dim] + (-1,))\n return jnp.sum(x, axis=-1)\n\n\ndef matrix_to_tril_vec(x, diagonal=0):\n idxs = jnp.tril_indices(x.shape[-1], diagonal)\n return x[..., idxs[0], idxs[1]]\n\n\ndef vec_to_tril_matrix(t, diagonal=0):\n # NB: the following formula only works for diagonal <= 0\n n = round((math.sqrt(1 + 8 * t.shape[-1]) - 1) / 2) - diagonal\n n2 = n * n\n idx = jnp.reshape(jnp.arange(n2), (n, n))[jnp.tril_indices(n, diagonal)]\n x = lax.scatter_add(jnp.zeros(t.shape[:-1] + (n2,)), jnp.expand_dims(idx, axis=-1), t,\n lax.ScatterDimensionNumbers(update_window_dims=range(t.ndim - 1),\n inserted_window_dims=(t.ndim - 1,),\n scatter_dims_to_operand_dims=(t.ndim - 1,)))\n return jnp.reshape(x, x.shape[:-1] + (n, n))\n\n\ndef cholesky_update(L, x, coef=1):\n \"\"\"\n Finds cholesky of L @ L.T + coef * x @ x.T.\n\n **References;**\n\n 1. A more efficient rank-one covariance matrix update for evolution strategies,\n Oswin Krause and Christian Igel\n \"\"\"\n batch_shape = lax.broadcast_shapes(L.shape[:-2], x.shape[:-1])\n L = jnp.broadcast_to(L, batch_shape + L.shape[-2:])\n x = jnp.broadcast_to(x, batch_shape + x.shape[-1:])\n diag = jnp.diagonal(L, axis1=-2, axis2=-1)\n # convert to unit diagonal triangular matrix: L @ D @ T.t\n L = L / diag[..., None, :]\n D = jnp.square(diag)\n\n def scan_fn(carry, val):\n b, w = carry\n j, Dj, L_j = val\n wj = w[..., j]\n gamma = b * Dj + coef * jnp.square(wj)\n Dj_new = gamma / b\n b = gamma / Dj_new\n\n # update vectors w and L_j\n w = w - wj[..., None] * L_j\n L_j = L_j + (coef * wj / gamma)[..., None] * w\n return (b, w), (Dj_new, L_j)\n\n D, L = jnp.moveaxis(D, -1, 0), jnp.moveaxis(L, -1, 0) # move scan dim to front\n _, (D, L) = lax.scan(scan_fn, (jnp.ones(batch_shape), x), (jnp.arange(D.shape[0]), D, L))\n D, L = jnp.moveaxis(D, 0, -1), jnp.moveaxis(L, 0, -1) # move scan dim back\n return L * jnp.sqrt(D)[..., None, :]\n\n\ndef signed_stick_breaking_tril(t):\n # make sure that t in (-1, 1)\n eps = jnp.finfo(t.dtype).eps\n t = jnp.clip(t, a_min=(-1 + eps), a_max=(1 - eps))\n # transform t to tril matrix with identity diagonal\n r = vec_to_tril_matrix(t, diagonal=-1)\n\n # apply stick-breaking on the squared values;\n # we omit the step of computing s = z * z_cumprod by using the fact:\n # y = sign(r) * s = sign(r) * sqrt(z * z_cumprod) = r * sqrt(z_cumprod)\n z = r ** 2\n z1m_cumprod = jnp.cumprod(1 - z, axis=-1)\n z1m_cumprod_sqrt = jnp.sqrt(z1m_cumprod)\n\n pad_width = [(0, 0)] * z.ndim\n pad_width[-1] = (1, 0)\n z1m_cumprod_sqrt_shifted = jnp.pad(z1m_cumprod_sqrt[..., :-1], pad_width,\n mode=\"constant\", constant_values=1.)\n y = (r + jnp.identity(r.shape[-1])) * z1m_cumprod_sqrt_shifted\n return y\n\n\ndef logmatmulexp(x, y):\n \"\"\"\n Numerically stable version of ``(x.log() @ y.log()).exp()``.\n \"\"\"\n x_shift = lax.stop_gradient(jnp.amax(x, -1, keepdims=True))\n y_shift = lax.stop_gradient(jnp.amax(y, -2, keepdims=True))\n xy = jnp.log(jnp.matmul(jnp.exp(x - x_shift), jnp.exp(y - y_shift)))\n return xy + x_shift + y_shift\n\n\ndef clamp_probs(probs):\n finfo = jnp.finfo(get_dtype(probs))\n return jnp.clip(probs, a_min=finfo.tiny, a_max=1. - finfo.eps)\n\n\ndef is_identically_one(x):\n \"\"\"\n Check if argument is exactly the number one. True for the number one;\n false for other numbers; false for ndarrays.\n \"\"\"\n if isinstance(x, (int, float)):\n return x == 1\n else:\n return False\n\n\ndef von_mises_centered(key, concentration, shape=(), dtype=jnp.float64):\n \"\"\" Compute centered von Mises samples using rejection sampling from [1] with wrapped Cauchy proposal.\n\n *** References ***\n [1] Luc Devroye \"Non-Uniform Random Variate Generation\", Springer-Verlag, 1986;\n Chapter 9, p. 473-476. http://www.nrbook.com/devroye/Devroye_files/chapter_nine.pdf\n\n\n :param key: random number generator key\n :param concentration: concentration of distribution\n :param shape: shape of samples\n :param dtype: float precesions for choosing correct s cutfoff\n :return: centered samples from von Mises\n \"\"\"\n shape = shape or jnp.shape(concentration)\n dtype = canonicalize_dtype(dtype)\n concentration = lax.convert_element_type(concentration, dtype)\n concentration = jnp.broadcast_to(concentration, shape)\n return _von_mises_centered(key, concentration, shape, dtype)\n\n\n@partial(jit, static_argnums=(2, 3))\ndef _von_mises_centered(key, concentration, shape, dtype):\n # Cutoff from TensorFlow probability\n # (https://github.com/tensorflow/probability/blob/f051e03dd3cc847d31061803c2b31c564562a993/tensorflow_probability/python/distributions/von_mises.py#L567-L570)\n s_cutoff_map = {jnp.dtype(jnp.float16): 1.8e-1,\n jnp.dtype(jnp.float32): 2e-2,\n jnp.dtype(jnp.float64): 1.2e-4}\n s_cutoff = s_cutoff_map.get(dtype)\n\n r = 1. + jnp.sqrt(1. + 4. * concentration ** 2)\n rho = (r - jnp.sqrt(2. * r)) / (2. * concentration)\n s_exact = (1. + rho ** 2) / (2. * rho)\n\n s_approximate = 1. / concentration\n\n s = jnp.where(concentration > s_cutoff, s_exact, s_approximate)\n\n def cond_fn(*args):\n \"\"\" check if all are done or reached max number of iterations \"\"\"\n i, _, done, _, _ = args[0]\n return jnp.bitwise_and(i < 100, jnp.logical_not(jnp.all(done)))\n\n def body_fn(*args):\n i, key, done, _, w = args[0]\n uni_ukey, uni_vkey, key = random.split(key, 3)\n\n u = random.uniform(key=uni_ukey, shape=shape, dtype=concentration.dtype, minval=-1., maxval=1.)\n z = jnp.cos(jnp.pi * u)\n w = jnp.where(done, w, (1. + s * z) / (s + z)) # Update where not done\n\n y = concentration * (s - w)\n v = random.uniform(key=uni_vkey, shape=shape, dtype=concentration.dtype, minval=-1., maxval=1.)\n\n accept = (y * (2. - y) >= v) | (jnp.log(y / v) + 1. >= y)\n\n return i+1, key, accept | done, u, w\n\n init_done = jnp.zeros(shape, dtype=bool)\n init_u = jnp.zeros(shape)\n init_w = jnp.zeros(shape)\n\n _, _, done, u, w = lax.while_loop(\n cond_fun=cond_fn,\n body_fun=body_fn,\n init_val=(jnp.array(0), key, init_done, init_u, init_w)\n )\n\n return jnp.sign(u) * jnp.arccos(w)\n\n\n# TODO: use funsor implementation\ndef periodic_repeat(x, size, dim):\n \"\"\"\n Repeat a ``period``-sized array up to given ``size``.\n \"\"\"\n assert isinstance(size, int) and size >= 0\n assert isinstance(dim, int)\n if dim >= 0:\n dim -= jnp.ndim(x)\n\n period = jnp.shape(x)[dim]\n repeats = (size + period - 1) // period\n result = jnp.repeat(x, repeats, axis=dim)\n result = result[(Ellipsis, slice(None, size)) + (slice(None),) * (-1 - dim)]\n return result\n\n\n# The is sourced from: torch.distributions.util.py\n#\n# Copyright (c) 2016- Facebook, Inc (Adam Paszke)\n# Copyright (c) 2014- Facebook, Inc (Soumith Chintala)\n# Copyright (c) 2011-2014 Idiap Research Institute (Ronan Collobert)\n# Copyright (c) 2012-2014 Deepmind Technologies (Koray Kavukcuoglu)\n# Copyright (c) 2011-2012 NEC Laboratories America (Koray Kavukcuoglu)\n# Copyright (c) 2011-2013 NYU (Clement Farabet)\n# Copyright (c) 2006-2010 NEC Laboratories America (Ronan Collobert, Leon Bottou, Iain Melvin, Jason Weston)\n# Copyright (c) 2006 Idiap Research Institute (Samy Bengio)\n# Copyright (c) 2001-2004 Idiap Research Institute (Ronan Collobert, Samy Bengio, Johnny Mariethoz)\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\nclass lazy_property(object):\n r\"\"\"\n Used as a decorator for lazy loading of class attributes. This uses a\n non-data descriptor that calls the wrapped method to compute the property on\n first call; thereafter replacing the wrapped method into an instance\n attribute.\n \"\"\"\n\n def __init__(self, wrapped):\n self.wrapped = wrapped\n update_wrapper(self, wrapped)\n\n # This is to prevent warnings from sphinx\n def __call__(self, *args, **kwargs):\n return self.wrapped(*args, **kwargs)\n\n def __get__(self, instance, obj_type=None):\n if instance is None:\n return self\n value = self.wrapped(instance)\n setattr(instance, self.wrapped.__name__, value)\n return value\n\n\ndef validate_sample(log_prob_fn):\n def wrapper(self, *args, **kwargs):\n log_prob = log_prob_fn(self, *args, *kwargs)\n if self._validate_args:\n value = kwargs['value'] if 'value' in kwargs else args[0]\n mask = self._validate_sample(value)\n log_prob = jnp.where(mask, log_prob, -jnp.inf)\n return log_prob\n\n return wrapper\n", "path": "numpyro/distributions/util.py" }, { "content": "# Copyright Contributors to the Pyro project.\n# SPDX-License-Identifier: Apache-2.0\n\n# Adapted from pyro.infer.autoguide\nfrom abc import ABC, abstractmethod\nfrom contextlib import ExitStack\nimport warnings\n\nfrom jax import hessian, lax, random, tree_map\nfrom jax.experimental import stax\nfrom jax.flatten_util import ravel_pytree\nimport jax.numpy as jnp\n\nimport numpyro\nfrom numpyro import handlers\nimport numpyro.distributions as dist\nfrom numpyro.distributions import constraints\nfrom numpyro.distributions.flows import BlockNeuralAutoregressiveTransform, InverseAutoregressiveTransform\nfrom numpyro.distributions.transforms import (\n AffineTransform,\n ComposeTransform,\n LowerCholeskyAffine,\n PermuteTransform,\n UnpackTransform,\n biject_to\n)\nfrom numpyro.distributions.util import cholesky_of_inverse, periodic_repeat, sum_rightmost\nfrom numpyro.infer.elbo import ELBO\nfrom numpyro.infer.util import init_to_uniform, initialize_model\nfrom numpyro.nn.auto_reg_nn import AutoregressiveNN\nfrom numpyro.nn.block_neural_arn import BlockNeuralAutoregressiveNN\nfrom numpyro.util import not_jax_tracer\n\n__all__ = [\n 'AutoContinuous',\n 'AutoGuide',\n 'AutoDiagonalNormal',\n 'AutoLaplaceApproximation',\n 'AutoLowRankMultivariateNormal',\n 'AutoNormal',\n 'AutoMultivariateNormal',\n 'AutoBNAFNormal',\n 'AutoIAFNormal',\n]\n\n\nclass AutoGuide(ABC):\n \"\"\"\n Base class for automatic guides.\n\n Derived classes must implement the :meth:`__call__` method.\n\n :param callable model: a pyro model\n :param str prefix: a prefix that will be prefixed to all param internal sites\n :param callable init_strategy: A per-site initialization function.\n See :ref:`init_strategy` section for available functions.\n :param callable create_plates: An optional function inputing the same\n ``*args,**kwargs`` as ``model()`` and returning a :class:`numpyro.plate`\n or iterable of plates. Plates not returned will be created\n automatically as usual. This is useful for data subsampling.\n \"\"\"\n\n def __init__(self, model, *, prefix=\"auto\", init_strategy=init_to_uniform, create_plates=None):\n self.model = model\n self.prefix = prefix\n self.init_strategy = init_strategy\n self.create_plates = create_plates\n self.prototype_trace = None\n self._prototype_frames = {}\n self._prototype_frame_full_sizes = {}\n\n def _create_plates(self, *args, **kwargs):\n if self.create_plates is None:\n self.plates = {}\n else:\n plates = self.create_plates(*args, **kwargs)\n if isinstance(plates, numpyro.plate):\n plates = [plates]\n assert all(isinstance(p, numpyro.plate) for p in plates), \\\n \"create_plates() returned a non-plate\"\n self.plates = {p.name: p for p in plates}\n for name, frame in sorted(self._prototype_frames.items()):\n if name not in self.plates:\n full_size = self._prototype_frame_full_sizes[name]\n self.plates[name] = numpyro.plate(name, full_size, dim=frame.dim,\n subsample_size=frame.size)\n return self.plates\n\n @abstractmethod\n def __call__(self, *args, **kwargs):\n \"\"\"\n A guide with the same ``*args, **kwargs`` as the base ``model``.\n\n :return: A dict mapping sample site name to sampled value.\n :rtype: dict\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def sample_posterior(self, rng_key, params, *args, **kwargs):\n \"\"\"\n Generate samples from the approximate posterior over the latent\n sites in the model.\n\n :param jax.random.PRNGKey rng_key: PRNG seed.\n :param params: Current parameters of model and autoguide.\n :param sample_shape: (keyword argument) shape of samples to be drawn.\n :return: batch of samples from the approximate posterior.\n \"\"\"\n raise NotImplementedError\n\n def _setup_prototype(self, *args, **kwargs):\n rng_key = numpyro.sample(\"_{}_rng_key_setup\".format(self.prefix), dist.PRNGIdentity())\n with handlers.block():\n init_params, _, self._postprocess_fn, self.prototype_trace = initialize_model(\n rng_key, self.model,\n init_strategy=self.init_strategy,\n dynamic_args=False,\n model_args=args,\n model_kwargs=kwargs)\n self._init_locs = init_params[0]\n\n self._prototype_frames = {}\n self._prototype_plate_sizes = {}\n for name, site in self.prototype_trace.items():\n if site[\"type\"] == \"sample\":\n for frame in site[\"cond_indep_stack\"]:\n self._prototype_frames[frame.name] = frame\n elif site[\"type\"] == \"plate\":\n self._prototype_frame_full_sizes[name] = site[\"args\"][0]\n\n\nclass AutoNormal(AutoGuide):\n \"\"\"\n This implementation of :class:`AutoGuide` uses Normal distributions\n to construct a guide over the entire latent space. The guide does not\n depend on the model's ``*args, **kwargs``.\n\n This should be equivalent to :class: `AutoDiagonalNormal` , but with\n more convenient site names and with better support for mean field ELBO.\n\n Usage::\n\n guide = AutoNormal(model)\n svi = SVI(model, guide, ...)\n\n :param callable model: A NumPyro model.\n :param str prefix: a prefix that will be prefixed to all param internal sites.\n :param callable init_strategy: A per-site initialization function.\n See :ref:`init_strategy` section for available functions.\n :param float init_scale: Initial scale for the standard deviation of each\n (unconstrained transformed) latent variable.\n :param callable create_plates: An optional function inputing the same\n ``*args,**kwargs`` as ``model()`` and returning a :class:`numpyro.plate`\n or iterable of plates. Plates not returned will be created\n automatically as usual. This is useful for data subsampling.\n \"\"\"\n def __init__(self, model, *, prefix=\"auto\", init_strategy=init_to_uniform, init_scale=0.1,\n create_plates=None):\n # TODO: rename `init_strategy` to `init_loc_fn` to be consistent with Pyro\n self._init_scale = init_scale\n self._event_dims = {}\n super().__init__(model, prefix=prefix, init_strategy=init_strategy, create_plates=create_plates)\n\n def _setup_prototype(self, *args, **kwargs):\n super()._setup_prototype(*args, **kwargs)\n\n for name, site in self.prototype_trace.items():\n if site[\"type\"] != \"sample\" or isinstance(site[\"fn\"], dist.PRNGIdentity) or site[\"is_observed\"]:\n continue\n\n event_dim = site[\"fn\"].event_dim + jnp.ndim(self._init_locs[name]) - jnp.ndim(site[\"value\"])\n self._event_dims[name] = event_dim\n\n # If subsampling, repeat init_value to full size.\n for frame in site[\"cond_indep_stack\"]:\n full_size = self._prototype_frame_full_sizes[frame.name]\n if full_size != frame.size:\n dim = frame.dim - event_dim\n self._init_locs[name] = periodic_repeat(self._init_locs[name], full_size, dim)\n\n def __call__(self, *args, **kwargs):\n \"\"\"\n An automatic guide with the same ``*args, **kwargs`` as the base ``model``.\n\n :return: A dict mapping sample site name to sampled value.\n :rtype: dict\n \"\"\"\n if self.prototype_trace is None:\n # run model to inspect the model structure\n self._setup_prototype(*args, **kwargs)\n\n plates = self._create_plates(*args, **kwargs)\n result = {}\n for name, site in self.prototype_trace.items():\n if site[\"type\"] != \"sample\" or isinstance(site[\"fn\"], dist.PRNGIdentity) or site[\"is_observed\"]:\n continue\n\n event_dim = self._event_dims[name]\n init_loc = self._init_locs[name]\n with ExitStack() as stack:\n for frame in site[\"cond_indep_stack\"]:\n stack.enter_context(plates[frame.name])\n\n site_loc = numpyro.param(\"{}_{}_loc\".format(name, self.prefix), init_loc,\n event_dim=event_dim)\n site_scale = numpyro.param(\"{}_{}_scale\".format(name, self.prefix),\n jnp.full(jnp.shape(init_loc), self._init_scale),\n constraint=constraints.positive,\n event_dim=event_dim)\n\n site_fn = dist.Normal(site_loc, site_scale).to_event(event_dim)\n if site[\"fn\"].support in [constraints.real, constraints.real_vector]:\n result[name] = numpyro.sample(name, site_fn)\n else:\n unconstrained_value = numpyro.sample(\"{}_unconstrained\".format(name), site_fn,\n infer={\"is_auxiliary\": True})\n\n transform = biject_to(site['fn'].support)\n value = transform(unconstrained_value)\n log_density = - transform.log_abs_det_jacobian(unconstrained_value, value)\n log_density = sum_rightmost(log_density,\n jnp.ndim(log_density) - jnp.ndim(value) + site[\"fn\"].event_dim)\n delta_dist = dist.Delta(value, log_density=log_density, event_dim=site[\"fn\"].event_dim)\n result[name] = numpyro.sample(name, delta_dist)\n\n return result\n\n def _constrain(self, latent_samples):\n name = list(latent_samples)[0]\n sample_shape = jnp.shape(latent_samples[name])[\n :jnp.ndim(latent_samples[name]) - jnp.ndim(self._init_locs[name])]\n if sample_shape:\n flatten_samples = tree_map(lambda x: jnp.reshape(x, (-1,) + jnp.shape(x)[len(sample_shape):]),\n latent_samples)\n contrained_samples = lax.map(self._postprocess_fn, flatten_samples)\n return tree_map(lambda x: jnp.reshape(x, sample_shape + jnp.shape(x)[1:]),\n contrained_samples)\n else:\n return self._postprocess_fn(latent_samples)\n\n def sample_posterior(self, rng_key, params, sample_shape=()):\n locs = {k: params[\"{}_{}_loc\".format(k, self.prefix)] for k in self._init_locs}\n scales = {k: params[\"{}_{}_scale\".format(k, self.prefix)] for k in locs}\n with handlers.seed(rng_seed=rng_key):\n latent_samples = {}\n for k in locs:\n latent_samples[k] = numpyro.sample(k, dist.Normal(locs[k], scales[k]).expand_by(sample_shape))\n return self._constrain(latent_samples)\n\n def median(self, params):\n locs = {k: params[\"{}_{}_loc\".format(k, self.prefix)] for k, v in self._init_locs.items()}\n return self._constrain(locs)\n\n def quantiles(self, params, quantiles):\n quantiles = jnp.array(quantiles)[..., None]\n locs = {k: params[\"{}_{}_loc\".format(k, self.prefix)] for k in self._init_locs}\n scales = {k: params[\"{}_{}_scale\".format(k, self.prefix)] for k in locs}\n latent = {k: dist.Normal(locs[k], scales[k]).icdf(quantiles) for k in locs}\n return self._constrain(latent)\n\n\nclass AutoContinuous(AutoGuide):\n \"\"\"\n Base class for implementations of continuous-valued Automatic\n Differentiation Variational Inference [1].\n\n Each derived class implements its own :meth:`_get_posterior` method.\n\n Assumes model structure and latent dimension are fixed, and all latent\n variables are continuous.\n\n **Reference:**\n\n 1. *Automatic Differentiation Variational Inference*,\n Alp Kucukelbir, Dustin Tran, Rajesh Ranganath, Andrew Gelman, David M.\n Blei\n\n :param callable model: A NumPyro model.\n :param str prefix: a prefix that will be prefixed to all param internal sites.\n :param callable init_strategy: A per-site initialization function.\n See :ref:`init_strategy` section for available functions.\n \"\"\"\n def _setup_prototype(self, *args, **kwargs):\n super()._setup_prototype(*args, **kwargs)\n self._init_latent, unpack_latent = ravel_pytree(self._init_locs)\n # this is to match the behavior of Pyro, where we can apply\n # unpack_latent for a batch of samples\n self._unpack_latent = UnpackTransform(unpack_latent)\n self.latent_dim = jnp.size(self._init_latent)\n if self.latent_dim == 0:\n raise RuntimeError('{} found no latent variables; Use an empty guide instead'\n .format(type(self).__name__))\n\n @abstractmethod\n def _get_posterior(self):\n raise NotImplementedError\n\n def _sample_latent(self, *args, **kwargs):\n sample_shape = kwargs.pop('sample_shape', ())\n posterior = self._get_posterior()\n return numpyro.sample(\"_{}_latent\".format(self.prefix), posterior.expand_by(sample_shape),\n infer={\"is_auxiliary\": True})\n\n def __call__(self, *args, **kwargs):\n \"\"\"\n An automatic guide with the same ``*args, **kwargs`` as the base ``model``.\n\n :return: A dict mapping sample site name to sampled value.\n :rtype: dict\n \"\"\"\n if self.prototype_trace is None:\n # run model to inspect the model structure\n self._setup_prototype(*args, **kwargs)\n\n latent = self._sample_latent(*args, **kwargs)\n\n # unpack continuous latent samples\n result = {}\n\n for name, unconstrained_value in self._unpack_latent(latent).items():\n site = self.prototype_trace[name]\n transform = biject_to(site['fn'].support)\n value = transform(unconstrained_value)\n log_density = - transform.log_abs_det_jacobian(unconstrained_value, value)\n event_ndim = len(site['fn'].event_shape)\n log_density = sum_rightmost(log_density,\n jnp.ndim(log_density) - jnp.ndim(value) + event_ndim)\n delta_dist = dist.Delta(value, log_density=log_density, event_dim=event_ndim)\n result[name] = numpyro.sample(name, delta_dist)\n\n return result\n\n def _unpack_and_constrain(self, latent_sample, params):\n def unpack_single_latent(latent):\n unpacked_samples = self._unpack_latent(latent)\n # TODO: this seems to be a legacy behavior? why we need to add param here?\n # add param sites in model\n unpacked_samples.update({k: v for k, v in params.items() if k in self.prototype_trace\n and self.prototype_trace[k]['type'] == 'param'})\n return self._postprocess_fn(unpacked_samples)\n\n sample_shape = jnp.shape(latent_sample)[:-1]\n if sample_shape:\n latent_sample = jnp.reshape(latent_sample, (-1, jnp.shape(latent_sample)[-1]))\n unpacked_samples = lax.map(unpack_single_latent, latent_sample)\n return tree_map(lambda x: jnp.reshape(x, sample_shape + jnp.shape(x)[1:]),\n unpacked_samples)\n else:\n return unpack_single_latent(latent_sample)\n\n def get_base_dist(self):\n \"\"\"\n Returns the base distribution of the posterior when reparameterized\n as a :class:`~numpyro.distributions.distribution.TransformedDistribution`. This\n should not depend on the model's `*args, **kwargs`.\n \"\"\"\n raise NotImplementedError\n\n def get_transform(self, params):\n \"\"\"\n Returns the transformation learned by the guide to generate samples from the unconstrained\n (approximate) posterior.\n\n :param dict params: Current parameters of model and autoguide.\n The parameters can be obtained using :meth:`~numpyro.infer.svi.SVI.get_params`\n method from :class:`~numpyro.infer.svi.SVI`.\n :return: the transform of posterior distribution\n :rtype: :class:`~numpyro.distributions.transforms.Transform`\n \"\"\"\n posterior = handlers.substitute(self._get_posterior, params)()\n assert isinstance(posterior, dist.TransformedDistribution), \\\n \"posterior is not a transformed distribution\"\n if len(posterior.transforms) > 0:\n return ComposeTransform(posterior.transforms)\n else:\n return posterior.transforms[0]\n\n def get_posterior(self, params):\n \"\"\"\n Returns the posterior distribution.\n\n :param dict params: Current parameters of model and autoguide.\n The parameters can be obtained using :meth:`~numpyro.infer.svi.SVI.get_params`\n method from :class:`~numpyro.infer.svi.SVI`.\n \"\"\"\n base_dist = self.get_base_dist()\n transform = self.get_transform(params)\n return dist.TransformedDistribution(base_dist, transform)\n\n def sample_posterior(self, rng_key, params, sample_shape=()):\n \"\"\"\n Get samples from the learned posterior.\n\n :param jax.random.PRNGKey rng_key: random key to be used draw samples.\n :param dict params: Current parameters of model and autoguide.\n The parameters can be obtained using :meth:`~numpyro.infer.svi.SVI.get_params`\n method from :class:`~numpyro.infer.svi.SVI`.\n :param tuple sample_shape: batch shape of each latent sample, defaults to ().\n :return: a dict containing samples drawn the this guide.\n :rtype: dict\n \"\"\"\n latent_sample = handlers.substitute(\n handlers.seed(self._sample_latent, rng_key), params)(sample_shape=sample_shape)\n return self._unpack_and_constrain(latent_sample, params)\n\n def median(self, params):\n \"\"\"\n Returns the posterior median value of each latent variable.\n\n :param dict params: A dict containing parameter values.\n The parameters can be obtained using :meth:`~numpyro.infer.svi.SVI.get_params`\n method from :class:`~numpyro.infer.svi.SVI`.\n :return: A dict mapping sample site name to median tensor.\n :rtype: dict\n \"\"\"\n raise NotImplementedError\n\n def quantiles(self, params, quantiles):\n \"\"\"\n Returns posterior quantiles each latent variable. Example::\n\n print(guide.quantiles(opt_state, [0.05, 0.5, 0.95]))\n\n :param dict params: A dict containing parameter values.\n The parameters can be obtained using :meth:`~numpyro.infer.svi.SVI.get_params`\n method from :class:`~numpyro.infer.svi.SVI`.\n :param list quantiles: A list of requested quantiles between 0 and 1.\n :return: A dict mapping sample site name to a list of quantile values.\n :rtype: dict\n \"\"\"\n raise NotImplementedError\n\n\nclass AutoDiagonalNormal(AutoContinuous):\n \"\"\"\n This implementation of :class:`AutoContinuous` uses a Normal distribution\n with a diagonal covariance matrix to construct a guide over the entire\n latent space. The guide does not depend on the model's ``*args, **kwargs``.\n\n Usage::\n\n guide = AutoDiagonalNormal(model, ...)\n svi = SVI(model, guide, ...)\n \"\"\"\n def __init__(self, model, *, prefix=\"auto\", init_strategy=init_to_uniform, init_scale=0.1):\n if init_scale <= 0:\n raise ValueError(\"Expected init_scale > 0. but got {}\".format(init_scale))\n self._init_scale = init_scale\n super().__init__(model, prefix=prefix, init_strategy=init_strategy)\n\n def _get_posterior(self):\n loc = numpyro.param('{}_loc'.format(self.prefix), self._init_latent)\n scale = numpyro.param('{}_scale'.format(self.prefix),\n jnp.full(self.latent_dim, self._init_scale),\n constraint=constraints.positive)\n return dist.Normal(loc, scale)\n\n def get_base_dist(self):\n return dist.Normal(jnp.zeros(self.latent_dim), 1).to_event(1)\n\n def get_transform(self, params):\n loc = params['{}_loc'.format(self.prefix)]\n scale = params['{}_scale'.format(self.prefix)]\n return AffineTransform(loc, scale, domain=constraints.real_vector)\n\n def get_posterior(self, params):\n \"\"\"\n Returns a diagonal Normal posterior distribution.\n \"\"\"\n transform = self.get_transform(params)\n return dist.Normal(transform.loc, transform.scale)\n\n def median(self, params):\n loc = params['{}_loc'.format(self.prefix)]\n return self._unpack_and_constrain(loc, params)\n\n def quantiles(self, params, quantiles):\n quantiles = jnp.array(quantiles)[..., None]\n latent = self.get_posterior(params).icdf(quantiles)\n return self._unpack_and_constrain(latent, params)\n\n\nclass AutoMultivariateNormal(AutoContinuous):\n \"\"\"\n This implementation of :class:`AutoContinuous` uses a MultivariateNormal\n distribution to construct a guide over the entire latent space.\n The guide does not depend on the model's ``*args, **kwargs``.\n\n Usage::\n\n guide = AutoMultivariateNormal(model, ...)\n svi = SVI(model, guide, ...)\n \"\"\"\n def __init__(self, model, *, prefix=\"auto\", init_strategy=init_to_uniform, init_scale=0.1):\n if init_scale <= 0:\n raise ValueError(\"Expected init_scale > 0. but got {}\".format(init_scale))\n self._init_scale = init_scale\n super().__init__(model, prefix=prefix, init_strategy=init_strategy)\n\n def _get_posterior(self):\n loc = numpyro.param('{}_loc'.format(self.prefix), self._init_latent)\n scale_tril = numpyro.param('{}_scale_tril'.format(self.prefix),\n jnp.identity(self.latent_dim) * self._init_scale,\n constraint=constraints.lower_cholesky)\n return dist.MultivariateNormal(loc, scale_tril=scale_tril)\n\n def get_base_dist(self):\n return dist.Normal(jnp.zeros(self.latent_dim), 1).to_event(1)\n\n def get_transform(self, params):\n loc = params['{}_loc'.format(self.prefix)]\n scale_tril = params['{}_scale_tril'.format(self.prefix)]\n return LowerCholeskyAffine(loc, scale_tril)\n\n def get_posterior(self, params):\n \"\"\"\n Returns a multivariate Normal posterior distribution.\n \"\"\"\n transform = self.get_transform(params)\n return dist.MultivariateNormal(transform.loc, transform.scale_tril)\n\n def median(self, params):\n loc = params['{}_loc'.format(self.prefix)]\n return self._unpack_and_constrain(loc, params)\n\n def quantiles(self, params, quantiles):\n transform = self.get_transform(params)\n quantiles = jnp.array(quantiles)[..., None]\n latent = dist.Normal(transform.loc, jnp.diagonal(transform.scale_tril)).icdf(quantiles)\n return self._unpack_and_constrain(latent, params)\n\n\nclass AutoLowRankMultivariateNormal(AutoContinuous):\n \"\"\"\n This implementation of :class:`AutoContinuous` uses a LowRankMultivariateNormal\n distribution to construct a guide over the entire latent space.\n The guide does not depend on the model's ``*args, **kwargs``.\n\n Usage::\n\n guide = AutoLowRankMultivariateNormal(model, rank=2, ...)\n svi = SVI(model, guide, ...)\n \"\"\"\n def __init__(self, model, *, prefix=\"auto\", init_strategy=init_to_uniform, init_scale=0.1, rank=None):\n if init_scale <= 0:\n raise ValueError(\"Expected init_scale > 0. but got {}\".format(init_scale))\n self._init_scale = init_scale\n self.rank = rank\n super(AutoLowRankMultivariateNormal, self).__init__(\n model, prefix=prefix, init_strategy=init_strategy)\n\n def _get_posterior(self, *args, **kwargs):\n rank = int(round(self.latent_dim ** 0.5)) if self.rank is None else self.rank\n loc = numpyro.param('{}_loc'.format(self.prefix), self._init_latent)\n cov_factor = numpyro.param('{}_cov_factor'.format(self.prefix), jnp.zeros((self.latent_dim, rank)))\n scale = numpyro.param('{}_scale'.format(self.prefix),\n jnp.full(self.latent_dim, self._init_scale),\n constraint=constraints.positive)\n cov_diag = scale * scale\n cov_factor = cov_factor * scale[..., None]\n return dist.LowRankMultivariateNormal(loc, cov_factor, cov_diag)\n\n def get_base_dist(self):\n return dist.Normal(jnp.zeros(self.latent_dim), 1).to_event(1)\n\n def get_transform(self, params):\n posterior = self.get_posterior(params)\n return LowerCholeskyAffine(posterior.loc, posterior.scale_tril)\n\n def get_posterior(self, params):\n \"\"\"\n Returns a lowrank multivariate Normal posterior distribution.\n \"\"\"\n loc = params['{}_loc'.format(self.prefix)]\n cov_factor = params['{}_cov_factor'.format(self.prefix)]\n scale = params['{}_scale'.format(self.prefix)]\n cov_diag = scale * scale\n cov_factor = cov_factor * scale[..., None]\n return dist.LowRankMultivariateNormal(loc, cov_factor, cov_diag)\n\n def median(self, params):\n loc = params['{}_loc'.format(self.prefix)]\n return self._unpack_and_constrain(loc, params)\n\n def quantiles(self, params, quantiles):\n transform = self.get_transform(params)\n quantiles = jnp.array(quantiles)[..., None]\n latent = dist.Normal(transform.loc, jnp.diagonal(transform.scale_tril)).icdf(quantiles)\n return self._unpack_and_constrain(latent, params)\n\n\nclass AutoLaplaceApproximation(AutoContinuous):\n r\"\"\"\n Laplace approximation (quadratic approximation) approximates the posterior\n :math:`\\log p(z | x)` by a multivariate normal distribution in the\n unconstrained space. Under the hood, it uses Delta distributions to\n construct a MAP guide over the entire (unconstrained) latent space. Its\n covariance is given by the inverse of the hessian of :math:`-\\log p(x, z)`\n at the MAP point of `z`.\n\n Usage::\n\n guide = AutoLaplaceApproximation(model, ...)\n svi = SVI(model, guide, ...)\n \"\"\"\n def _setup_prototype(self, *args, **kwargs):\n super(AutoLaplaceApproximation, self)._setup_prototype(*args, **kwargs)\n\n def loss_fn(params):\n # we are doing maximum likelihood, so only require `num_particles=1` and an arbitrary rng_key.\n return ELBO().loss(random.PRNGKey(0), params, self.model, self, *args, **kwargs)\n\n self._loss_fn = loss_fn\n\n def _get_posterior(self, *args, **kwargs):\n # sample from Delta guide\n loc = numpyro.param('{}_loc'.format(self.prefix), self._init_latent)\n return dist.Delta(loc, event_dim=1)\n\n def get_base_dist(self):\n return dist.Normal(jnp.zeros(self.latent_dim), 1).to_event(1)\n\n def get_transform(self, params):\n def loss_fn(z):\n params1 = params.copy()\n params1['{}_loc'.format(self.prefix)] = z\n return self._loss_fn(params1)\n\n loc = params['{}_loc'.format(self.prefix)]\n precision = hessian(loss_fn)(loc)\n scale_tril = cholesky_of_inverse(precision)\n if not_jax_tracer(scale_tril):\n if jnp.any(jnp.isnan(scale_tril)):\n warnings.warn(\"Hessian of log posterior at the MAP point is singular. Posterior\"\n \" samples from AutoLaplaceApproxmiation will be constant (equal to\"\n \" the MAP point).\")\n scale_tril = jnp.where(jnp.isnan(scale_tril), 0., scale_tril)\n return LowerCholeskyAffine(loc, scale_tril)\n\n def get_posterior(self, params):\n \"\"\"\n Returns a multivariate Normal posterior distribution.\n \"\"\"\n transform = self.get_transform(params)\n return dist.MultivariateNormal(transform.loc, scale_tril=transform.scale_tril)\n\n def sample_posterior(self, rng_key, params, sample_shape=()):\n latent_sample = self.get_posterior(params).sample(rng_key, sample_shape)\n return self._unpack_and_constrain(latent_sample, params)\n\n def median(self, params):\n loc = params['{}_loc'.format(self.prefix)]\n return self._unpack_and_constrain(loc, params)\n\n def quantiles(self, params, quantiles):\n transform = self.get_transform(params)\n quantiles = jnp.array(quantiles)[..., None]\n latent = dist.Normal(transform.loc, jnp.diagonal(transform.scale_tril)).icdf(quantiles)\n return self._unpack_and_constrain(latent, params)\n\n\nclass AutoIAFNormal(AutoContinuous):\n \"\"\"\n This implementation of :class:`AutoContinuous` uses a Diagonal Normal\n distribution transformed via a\n :class:`~numpyro.distributions.flows.InverseAutoregressiveTransform`\n to construct a guide over the entire latent space. The guide does not\n depend on the model's ``*args, **kwargs``.\n\n Usage::\n\n guide = AutoIAFNormal(model, hidden_dims=[20], skip_connections=True, ...)\n svi = SVI(model, guide, ...)\n\n :param callable model: a generative model.\n :param str prefix: a prefix that will be prefixed to all param internal sites.\n :param callable init_strategy: A per-site initialization function.\n :param int num_flows: the number of flows to be used, defaults to 3.\n :param list hidden_dims: the dimensionality of the hidden units per layer.\n Defaults to ``[latent_dim, latent_dim]``.\n :param bool skip_connections: whether to add skip connections from the input to the\n output of each flow. Defaults to False.\n :param callable nonlinearity: the nonlinearity to use in the feedforward network.\n Defaults to :func:`jax.experimental.stax.Elu`.\n \"\"\"\n def __init__(self, model, *, prefix=\"auto\", init_strategy=init_to_uniform,\n num_flows=3, hidden_dims=None, skip_connections=False, nonlinearity=stax.Elu):\n self.num_flows = num_flows\n # 2-layer, stax.Elu, skip_connections=False by default following the experiments in\n # IAF paper (https://arxiv.org/abs/1606.04934)\n # and Neutra paper (https://arxiv.org/abs/1903.03704)\n self._hidden_dims = hidden_dims\n self._skip_connections = skip_connections\n self._nonlinearity = nonlinearity\n super(AutoIAFNormal, self).__init__(model, prefix=prefix, init_strategy=init_strategy)\n\n def _get_posterior(self):\n if self.latent_dim == 1:\n raise ValueError('latent dim = 1. Consider using AutoDiagonalNormal instead')\n hidden_dims = [self.latent_dim, self.latent_dim] if self._hidden_dims is None else self._hidden_dims\n flows = []\n for i in range(self.num_flows):\n if i > 0:\n flows.append(PermuteTransform(jnp.arange(self.latent_dim)[::-1]))\n arn = AutoregressiveNN(self.latent_dim, hidden_dims,\n permutation=jnp.arange(self.latent_dim),\n skip_connections=self._skip_connections,\n nonlinearity=self._nonlinearity)\n arnn = numpyro.module('{}_arn__{}'.format(self.prefix, i), arn, (self.latent_dim,))\n flows.append(InverseAutoregressiveTransform(arnn))\n return dist.TransformedDistribution(self.get_base_dist(), flows)\n\n def get_base_dist(self):\n return dist.Normal(jnp.zeros(self.latent_dim), 1).to_event(1)\n\n\nclass AutoBNAFNormal(AutoContinuous):\n \"\"\"\n This implementation of :class:`AutoContinuous` uses a Diagonal Normal\n distribution transformed via a\n :class:`~numpyro.distributions.flows.BlockNeuralAutoregressiveTransform`\n to construct a guide over the entire latent space. The guide does not\n depend on the model's ``*args, **kwargs``.\n\n Usage::\n\n guide = AutoBNAFNormal(model, num_flows=1, hidden_factors=[50, 50], ...)\n svi = SVI(model, guide, ...)\n\n **References**\n\n 1. *Block Neural Autoregressive Flow*,\n Nicola De Cao, Ivan Titov, Wilker Aziz\n\n :param callable model: a generative model.\n :param str prefix: a prefix that will be prefixed to all param internal sites.\n :param callable init_strategy: A per-site initialization function.\n :param int num_flows: the number of flows to be used, defaults to 3.\n :param list hidden_factors: Hidden layer i has ``hidden_factors[i]`` hidden units per\n input dimension. This corresponds to both :math:`a` and :math:`b` in reference [1].\n The elements of hidden_factors must be integers.\n \"\"\"\n def __init__(self, model, *, prefix=\"auto\", init_strategy=init_to_uniform, num_flows=1,\n hidden_factors=[8, 8]):\n self.num_flows = num_flows\n self._hidden_factors = hidden_factors\n super(AutoBNAFNormal, self).__init__(model, prefix=prefix, init_strategy=init_strategy)\n\n def _get_posterior(self):\n if self.latent_dim == 1:\n raise ValueError('latent dim = 1. Consider using AutoDiagonalNormal instead')\n flows = []\n for i in range(self.num_flows):\n if i > 0:\n flows.append(PermuteTransform(jnp.arange(self.latent_dim)[::-1]))\n residual = \"gated\" if i < (self.num_flows - 1) else None\n arn = BlockNeuralAutoregressiveNN(self.latent_dim, self._hidden_factors, residual)\n arnn = numpyro.module('{}_arn__{}'.format(self.prefix, i), arn, (self.latent_dim,))\n flows.append(BlockNeuralAutoregressiveTransform(arnn))\n return dist.TransformedDistribution(self.get_base_dist(), flows)\n\n def get_base_dist(self):\n return dist.Normal(jnp.zeros(self.latent_dim), 1).to_event(1)\n", "path": "numpyro/infer/autoguide.py" } ]
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)) + + [email protected]("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 (Soumith Chintala)\n# Copyright (c) 2011-2014 Idiap Research Institute (Ronan Collobert)\n# Copyright (c) 2012-2014 Deepmind Technologies (Koray Kavukcuoglu)\n# Copyright (c) 2011-2012 NEC Laboratories America (Koray Kavukcuoglu)\n# Copyright (c) 2011-2013 NYU (Clement Farabet)\n# Copyright (c) 2006-2010 NEC Laboratories America (Ronan Collobert, Leon Bottou, Iain Melvin, Jason Weston)\n# Copyright (c) 2006 Idiap Research Institute (Samy Bengio)\n# Copyright (c) 2001-2004 Idiap Research Institute (Ronan Collobert, Samy Bengio, Johnny Mariethoz)\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\nimport numpy as np\n\nfrom jax import lax, vmap\nfrom jax.experimental.sparse import BCOO\nfrom jax.lax import scan\nimport jax.nn as nn\nimport jax.numpy as jnp\nimport jax.random as random\nfrom jax.scipy.linalg import cho_solve, solve_triangular\nfrom jax.scipy.special import (\n betaln,\n expi,\n expit,\n gammainc,\n gammaln,\n logit,\n multigammaln,\n ndtr,\n ndtri,\n xlog1py,\n xlogy,\n)\n\nfrom numpyro.distributions import constraints\nfrom numpyro.distributions.discrete import _to_logits_bernoulli\nfrom numpyro.distributions.distribution import Distribution, TransformedDistribution\nfrom numpyro.distributions.transforms import (\n AffineTransform,\n CorrMatrixCholeskyTransform,\n ExpTransform,\n PowerTransform,\n SigmoidTransform,\n)\nfrom numpyro.distributions.util import (\n betainc,\n betaincinv,\n cholesky_of_inverse,\n gammaincinv,\n is_prng_key,\n lazy_property,\n matrix_to_tril_vec,\n promote_shapes,\n signed_stick_breaking_tril,\n validate_sample,\n vec_to_tril_matrix,\n)\n\n\nclass AsymmetricLaplace(Distribution):\n arg_constraints = {\n \"loc\": constraints.real,\n \"scale\": constraints.positive,\n \"asymmetry\": constraints.positive,\n }\n reparametrized_params = [\"loc\", \"scale\", \"asymmetry\"]\n support = constraints.real\n\n def __init__(self, loc=0.0, scale=1.0, asymmetry=1.0, *, validate_args=None):\n batch_shape = lax.broadcast_shapes(\n jnp.shape(loc), jnp.shape(scale), jnp.shape(asymmetry)\n )\n self.loc, self.scale, self.asymmetry = promote_shapes(\n loc, scale, asymmetry, shape=batch_shape\n )\n super(AsymmetricLaplace, self).__init__(\n batch_shape=batch_shape, validate_args=validate_args\n )\n\n @lazy_property\n def left_scale(self):\n return self.scale * self.asymmetry\n\n @lazy_property\n def right_scale(self):\n return self.scale / self.asymmetry\n\n def log_prob(self, value):\n if self._validate_args:\n self._validate_sample(value)\n z = value - self.loc\n z = -jnp.abs(z) / jnp.where(z < 0, self.left_scale, self.right_scale)\n return z - jnp.log(self.left_scale + self.right_scale)\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n shape = (2,) + sample_shape + self.batch_shape + self.event_shape\n u, v = random.exponential(key, shape=shape)\n return self.loc - self.left_scale * u + self.right_scale * v\n\n @property\n def mean(self):\n total_scale = self.left_scale + self.right_scale\n mean = self.loc + (self.right_scale**2 - self.left_scale**2) / total_scale\n return jnp.broadcast_to(mean, self.batch_shape)\n\n @property\n def variance(self):\n left = self.left_scale\n right = self.right_scale\n total = left + right\n p = left / total\n q = right / total\n variance = p * left**2 + q * right**2 + p * q * total**2\n return jnp.broadcast_to(variance, self.batch_shape)\n\n def cdf(self, value):\n z = value - self.loc\n k = self.asymmetry\n return jnp.where(\n z >= 0,\n 1 - (1 / (1 + k**2)) * jnp.exp(-jnp.abs(z) / self.right_scale),\n k**2 / (1 + k**2) * jnp.exp(-jnp.abs(z) / self.left_scale),\n )\n\n def icdf(self, value):\n k = self.asymmetry\n temp = k**2 / (1 + k**2)\n return jnp.where(\n value <= temp,\n self.loc + self.left_scale * jnp.log(value / temp),\n self.loc - self.right_scale * jnp.log((1 + k**2) * (1 - value)),\n )\n\n\nclass Beta(Distribution):\n arg_constraints = {\n \"concentration1\": constraints.positive,\n \"concentration0\": constraints.positive,\n }\n reparametrized_params = [\"concentration1\", \"concentration0\"]\n support = constraints.unit_interval\n\n def __init__(self, concentration1, concentration0, *, validate_args=None):\n self.concentration1, self.concentration0 = promote_shapes(\n concentration1, concentration0\n )\n batch_shape = lax.broadcast_shapes(\n jnp.shape(concentration1), jnp.shape(concentration0)\n )\n concentration1 = jnp.broadcast_to(concentration1, batch_shape)\n concentration0 = jnp.broadcast_to(concentration0, batch_shape)\n super(Beta, self).__init__(batch_shape=batch_shape, validate_args=validate_args)\n self._dirichlet = Dirichlet(\n jnp.stack([concentration1, concentration0], axis=-1)\n )\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n return self._dirichlet.sample(key, sample_shape)[..., 0]\n\n @validate_sample\n def log_prob(self, value):\n return self._dirichlet.log_prob(jnp.stack([value, 1.0 - value], -1))\n\n @property\n def mean(self):\n return self.concentration1 / (self.concentration1 + self.concentration0)\n\n @property\n def variance(self):\n total = self.concentration1 + self.concentration0\n return self.concentration1 * self.concentration0 / (total**2 * (total + 1))\n\n def cdf(self, value):\n return betainc(self.concentration1, self.concentration0, value)\n\n def icdf(self, q):\n return betaincinv(self.concentration1, self.concentration0, q)\n\n\nclass Cauchy(Distribution):\n arg_constraints = {\"loc\": constraints.real, \"scale\": constraints.positive}\n support = constraints.real\n reparametrized_params = [\"loc\", \"scale\"]\n\n def __init__(self, loc=0.0, scale=1.0, *, validate_args=None):\n self.loc, self.scale = promote_shapes(loc, scale)\n batch_shape = lax.broadcast_shapes(jnp.shape(loc), jnp.shape(scale))\n super(Cauchy, self).__init__(\n batch_shape=batch_shape, validate_args=validate_args\n )\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n eps = random.cauchy(key, shape=sample_shape + self.batch_shape)\n return self.loc + eps * self.scale\n\n @validate_sample\n def log_prob(self, value):\n return (\n -jnp.log(jnp.pi)\n - jnp.log(self.scale)\n - jnp.log1p(((value - self.loc) / self.scale) ** 2)\n )\n\n @property\n def mean(self):\n return jnp.full(self.batch_shape, jnp.nan)\n\n @property\n def variance(self):\n return jnp.full(self.batch_shape, jnp.nan)\n\n def cdf(self, value):\n scaled = (value - self.loc) / self.scale\n return jnp.arctan(scaled) / jnp.pi + 0.5\n\n def icdf(self, q):\n return self.loc + self.scale * jnp.tan(jnp.pi * (q - 0.5))\n\n\nclass Dirichlet(Distribution):\n arg_constraints = {\n \"concentration\": constraints.independent(constraints.positive, 1)\n }\n reparametrized_params = [\"concentration\"]\n support = constraints.simplex\n\n def __init__(self, concentration, *, validate_args=None):\n if jnp.ndim(concentration) < 1:\n raise ValueError(\n \"`concentration` parameter must be at least one-dimensional.\"\n )\n self.concentration = concentration\n batch_shape, event_shape = concentration.shape[:-1], concentration.shape[-1:]\n super(Dirichlet, self).__init__(\n batch_shape=batch_shape,\n event_shape=event_shape,\n validate_args=validate_args,\n )\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n shape = sample_shape + self.batch_shape\n samples = random.dirichlet(key, self.concentration, shape=shape)\n return jnp.clip(\n samples, a_min=jnp.finfo(samples).tiny, a_max=1 - jnp.finfo(samples).eps\n )\n\n @validate_sample\n def log_prob(self, value):\n normalize_term = jnp.sum(gammaln(self.concentration), axis=-1) - gammaln(\n jnp.sum(self.concentration, axis=-1)\n )\n return (\n jnp.sum(jnp.log(value) * (self.concentration - 1.0), axis=-1)\n - normalize_term\n )\n\n @property\n def mean(self):\n return self.concentration / jnp.sum(self.concentration, axis=-1, keepdims=True)\n\n @property\n def variance(self):\n con0 = jnp.sum(self.concentration, axis=-1, keepdims=True)\n return (\n self.concentration * (con0 - self.concentration) / (con0**2 * (con0 + 1))\n )\n\n @staticmethod\n def infer_shapes(concentration):\n batch_shape = concentration[:-1]\n event_shape = concentration[-1:]\n return batch_shape, event_shape\n\n\nclass EulerMaruyama(Distribution):\n \"\"\"\n Euler–Maruyama method is a method for the approximate numerical solution\n of a stochastic differential equation (SDE)\n\n :param ndarray t: discretized time\n :param callable sde_fn: function returning the drift and diffusion coefficients of SDE\n :param Distribution init_dist: Distribution for initial values.\n\n **References**\n\n [1] https://en.wikipedia.org/wiki/Euler-Maruyama_method\n \"\"\"\n\n arg_constraints = {\"t\": constraints.ordered_vector}\n\n def __init__(self, t, sde_fn, init_dist, *, validate_args=None):\n self.t = t\n self.sde_fn = sde_fn\n self.init_dist = init_dist\n\n if not isinstance(init_dist, Distribution):\n raise TypeError(\"Init distribution is expected to be Distribution class.\")\n\n batch_shape_t = jnp.shape(t)[:-1]\n batch_shape = lax.broadcast_shapes(batch_shape_t, init_dist.batch_shape)\n event_shape = (jnp.shape(t)[-1],) + init_dist.event_shape\n\n super(EulerMaruyama, self).__init__(\n batch_shape, event_shape, validate_args=validate_args\n )\n\n @constraints.dependent_property(is_discrete=False)\n def support(self):\n return constraints.independent(constraints.real, self.event_dim)\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n batch_shape = sample_shape + self.batch_shape\n\n def step(y_curr, xs):\n noise_curr, t_curr, dt_curr = xs\n f, g = self.sde_fn(y_curr, t_curr)\n mu = y_curr + dt_curr * f\n sigma = jnp.sqrt(dt_curr) * g\n y_next = mu + sigma * noise_curr\n return y_next, y_next\n\n rng_noise, rng_init = random.split(key)\n noises = random.normal(\n rng_noise,\n shape=batch_shape + (self.event_shape[0] - 1,) + self.event_shape[1:],\n )\n inits = self.init_dist.expand(batch_shape).sample(rng_init)\n\n def scan_fn(init, noise, tm1, dt):\n return scan(step, init, (noise, tm1, dt))\n\n batch_dim = len(batch_shape)\n if batch_dim:\n inits = inits.reshape((-1,) + inits.shape[batch_dim:])\n noises = noises.reshape((-1,) + noises.shape[batch_dim:])\n t = jnp.broadcast_to(self.t, batch_shape + (self.event_shape[0],))\n t = t.reshape((-1,) + t.shape[batch_dim:])\n dt = jnp.diff(t, axis=-1)\n _, sde_out = vmap(scan_fn)(inits, noises, t[..., :-1], dt)\n sde_out = jnp.concatenate([inits[:, None], sde_out], axis=1)\n sde_out = jnp.reshape(sde_out, batch_shape + self.event_shape)\n else:\n dt = jnp.diff(self.t, axis=-1)\n _, sde_out = scan_fn(inits, noises, self.t[:-1], dt)\n sde_out = jnp.concatenate([inits[None], sde_out], axis=0)\n\n return sde_out\n\n @validate_sample\n def log_prob(self, value):\n sample_shape = lax.broadcast_shapes(\n value.shape[: -self.event_dim], self.batch_shape\n )\n value = jnp.broadcast_to(value, sample_shape + self.event_shape)\n\n if sample_shape:\n reshaped_value = value.reshape((-1,) + self.event_shape)\n xtm1, xt = reshaped_value[:, :-1], reshaped_value[:, 1:]\n value0 = reshaped_value[:, 0]\n t = jnp.broadcast_to(self.t, sample_shape + (self.event_shape[0],))\n t = t.reshape((-1,) + (self.event_shape[0],))\n\n f, g = vmap(vmap(self.sde_fn))(xtm1, t[:, :-1])\n\n f = f.reshape(sample_shape + f.shape[1:])\n g = g.reshape(sample_shape + g.shape[1:])\n xtm1 = xtm1.reshape(sample_shape + xtm1.shape[1:])\n xt = xt.reshape(sample_shape + xt.shape[1:])\n value0 = value0.reshape(sample_shape + value0.shape[1:])\n\n else:\n xtm1, xt = value[:-1], value[1:]\n value0 = value[0]\n\n f, g = vmap(self.sde_fn)(xtm1, self.t[:-1])\n\n # add missing event dimensions\n batch_dim = len(sample_shape)\n f = f.reshape(\n f.shape[: batch_dim + 1]\n + (1,) * (xt.ndim - f.ndim)\n + f.shape[batch_dim + 1 :]\n )\n g = g.reshape(\n g.shape[: batch_dim + 1]\n + (1,) * (xt.ndim - g.ndim)\n + g.shape[batch_dim + 1 :]\n )\n\n dt = jnp.diff(self.t, axis=-1)\n dt = dt.reshape(dt.shape + (1,) * (self.event_dim - 1))\n mu = xtm1 + dt * f\n sigma = jnp.sqrt(dt) * g\n\n sde_log_prob = Normal(mu, sigma).to_event(self.event_dim).log_prob(xt)\n init_log_prob = self.init_dist.log_prob(value0)\n\n return sde_log_prob + init_log_prob\n\n\nclass Exponential(Distribution):\n reparametrized_params = [\"rate\"]\n arg_constraints = {\"rate\": constraints.positive}\n support = constraints.positive\n\n def __init__(self, rate=1.0, *, validate_args=None):\n self.rate = rate\n super(Exponential, self).__init__(\n batch_shape=jnp.shape(rate), validate_args=validate_args\n )\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n return (\n random.exponential(key, shape=sample_shape + self.batch_shape) / self.rate\n )\n\n @validate_sample\n def log_prob(self, value):\n return jnp.log(self.rate) - self.rate * value\n\n @property\n def mean(self):\n return jnp.reciprocal(self.rate)\n\n @property\n def variance(self):\n return jnp.reciprocal(self.rate**2)\n\n def cdf(self, value):\n return -jnp.expm1(-self.rate * value)\n\n def icdf(self, q):\n return -jnp.log1p(-q) / self.rate\n\n\nclass Gamma(Distribution):\n arg_constraints = {\n \"concentration\": constraints.positive,\n \"rate\": constraints.positive,\n }\n support = constraints.positive\n reparametrized_params = [\"concentration\", \"rate\"]\n\n def __init__(self, concentration, rate=1.0, *, validate_args=None):\n self.concentration, self.rate = promote_shapes(concentration, rate)\n batch_shape = lax.broadcast_shapes(jnp.shape(concentration), jnp.shape(rate))\n super(Gamma, self).__init__(\n batch_shape=batch_shape, validate_args=validate_args\n )\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n shape = sample_shape + self.batch_shape + self.event_shape\n return random.gamma(key, self.concentration, shape=shape) / self.rate\n\n @validate_sample\n def log_prob(self, value):\n normalize_term = gammaln(self.concentration) - self.concentration * jnp.log(\n self.rate\n )\n return (\n (self.concentration - 1) * jnp.log(value)\n - self.rate * value\n - normalize_term\n )\n\n @property\n def mean(self):\n return self.concentration / self.rate\n\n @property\n def variance(self):\n return self.concentration / jnp.power(self.rate, 2)\n\n def cdf(self, x):\n return gammainc(self.concentration, self.rate * x)\n\n def icdf(self, q):\n return gammaincinv(self.concentration, q) / self.rate\n\n\nclass Chi2(Gamma):\n arg_constraints = {\"df\": constraints.positive}\n reparametrized_params = [\"df\"]\n\n def __init__(self, df, *, validate_args=None):\n self.df = df\n super(Chi2, self).__init__(0.5 * df, 0.5, validate_args=validate_args)\n\n\nclass GaussianRandomWalk(Distribution):\n arg_constraints = {\"scale\": constraints.positive}\n support = constraints.real_vector\n reparametrized_params = [\"scale\"]\n\n def __init__(self, scale=1.0, num_steps=1, *, validate_args=None):\n assert (\n isinstance(num_steps, int) and num_steps > 0\n ), \"`num_steps` argument should be an positive integer.\"\n self.scale = scale\n self.num_steps = num_steps\n batch_shape, event_shape = jnp.shape(scale), (num_steps,)\n super(GaussianRandomWalk, self).__init__(\n batch_shape, event_shape, validate_args=validate_args\n )\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n shape = sample_shape + self.batch_shape + self.event_shape\n walks = random.normal(key, shape=shape)\n return jnp.cumsum(walks, axis=-1) * jnp.expand_dims(self.scale, axis=-1)\n\n @validate_sample\n def log_prob(self, value):\n init_prob = Normal(0.0, self.scale).log_prob(value[..., 0])\n scale = jnp.expand_dims(self.scale, -1)\n step_probs = Normal(value[..., :-1], scale).log_prob(value[..., 1:])\n return init_prob + jnp.sum(step_probs, axis=-1)\n\n @property\n def mean(self):\n return jnp.zeros(self.batch_shape + self.event_shape)\n\n @property\n def variance(self):\n return jnp.broadcast_to(\n jnp.expand_dims(self.scale, -1) ** 2 * jnp.arange(1, self.num_steps + 1),\n self.batch_shape + self.event_shape,\n )\n\n def tree_flatten(self):\n return (self.scale,), self.num_steps\n\n @classmethod\n def tree_unflatten(cls, aux_data, params):\n return cls(*params, num_steps=aux_data)\n\n\nclass HalfCauchy(Distribution):\n reparametrized_params = [\"scale\"]\n support = constraints.positive\n arg_constraints = {\"scale\": constraints.positive}\n\n def __init__(self, scale=1.0, *, validate_args=None):\n self._cauchy = Cauchy(0.0, scale)\n self.scale = scale\n super(HalfCauchy, self).__init__(\n batch_shape=jnp.shape(scale), validate_args=validate_args\n )\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n return jnp.abs(self._cauchy.sample(key, sample_shape))\n\n @validate_sample\n def log_prob(self, value):\n return self._cauchy.log_prob(value) + jnp.log(2)\n\n def cdf(self, value):\n return self._cauchy.cdf(value) * 2 - 1\n\n def icdf(self, q):\n return self._cauchy.icdf((q + 1) / 2)\n\n @property\n def mean(self):\n return jnp.full(self.batch_shape, jnp.inf)\n\n @property\n def variance(self):\n return jnp.full(self.batch_shape, jnp.inf)\n\n\nclass HalfNormal(Distribution):\n reparametrized_params = [\"scale\"]\n support = constraints.positive\n arg_constraints = {\"scale\": constraints.positive}\n\n def __init__(self, scale=1.0, *, validate_args=None):\n self._normal = Normal(0.0, scale)\n self.scale = scale\n super(HalfNormal, self).__init__(\n batch_shape=jnp.shape(scale), validate_args=validate_args\n )\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n return jnp.abs(self._normal.sample(key, sample_shape))\n\n @validate_sample\n def log_prob(self, value):\n return self._normal.log_prob(value) + jnp.log(2)\n\n def cdf(self, value):\n return self._normal.cdf(value) * 2 - 1\n\n def icdf(self, q):\n return self._normal.icdf((q + 1) / 2)\n\n @property\n def mean(self):\n return jnp.sqrt(2 / jnp.pi) * self.scale\n\n @property\n def variance(self):\n return (1 - 2 / jnp.pi) * self.scale**2\n\n\nclass InverseGamma(TransformedDistribution):\n \"\"\"\n .. note:: We keep the same notation `rate` as in Pyro but\n it plays the role of scale parameter of InverseGamma in literatures\n (e.g. wikipedia: https://en.wikipedia.org/wiki/Inverse-gamma_distribution)\n \"\"\"\n\n arg_constraints = {\n \"concentration\": constraints.positive,\n \"rate\": constraints.positive,\n }\n reparametrized_params = [\"concentration\", \"rate\"]\n support = constraints.positive\n\n def __init__(self, concentration, rate=1.0, *, validate_args=None):\n base_dist = Gamma(concentration, rate)\n self.concentration = base_dist.concentration\n self.rate = base_dist.rate\n super(InverseGamma, self).__init__(\n base_dist, PowerTransform(-1.0), validate_args=validate_args\n )\n\n @property\n def mean(self):\n # mean is inf for alpha <= 1\n a = self.rate / (self.concentration - 1)\n return jnp.where(self.concentration <= 1, jnp.inf, a)\n\n @property\n def variance(self):\n # var is inf for alpha <= 2\n a = (self.rate / (self.concentration - 1)) ** 2 / (self.concentration - 2)\n return jnp.where(self.concentration <= 2, jnp.inf, a)\n\n def tree_flatten(self):\n return super(TransformedDistribution, self).tree_flatten()\n\n def cdf(self, x):\n return 1 - self.base_dist.cdf(1 / x)\n\n\nclass Gompertz(Distribution):\n r\"\"\"Gompertz Distribution.\n\n The Gompertz distribution is a distribution with support on the positive real line that is closely\n related to the Gumbel distribution. This implementation follows the notation used in the Wikipedia\n entry for the Gompertz distribution. See https://en.wikipedia.org/wiki/Gompertz_distribution.\n\n However, we call the parameter \"eta\" a concentration parameter and the parameter\n \"b\" a rate parameter (as opposed to scale parameter as in wikipedia description.)\n\n The CDF, in terms of `concentration` (`con`) and `rate`, is\n\n .. math::\n F(x) = 1 - \\exp \\left\\{ - \\text{con} * \\left [ \\exp\\{x * rate \\} - 1 \\right ] \\right\\}\n \"\"\"\n\n arg_constraints = {\n \"concentration\": constraints.positive,\n \"rate\": constraints.positive,\n }\n support = constraints.positive\n reparametrized_params = [\"concentration\", \"rate\"]\n\n def __init__(self, concentration, rate=1.0, *, validate_args=None):\n self.concentration, self.rate = promote_shapes(concentration, rate)\n super(Gompertz, self).__init__(\n batch_shape=lax.broadcast_shapes(jnp.shape(concentration), jnp.shape(rate)),\n validate_args=validate_args,\n )\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n random_shape = sample_shape + self.batch_shape + self.event_shape\n unifs = random.uniform(key, shape=random_shape)\n return self.icdf(unifs)\n\n @validate_sample\n def log_prob(self, value):\n scaled_value = value * self.rate\n return (\n jnp.log(self.concentration)\n + jnp.log(self.rate)\n + scaled_value\n - self.concentration * jnp.expm1(scaled_value)\n )\n\n def cdf(self, value):\n return -jnp.expm1(-self.concentration * jnp.expm1(value * self.rate))\n\n def icdf(self, q):\n return jnp.log1p(-jnp.log1p(-q) / self.concentration) / self.rate\n\n @property\n def mean(self):\n return -jnp.exp(self.concentration) * expi(-self.concentration) / self.rate\n\n\nclass Gumbel(Distribution):\n arg_constraints = {\"loc\": constraints.real, \"scale\": constraints.positive}\n support = constraints.real\n reparametrized_params = [\"loc\", \"scale\"]\n\n def __init__(self, loc=0.0, scale=1.0, *, validate_args=None):\n self.loc, self.scale = promote_shapes(loc, scale)\n batch_shape = lax.broadcast_shapes(jnp.shape(loc), jnp.shape(scale))\n\n super(Gumbel, self).__init__(\n batch_shape=batch_shape, validate_args=validate_args\n )\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n standard_gumbel_sample = random.gumbel(\n key, shape=sample_shape + self.batch_shape + self.event_shape\n )\n return self.loc + self.scale * standard_gumbel_sample\n\n @validate_sample\n def log_prob(self, value):\n z = (value - self.loc) / self.scale\n return -(z + jnp.exp(-z)) - jnp.log(self.scale)\n\n @property\n def mean(self):\n return jnp.broadcast_to(\n self.loc + self.scale * jnp.euler_gamma, self.batch_shape\n )\n\n @property\n def variance(self):\n return jnp.broadcast_to(jnp.pi**2 / 6.0 * self.scale**2, self.batch_shape)\n\n def cdf(self, value):\n return jnp.exp(-jnp.exp((self.loc - value) / self.scale))\n\n def icdf(self, q):\n return self.loc - self.scale * jnp.log(-jnp.log(q))\n\n\nclass Kumaraswamy(TransformedDistribution):\n arg_constraints = {\n \"concentration1\": constraints.positive,\n \"concentration0\": constraints.positive,\n }\n reparametrized_params = [\"concentration1\", \"concentration0\"]\n support = constraints.unit_interval\n # XXX: This flag is used to approximate the Taylor expansion\n # of KL(Kumaraswamy||Beta) following\n # https://arxiv.org/abs/1605.06197 Formula (12)\n # We follow the paper and set this to 10 but to get more precise KL,\n # we can set this flag to 1000.\n KL_KUMARASWAMY_BETA_TAYLOR_ORDER = 10\n\n def __init__(self, concentration1, concentration0, *, validate_args=None):\n self.concentration1, self.concentration0 = promote_shapes(\n concentration1, concentration0\n )\n batch_shape = lax.broadcast_shapes(\n jnp.shape(concentration1), jnp.shape(concentration0)\n )\n base_dist = Uniform(0, 1).expand(batch_shape)\n transforms = [\n PowerTransform(1 / concentration0),\n AffineTransform(1, -1),\n PowerTransform(1 / concentration1),\n ]\n super().__init__(base_dist, transforms, validate_args=validate_args)\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n minval = jnp.finfo(jnp.result_type(float)).tiny\n u = random.uniform(key, shape=sample_shape + self.batch_shape, minval=minval)\n log_sample = jnp.log1p(-(u ** (1 / self.concentration0))) / self.concentration1\n finfo = jnp.finfo(u)\n return jnp.clip(jnp.exp(log_sample), a_min=finfo.tiny, a_max=1 - finfo.eps)\n\n @validate_sample\n def log_prob(self, value):\n normalize_term = jnp.log(self.concentration0) + jnp.log(self.concentration1)\n return (\n xlogy(self.concentration1 - 1, value)\n + xlog1py(self.concentration0 - 1, -(value**self.concentration1))\n + normalize_term\n )\n\n @property\n def mean(self):\n log_beta = betaln(1 + 1 / self.concentration1, self.concentration0)\n return self.concentration0 * jnp.exp(log_beta)\n\n @property\n def variance(self):\n log_beta = betaln(1 + 2 / self.concentration1, self.concentration0)\n return self.concentration0 * jnp.exp(log_beta) - jnp.square(self.mean)\n\n def tree_flatten(self):\n return super(TransformedDistribution, self).tree_flatten()\n\n\nclass Laplace(Distribution):\n arg_constraints = {\"loc\": constraints.real, \"scale\": constraints.positive}\n support = constraints.real\n reparametrized_params = [\"loc\", \"scale\"]\n\n def __init__(self, loc=0.0, scale=1.0, *, validate_args=None):\n self.loc, self.scale = promote_shapes(loc, scale)\n batch_shape = lax.broadcast_shapes(jnp.shape(loc), jnp.shape(scale))\n super(Laplace, self).__init__(\n batch_shape=batch_shape, validate_args=validate_args\n )\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n eps = random.laplace(\n key, shape=sample_shape + self.batch_shape + self.event_shape\n )\n return self.loc + eps * self.scale\n\n @validate_sample\n def log_prob(self, value):\n normalize_term = jnp.log(2 * self.scale)\n value_scaled = jnp.abs(value - self.loc) / self.scale\n return -value_scaled - normalize_term\n\n @property\n def mean(self):\n return jnp.broadcast_to(self.loc, self.batch_shape)\n\n @property\n def variance(self):\n return jnp.broadcast_to(2 * self.scale**2, self.batch_shape)\n\n def cdf(self, value):\n scaled = (value - self.loc) / self.scale\n return 0.5 - 0.5 * jnp.sign(scaled) * jnp.expm1(-jnp.abs(scaled))\n\n def icdf(self, q):\n a = q - 0.5\n return self.loc - self.scale * jnp.sign(a) * jnp.log1p(-2 * jnp.abs(a))\n\n\nclass LKJ(TransformedDistribution):\n r\"\"\"\n LKJ distribution for correlation matrices. The distribution is controlled by ``concentration``\n parameter :math:`\\eta` to make the probability of the correlation matrix :math:`M` proportional\n to :math:`\\det(M)^{\\eta - 1}`. Because of that, when ``concentration == 1``, we have a\n uniform distribution over correlation matrices.\n\n When ``concentration > 1``, the distribution favors samples with large large determinent. This\n is useful when we know a priori that the underlying variables are not correlated.\n\n When ``concentration < 1``, the distribution favors samples with small determinent. This is\n useful when we know a priori that some underlying variables are correlated.\n\n Sample code for using LKJ in the context of multivariate normal sample::\n\n def model(y): # y has dimension N x d\n d = y.shape[1]\n N = y.shape[0]\n # Vector of variances for each of the d variables\n theta = numpyro.sample(\"theta\", dist.HalfCauchy(jnp.ones(d)))\n\n concentration = jnp.ones(1) # Implies a uniform distribution over correlation matrices\n corr_mat = numpyro.sample(\"corr_mat\", dist.LKJ(d, concentration))\n sigma = jnp.sqrt(theta)\n # we can also use a faster formula `cov_mat = jnp.outer(theta, theta) * corr_mat`\n cov_mat = jnp.matmul(jnp.matmul(jnp.diag(sigma), corr_mat), jnp.diag(sigma))\n\n # Vector of expectations\n mu = jnp.zeros(d)\n\n with numpyro.plate(\"observations\", N):\n obs = numpyro.sample(\"obs\", dist.MultivariateNormal(mu, covariance_matrix=cov_mat), obs=y)\n return obs\n\n :param int dimension: dimension of the matrices\n :param ndarray concentration: concentration/shape parameter of the\n distribution (often referred to as eta)\n :param str sample_method: Either \"cvine\" or \"onion\". Both methods are proposed in [1] and\n offer the same distribution over correlation matrices. But they are different in how\n to generate samples. Defaults to \"onion\".\n\n **References**\n\n [1] `Generating random correlation matrices based on vines and extended onion method`,\n Daniel Lewandowski, Dorota Kurowicka, Harry Joe\n \"\"\"\n arg_constraints = {\"concentration\": constraints.positive}\n reparametrized_params = [\"concentration\"]\n support = constraints.corr_matrix\n\n def __init__(\n self, dimension, concentration=1.0, sample_method=\"onion\", *, validate_args=None\n ):\n base_dist = LKJCholesky(dimension, concentration, sample_method)\n self.dimension, self.concentration = (\n base_dist.dimension,\n base_dist.concentration,\n )\n self.sample_method = sample_method\n super(LKJ, self).__init__(\n base_dist, CorrMatrixCholeskyTransform().inv, validate_args=validate_args\n )\n\n @property\n def mean(self):\n return jnp.broadcast_to(\n jnp.identity(self.dimension),\n self.batch_shape + (self.dimension, self.dimension),\n )\n\n def tree_flatten(self):\n return (self.concentration,), (self.dimension, self.sample_method)\n\n @classmethod\n def tree_unflatten(cls, aux_data, params):\n dimension, sample_method = aux_data\n return cls(dimension, *params, sample_method=sample_method)\n\n\nclass LKJCholesky(Distribution):\n r\"\"\"\n LKJ distribution for lower Cholesky factors of correlation matrices. The distribution is\n controlled by ``concentration`` parameter :math:`\\eta` to make the probability of the\n correlation matrix :math:`M` generated from a Cholesky factor propotional to\n :math:`\\det(M)^{\\eta - 1}`. Because of that, when ``concentration == 1``, we have a\n uniform distribution over Cholesky factors of correlation matrices.\n\n When ``concentration > 1``, the distribution favors samples with large diagonal entries\n (hence large determinent). This is useful when we know a priori that the underlying\n variables are not correlated.\n\n When ``concentration < 1``, the distribution favors samples with small diagonal entries\n (hence small determinent). This is useful when we know a priori that some underlying\n variables are correlated.\n\n Sample code for using LKJCholesky in the context of multivariate normal sample::\n\n def model(y): # y has dimension N x d\n d = y.shape[1]\n N = y.shape[0]\n # Vector of variances for each of the d variables\n theta = numpyro.sample(\"theta\", dist.HalfCauchy(jnp.ones(d)))\n # Lower cholesky factor of a correlation matrix\n concentration = jnp.ones(1) # Implies a uniform distribution over correlation matrices\n L_omega = numpyro.sample(\"L_omega\", dist.LKJCholesky(d, concentration))\n # Lower cholesky factor of the covariance matrix\n sigma = jnp.sqrt(theta)\n # we can also use a faster formula `L_Omega = sigma[..., None] * L_omega`\n L_Omega = jnp.matmul(jnp.diag(sigma), L_omega)\n\n # Vector of expectations\n mu = jnp.zeros(d)\n\n with numpyro.plate(\"observations\", N):\n obs = numpyro.sample(\"obs\", dist.MultivariateNormal(mu, scale_tril=L_Omega), obs=y)\n return obs\n\n :param int dimension: dimension of the matrices\n :param ndarray concentration: concentration/shape parameter of the\n distribution (often referred to as eta)\n :param str sample_method: Either \"cvine\" or \"onion\". Both methods are proposed in [1] and\n offer the same distribution over correlation matrices. But they are different in how\n to generate samples. Defaults to \"onion\".\n\n **References**\n\n [1] `Generating random correlation matrices based on vines and extended onion method`,\n Daniel Lewandowski, Dorota Kurowicka, Harry Joe\n \"\"\"\n arg_constraints = {\"concentration\": constraints.positive}\n reparametrized_params = [\"concentration\"]\n support = constraints.corr_cholesky\n\n def __init__(\n self, dimension, concentration=1.0, sample_method=\"onion\", *, validate_args=None\n ):\n if dimension < 2:\n raise ValueError(\"Dimension must be greater than or equal to 2.\")\n self.dimension = dimension\n self.concentration = concentration\n batch_shape = jnp.shape(concentration)\n event_shape = (dimension, dimension)\n\n # We construct base distributions to generate samples for each method.\n # The purpose of this base distribution is to generate a distribution for\n # correlation matrices which is propotional to `det(M)^{\\eta - 1}`.\n # (note that this is not a unique way to define base distribution)\n # Both of the following methods have marginal distribution of each off-diagonal\n # element of sampled correlation matrices is Beta(eta + (D-2) / 2, eta + (D-2) / 2)\n # (up to a linear transform: x -> 2x - 1)\n Dm1 = self.dimension - 1\n marginal_concentration = concentration + 0.5 * (self.dimension - 2)\n offset = 0.5 * jnp.arange(Dm1)\n if sample_method == \"onion\":\n # The following construction follows from the algorithm in Section 3.2 of [1]:\n # NB: in [1], the method for case k > 1 can also work for the case k = 1.\n beta_concentration0 = (\n jnp.expand_dims(marginal_concentration, axis=-1) - offset\n )\n beta_concentration1 = offset + 0.5\n self._beta = Beta(beta_concentration1, beta_concentration0)\n elif sample_method == \"cvine\":\n # The following construction follows from the algorithm in Section 2.4 of [1]:\n # offset_tril is [0, 1, 1, 2, 2, 2,...] / 2\n offset_tril = matrix_to_tril_vec(jnp.broadcast_to(offset, (Dm1, Dm1)))\n beta_concentration = (\n jnp.expand_dims(marginal_concentration, axis=-1) - offset_tril\n )\n self._beta = Beta(beta_concentration, beta_concentration)\n else:\n raise ValueError(\"`method` should be one of 'cvine' or 'onion'.\")\n self.sample_method = sample_method\n\n super(LKJCholesky, self).__init__(\n batch_shape=batch_shape,\n event_shape=event_shape,\n validate_args=validate_args,\n )\n\n def _cvine(self, key, size):\n # C-vine method first uses beta_dist to generate partial correlations,\n # then apply signed stick breaking to transform to cholesky factor.\n # Here is an attempt to prove that using signed stick breaking to\n # generate correlation matrices is the same as the C-vine method in [1]\n # for the entry r_32.\n #\n # With notations follow from [1], we define\n # p: partial correlation matrix,\n # c: cholesky factor,\n # r: correlation matrix.\n # From recursive formula (2) in [1], we have\n # r_32 = p_32 * sqrt{(1 - p_21^2)*(1 - p_31^2)} + p_21 * p_31 =: I\n # On the other hand, signed stick breaking process gives:\n # l_21 = p_21, l_31 = p_31, l_22 = sqrt(1 - p_21^2), l_32 = p_32 * sqrt(1 - p_31^2)\n # r_32 = l_21 * l_31 + l_22 * l_32\n # = p_21 * p_31 + p_32 * sqrt{(1 - p_21^2)*(1 - p_31^2)} = I\n beta_sample = self._beta.sample(key, size)\n partial_correlation = 2 * beta_sample - 1 # scale to domain to (-1, 1)\n return signed_stick_breaking_tril(partial_correlation)\n\n def _onion(self, key, size):\n key_beta, key_normal = random.split(key)\n # Now we generate w term in Algorithm 3.2 of [1].\n beta_sample = self._beta.sample(key_beta, size)\n # The following Normal distribution is used to create a uniform distribution on\n # a hypershere (ref: http://mathworld.wolfram.com/HyperspherePointPicking.html)\n normal_sample = random.normal(\n key_normal,\n shape=size\n + self.batch_shape\n + (self.dimension * (self.dimension - 1) // 2,),\n )\n normal_sample = vec_to_tril_matrix(normal_sample, diagonal=0)\n u_hypershere = normal_sample / jnp.linalg.norm(\n normal_sample, axis=-1, keepdims=True\n )\n w = jnp.expand_dims(jnp.sqrt(beta_sample), axis=-1) * u_hypershere\n\n # put w into the off-diagonal triangular part\n cholesky = jnp.zeros(size + self.batch_shape + self.event_shape)\n cholesky = cholesky.at[..., 1:, :-1].set(w)\n # correct the diagonal\n # NB: beta_sample = sum(w ** 2) because norm 2 of u is 1.\n diag = jnp.ones(cholesky.shape[:-1]).at[..., 1:].set(jnp.sqrt(1 - beta_sample))\n cholesky = cholesky + jnp.expand_dims(diag, axis=-1) * jnp.identity(\n self.dimension\n )\n return cholesky\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n if self.sample_method == \"onion\":\n return self._onion(key, sample_shape)\n else:\n return self._cvine(key, sample_shape)\n\n @validate_sample\n def log_prob(self, value):\n # Note about computing Jacobian of the transformation from Cholesky factor to\n # correlation matrix:\n #\n # Assume C = L@Lt and L = (1 0 0; a \\sqrt(1-a^2) 0; b c \\sqrt(1-b^2-c^2)), we have\n # Then off-diagonal lower triangular vector of L is transformed to the off-diagonal\n # lower triangular vector of C by the transform:\n # (a, b, c) -> (a, b, ab + c\\sqrt(1-a^2))\n # Hence, Jacobian = 1 * 1 * \\sqrt(1 - a^2) = \\sqrt(1 - a^2) = L22, where L22\n # is the 2th diagonal element of L\n # Generally, for a D dimensional matrix, we have:\n # Jacobian = L22^(D-2) * L33^(D-3) * ... * Ldd^0\n #\n # From [1], we know that probability of a correlation matrix is propotional to\n # determinant ** (concentration - 1) = prod(L_ii ^ 2(concentration - 1))\n # On the other hand, Jabobian of the transformation from Cholesky factor to\n # correlation matrix is:\n # prod(L_ii ^ (D - i))\n # So the probability of a Cholesky factor is propotional to\n # prod(L_ii ^ (2 * concentration - 2 + D - i)) =: prod(L_ii ^ order_i)\n # with order_i = 2 * concentration - 2 + D - i,\n # i = 2..D (we omit the element i = 1 because L_11 = 1)\n\n # Compute `order` vector (note that we need to reindex i -> i-2):\n one_to_D = jnp.arange(1, self.dimension)\n order_offset = (3 - self.dimension) + one_to_D\n order = 2 * jnp.expand_dims(self.concentration, axis=-1) - order_offset\n\n # Compute unnormalized log_prob:\n value_diag = jnp.asarray(value)[..., one_to_D, one_to_D]\n unnormalized = jnp.sum(order * jnp.log(value_diag), axis=-1)\n\n # Compute normalization constant (on the first proof of page 1999 of [1])\n Dm1 = self.dimension - 1\n alpha = self.concentration + 0.5 * Dm1\n denominator = gammaln(alpha) * Dm1\n numerator = multigammaln(alpha - 0.5, Dm1)\n # pi_constant in [1] is D * (D - 1) / 4 * log(pi)\n # pi_constant in multigammaln is (D - 1) * (D - 2) / 4 * log(pi)\n # hence, we need to add a pi_constant = (D - 1) * log(pi) / 2\n pi_constant = 0.5 * Dm1 * jnp.log(jnp.pi)\n normalize_term = pi_constant + numerator - denominator\n return unnormalized - normalize_term\n\n def tree_flatten(self):\n return (self.concentration,), (self.dimension, self.sample_method)\n\n @classmethod\n def tree_unflatten(cls, aux_data, params):\n dimension, sample_method = aux_data\n return cls(dimension, *params, sample_method=sample_method)\n\n\nclass LogNormal(TransformedDistribution):\n arg_constraints = {\"loc\": constraints.real, \"scale\": constraints.positive}\n support = constraints.positive\n reparametrized_params = [\"loc\", \"scale\"]\n\n def __init__(self, loc=0.0, scale=1.0, *, validate_args=None):\n base_dist = Normal(loc, scale)\n self.loc, self.scale = base_dist.loc, base_dist.scale\n super(LogNormal, self).__init__(\n base_dist, ExpTransform(), validate_args=validate_args\n )\n\n @property\n def mean(self):\n return jnp.exp(self.loc + self.scale**2 / 2)\n\n @property\n def variance(self):\n return (jnp.exp(self.scale**2) - 1) * jnp.exp(2 * self.loc + self.scale**2)\n\n def tree_flatten(self):\n return super(TransformedDistribution, self).tree_flatten()\n\n def cdf(self, x):\n return self.base_dist.cdf(jnp.log(x))\n\n\nclass Logistic(Distribution):\n arg_constraints = {\"loc\": constraints.real, \"scale\": constraints.positive}\n support = constraints.real\n reparametrized_params = [\"loc\", \"scale\"]\n\n def __init__(self, loc=0.0, scale=1.0, *, validate_args=None):\n self.loc, self.scale = promote_shapes(loc, scale)\n batch_shape = lax.broadcast_shapes(jnp.shape(loc), jnp.shape(scale))\n super(Logistic, self).__init__(batch_shape, validate_args=validate_args)\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n z = random.logistic(\n key, shape=sample_shape + self.batch_shape + self.event_shape\n )\n return self.loc + z * self.scale\n\n @validate_sample\n def log_prob(self, value):\n log_exponent = (self.loc - value) / self.scale\n log_denominator = jnp.log(self.scale) + 2 * nn.softplus(log_exponent)\n return log_exponent - log_denominator\n\n @property\n def mean(self):\n return jnp.broadcast_to(self.loc, self.batch_shape)\n\n @property\n def variance(self):\n var = (self.scale**2) * (jnp.pi**2) / 3\n return jnp.broadcast_to(var, self.batch_shape)\n\n def cdf(self, value):\n scaled = (value - self.loc) / self.scale\n return expit(scaled)\n\n def icdf(self, q):\n return self.loc + self.scale * logit(q)\n\n\nclass LogUniform(TransformedDistribution):\n arg_constraints = {\"low\": constraints.positive, \"high\": constraints.positive}\n reparametrized_params = [\"low\", \"high\"]\n\n def __init__(self, low, high, *, validate_args=None):\n base_dist = Uniform(jnp.log(low), jnp.log(high))\n self.low, self.high = promote_shapes(low, high)\n self._support = constraints.interval(self.low, self.high)\n super(LogUniform, self).__init__(\n base_dist, ExpTransform(), validate_args=validate_args\n )\n\n @constraints.dependent_property(is_discrete=False, event_dim=0)\n def support(self):\n return self._support\n\n @property\n def mean(self):\n return (self.high - self.low) / jnp.log(self.high / self.low)\n\n @property\n def variance(self):\n return (\n 0.5 * (self.high**2 - self.low**2) / jnp.log(self.high / self.low)\n - self.mean**2\n )\n\n def tree_flatten(self):\n return super(TransformedDistribution, self).tree_flatten()\n\n def cdf(self, x):\n return self.base_dist.cdf(jnp.log(x))\n\n\ndef _batch_solve_triangular(A, B):\n \"\"\"\n Extende solve_triangular for the case that B.ndim > A.ndim.\n This is achived by first flattening the leading B.ndim - A.ndim dimensions of B and then\n moving the first dimension to the end.\n\n\n :param jnp.ndarray (...,M,M) A: An array with lower triangular structure in the last two dimensions.\n :param jnp.ndarray (...,M,N) B: Right-hand side matrix in A x = B.\n\n :return: Solution of A x = B.\n \"\"\"\n event_shape = B.shape[-2:]\n batch_shape = lax.broadcast_shapes(A.shape[:-2], B.shape[-A.ndim : -2])\n sample_shape = B.shape[: -A.ndim]\n n, p = event_shape\n\n A = jnp.broadcast_to(A, batch_shape + A.shape[-2:])\n B = jnp.broadcast_to(B, sample_shape + batch_shape + event_shape)\n\n B_flat = jnp.moveaxis(B.reshape((-1,) + batch_shape + event_shape), 0, -2).reshape(\n batch_shape + (n,) + (-1,)\n )\n\n X_flat = solve_triangular(A, B_flat, lower=True)\n\n sample_shape_dim = len(sample_shape)\n src_axes = tuple([-2 - i for i in range(sample_shape_dim)])\n src_axes = src_axes[::-1]\n dest_axes = tuple([i for i in range(sample_shape_dim)])\n\n X = jnp.moveaxis(\n X_flat.reshape(batch_shape + (n,) + sample_shape + (p,)),\n src_axes,\n dest_axes,\n )\n return X\n\n\nclass MatrixNormal(Distribution):\n \"\"\"\n Matrix variate normal distribution as described in [1] but with a lower_triangular parametrization,\n i.e. :math:`U=scale_tril_row @ scale_tril_row^{T}` and :math:`V=scale_tril_column @ scale_tril_column^{T}`.\n The distribution is related to the multivariate normal distribution in the following way.\n If :math:`X ~ MN(loc,U,V)` then :math:`vec(X) ~ MVN(vec(loc), kron(V,U) )`.\n\n :param array_like loc: Location of the distribution.\n :param array_like scale_tril_row: Lower cholesky of rows correlation matrix.\n :param array_like scale_tril_column: Lower cholesky of columns correlation matrix.\n\n **References**\n\n [1] https://en.wikipedia.org/wiki/Matrix_normal_distribution\n \"\"\"\n\n arg_constraints = {\n \"loc\": constraints.real_vector,\n \"scale_tril_row\": constraints.lower_cholesky,\n \"scale_tril_column\": constraints.lower_cholesky,\n }\n support = constraints.real_matrix\n reparametrized_params = [\n \"loc\",\n \"scale_tril_row\",\n \"scale_tril_column\",\n ]\n\n def __init__(self, loc, scale_tril_row, scale_tril_column, validate_args=None):\n event_shape = loc.shape[-2:]\n batch_shape = lax.broadcast_shapes(\n jnp.shape(loc)[:-2],\n jnp.shape(scale_tril_row)[:-2],\n jnp.shape(scale_tril_column)[:-2],\n )\n (self.loc,) = promote_shapes(loc, shape=batch_shape + loc.shape[-2:])\n (self.scale_tril_row,) = promote_shapes(\n scale_tril_row, shape=batch_shape + scale_tril_row.shape[-2:]\n )\n (self.scale_tril_column,) = promote_shapes(\n scale_tril_column, shape=batch_shape + scale_tril_column.shape[-2:]\n )\n super(MatrixNormal, self).__init__(\n batch_shape=batch_shape,\n event_shape=event_shape,\n validate_args=validate_args,\n )\n\n @property\n def mean(self):\n return jnp.broadcast_to(self.loc, self.shape())\n\n def sample(self, key, sample_shape=()):\n eps = random.normal(\n key, shape=sample_shape + self.batch_shape + self.event_shape\n )\n samples = self.loc + self.scale_tril_row @ eps @ jnp.swapaxes(\n self.scale_tril_column, -2, -1\n )\n\n return samples\n\n @validate_sample\n def log_prob(self, values):\n n, p = self.event_shape\n\n row_log_det = jnp.log(\n jnp.diagonal(self.scale_tril_row, axis1=-2, axis2=-1)\n ).sum(-1)\n col_log_det = jnp.log(\n jnp.diagonal(self.scale_tril_column, axis1=-2, axis2=-1)\n ).sum(-1)\n log_det_term = (\n p * row_log_det + n * col_log_det + 0.5 * n * p * jnp.log(2 * jnp.pi)\n )\n\n # compute the trace term\n diff = values - self.loc\n diff_row_solve = _batch_solve_triangular(A=self.scale_tril_row, B=diff)\n diff_col_solve = _batch_solve_triangular(\n A=self.scale_tril_column, B=jnp.swapaxes(diff_row_solve, -2, -1)\n )\n batched_trace_term = jnp.square(\n diff_col_solve.reshape(diff_col_solve.shape[:-2] + (-1,))\n ).sum(-1)\n\n log_prob = -0.5 * batched_trace_term - log_det_term\n\n return log_prob\n\n\ndef _batch_mahalanobis(bL, bx):\n if bL.shape[:-1] == bx.shape:\n # no need to use the below optimization procedure\n solve_bL_bx = solve_triangular(bL, bx[..., None], lower=True).squeeze(-1)\n return jnp.sum(jnp.square(solve_bL_bx), -1)\n\n # NB: The following procedure handles the case: bL.shape = (i, 1, n, n), bx.shape = (i, j, n)\n # because we don't want to broadcast bL to the shape (i, j, n, n).\n\n # Assume that bL.shape = (i, 1, n, n), bx.shape = (..., i, j, n),\n # we are going to make bx have shape (..., 1, j, i, 1, n) to apply batched tril_solve\n sample_ndim = bx.ndim - bL.ndim + 1 # size of sample_shape\n out_shape = jnp.shape(bx)[:-1] # shape of output\n # Reshape bx with the shape (..., 1, i, j, 1, n)\n bx_new_shape = out_shape[:sample_ndim]\n for sL, sx in zip(bL.shape[:-2], out_shape[sample_ndim:]):\n bx_new_shape += (sx // sL, sL)\n bx_new_shape += (-1,)\n bx = jnp.reshape(bx, bx_new_shape)\n # Permute bx to make it have shape (..., 1, j, i, 1, n)\n permute_dims = (\n tuple(range(sample_ndim))\n + tuple(range(sample_ndim, bx.ndim - 1, 2))\n + tuple(range(sample_ndim + 1, bx.ndim - 1, 2))\n + (bx.ndim - 1,)\n )\n bx = jnp.transpose(bx, permute_dims)\n\n # reshape to (-1, i, 1, n)\n xt = jnp.reshape(bx, (-1,) + bL.shape[:-1])\n # permute to (i, 1, n, -1)\n xt = jnp.moveaxis(xt, 0, -1)\n solve_bL_bx = solve_triangular(bL, xt, lower=True) # shape: (i, 1, n, -1)\n M = jnp.sum(solve_bL_bx**2, axis=-2) # shape: (i, 1, -1)\n # permute back to (-1, i, 1)\n M = jnp.moveaxis(M, -1, 0)\n # reshape back to (..., 1, j, i, 1)\n M = jnp.reshape(M, bx.shape[:-1])\n # permute back to (..., 1, i, j, 1)\n permute_inv_dims = tuple(range(sample_ndim))\n for i in range(bL.ndim - 2):\n permute_inv_dims += (sample_ndim + i, len(out_shape) + i)\n M = jnp.transpose(M, permute_inv_dims)\n return jnp.reshape(M, out_shape)\n\n\nclass MultivariateNormal(Distribution):\n arg_constraints = {\n \"loc\": constraints.real_vector,\n \"covariance_matrix\": constraints.positive_definite,\n \"precision_matrix\": constraints.positive_definite,\n \"scale_tril\": constraints.lower_cholesky,\n }\n support = constraints.real_vector\n reparametrized_params = [\n \"loc\",\n \"covariance_matrix\",\n \"precision_matrix\",\n \"scale_tril\",\n ]\n\n def __init__(\n self,\n loc=0.0,\n covariance_matrix=None,\n precision_matrix=None,\n scale_tril=None,\n validate_args=None,\n ):\n if jnp.ndim(loc) == 0:\n (loc,) = promote_shapes(loc, shape=(1,))\n # temporary append a new axis to loc\n loc = loc[..., jnp.newaxis]\n if covariance_matrix is not None:\n loc, self.covariance_matrix = promote_shapes(loc, covariance_matrix)\n self.scale_tril = jnp.linalg.cholesky(self.covariance_matrix)\n elif precision_matrix is not None:\n loc, self.precision_matrix = promote_shapes(loc, precision_matrix)\n self.scale_tril = cholesky_of_inverse(self.precision_matrix)\n elif scale_tril is not None:\n loc, self.scale_tril = promote_shapes(loc, scale_tril)\n else:\n raise ValueError(\n \"One of `covariance_matrix`, `precision_matrix`, `scale_tril`\"\n \" must be specified.\"\n )\n batch_shape = lax.broadcast_shapes(\n jnp.shape(loc)[:-2], jnp.shape(self.scale_tril)[:-2]\n )\n event_shape = jnp.shape(self.scale_tril)[-1:]\n self.loc = loc[..., 0]\n super(MultivariateNormal, self).__init__(\n batch_shape=batch_shape,\n event_shape=event_shape,\n validate_args=validate_args,\n )\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n eps = random.normal(\n key, shape=sample_shape + self.batch_shape + self.event_shape\n )\n return self.loc + jnp.squeeze(\n jnp.matmul(self.scale_tril, eps[..., jnp.newaxis]), axis=-1\n )\n\n @validate_sample\n def log_prob(self, value):\n M = _batch_mahalanobis(self.scale_tril, value - self.loc)\n half_log_det = jnp.log(jnp.diagonal(self.scale_tril, axis1=-2, axis2=-1)).sum(\n -1\n )\n normalize_term = half_log_det + 0.5 * self.scale_tril.shape[-1] * jnp.log(\n 2 * jnp.pi\n )\n return -0.5 * M - normalize_term\n\n @lazy_property\n def covariance_matrix(self):\n return jnp.matmul(self.scale_tril, jnp.swapaxes(self.scale_tril, -1, -2))\n\n @lazy_property\n def precision_matrix(self):\n identity = jnp.broadcast_to(\n jnp.eye(self.scale_tril.shape[-1]), self.scale_tril.shape\n )\n return cho_solve((self.scale_tril, True), identity)\n\n @property\n def mean(self):\n return jnp.broadcast_to(self.loc, self.shape())\n\n @property\n def variance(self):\n return jnp.broadcast_to(\n jnp.sum(self.scale_tril**2, axis=-1), self.batch_shape + self.event_shape\n )\n\n def tree_flatten(self):\n return (self.loc, self.scale_tril), None\n\n @classmethod\n def tree_unflatten(cls, aux_data, params):\n loc, scale_tril = params\n return cls(loc, scale_tril=scale_tril)\n\n @staticmethod\n def infer_shapes(\n loc=(), covariance_matrix=None, precision_matrix=None, scale_tril=None\n ):\n batch_shape, event_shape = loc[:-1], loc[-1:]\n for matrix in [covariance_matrix, precision_matrix, scale_tril]:\n if matrix is not None:\n batch_shape = lax.broadcast_shapes(batch_shape, matrix[:-2])\n event_shape = lax.broadcast_shapes(event_shape, matrix[-1:])\n return batch_shape, event_shape\n\n\ndef _is_sparse(A):\n from scipy import sparse\n\n return sparse.issparse(A)\n\n\ndef _to_sparse(A):\n from scipy import sparse\n\n return sparse.csr_matrix(A)\n\n\nclass CAR(Distribution):\n r\"\"\"\n The Conditional Autoregressive (CAR) distribution is a special case of the multivariate\n normal in which the precision matrix is structured according to the adjacency matrix of\n sites. The amount of autocorrelation between sites is controlled by ``correlation``. The\n distribution is a popular prior for areal spatial data.\n\n :param float or ndarray loc: mean of the multivariate normal\n :param float correlation: autoregression parameter. For most cases, the value should lie\n between 0 (sites are independent, collapses to an iid multivariate normal) and\n 1 (perfect autocorrelation between sites), but the specification allows for negative\n correlations.\n :param float conditional_precision: positive precision for the multivariate normal\n :param ndarray or scipy.sparse.csr_matrix adj_matrix: symmetric adjacency matrix where 1\n indicates adjacency between sites and 0 otherwise. :class:`jax.numpy.ndarray` ``adj_matrix`` is\n supported but is **not** recommended over :class:`numpy.ndarray` or :class:`scipy.sparse.spmatrix`.\n :param bool is_sparse: whether to use a sparse form of ``adj_matrix`` in calculations (must be True if\n ``adj_matrix`` is a :class:`scipy.sparse.spmatrix`)\n \"\"\"\n\n arg_constraints = {\n \"loc\": constraints.real_vector,\n \"correlation\": constraints.open_interval(-1, 1),\n \"conditional_precision\": constraints.positive,\n \"adj_matrix\": constraints.dependent(is_discrete=False, event_dim=2),\n }\n support = constraints.real_vector\n reparametrized_params = [\n \"loc\",\n \"correlation\",\n \"conditional_precision\",\n \"adj_matrix\",\n ]\n\n def __init__(\n self,\n loc,\n correlation,\n conditional_precision,\n adj_matrix,\n *,\n is_sparse=False,\n validate_args=None,\n ):\n if jnp.ndim(loc) == 0:\n (loc,) = promote_shapes(loc, shape=(1,))\n\n self.is_sparse = is_sparse\n\n batch_shape = lax.broadcast_shapes(\n jnp.shape(loc)[:-1],\n jnp.shape(correlation),\n jnp.shape(conditional_precision),\n jnp.shape(adj_matrix)[:-2],\n )\n\n if self.is_sparse:\n if adj_matrix.ndim != 2:\n raise ValueError(\n \"Currently, we only support 2-dimensional adj_matrix. Please make a feature request\",\n \" if you need higher dimensional adj_matrix.\",\n )\n if not (isinstance(adj_matrix, np.ndarray) or _is_sparse(adj_matrix)):\n raise ValueError(\n \"adj_matrix needs to be a numpy array or a scipy sparse matrix. Please make a feature\",\n \" request if you need to support jax ndarrays.\",\n )\n # TODO: look into future jax sparse csr functionality and other developments\n self.adj_matrix = _to_sparse(adj_matrix)\n else:\n assert not _is_sparse(\n adj_matrix\n ), \"adj_matrix is a sparse matrix so please specify `is_sparse=True`.\"\n # TODO: look into static jax ndarray representation\n (self.adj_matrix,) = promote_shapes(\n adj_matrix, shape=batch_shape + adj_matrix.shape[-2:]\n )\n\n event_shape = jnp.shape(self.adj_matrix)[-1:]\n (self.loc,) = promote_shapes(loc, shape=batch_shape + event_shape)\n self.correlation, self.conditional_precision = promote_shapes(\n correlation, conditional_precision, shape=batch_shape\n )\n\n super(CAR, self).__init__(\n batch_shape=batch_shape,\n event_shape=event_shape,\n validate_args=validate_args,\n )\n\n if self._validate_args and (isinstance(adj_matrix, np.ndarray) or is_sparse):\n assert (\n self.adj_matrix.sum(axis=-1) > 0\n ).all() > 0, \"all sites in adjacency matrix must have neighbours\"\n\n if self.is_sparse:\n assert (\n self.adj_matrix != self.adj_matrix.T\n ).nnz == 0, \"adjacency matrix must be symmetric\"\n else:\n assert np.array_equal(\n self.adj_matrix, np.swapaxes(self.adj_matrix, -2, -1)\n ), \"adjacency matrix must be symmetric\"\n\n def sample(self, key, sample_shape=()):\n # TODO: look into a sparse sampling method\n mvn = MultivariateNormal(self.mean, precision_matrix=self.precision_matrix)\n return mvn.sample(key, sample_shape=sample_shape)\n\n @validate_sample\n def log_prob(self, value):\n phi = value - self.loc\n adj_matrix = self.adj_matrix\n\n if self.is_sparse:\n D = np.asarray(adj_matrix.sum(axis=-1)).squeeze(axis=-1)\n D_rsqrt = D ** (-0.5)\n\n adj_matrix_scaled = (\n adj_matrix.multiply(D_rsqrt).multiply(D_rsqrt[:, np.newaxis]).toarray()\n )\n\n adj_matrix = BCOO.from_scipy_sparse(adj_matrix)\n\n else:\n D = adj_matrix.sum(axis=-1)\n D_rsqrt = D ** (-0.5)\n\n adj_matrix_scaled = adj_matrix * (\n D_rsqrt[..., None, :] * D_rsqrt[..., None]\n )\n\n # TODO: look into sparse eignvalue methods\n if isinstance(adj_matrix_scaled, np.ndarray):\n lam = np.linalg.eigvalsh(adj_matrix_scaled)\n else:\n lam = jnp.linalg.eigvalsh(adj_matrix_scaled)\n\n n = D.shape[-1]\n\n logprec = n * jnp.log(self.conditional_precision)\n logdet = jnp.log1p(-jnp.expand_dims(self.correlation, -1) * lam).sum(-1)\n logdet = logdet + jnp.log(D).sum(-1)\n\n logquad = self.conditional_precision * jnp.sum(\n phi\n * (\n D * phi\n - jnp.expand_dims(self.correlation, -1)\n * (adj_matrix @ phi[..., jnp.newaxis]).squeeze(axis=-1)\n ),\n -1,\n )\n\n return 0.5 * (-n * jnp.log(2 * jnp.pi) + logprec + logdet - logquad)\n\n @property\n def mean(self):\n return jnp.broadcast_to(self.loc, self.shape())\n\n @lazy_property\n def precision_matrix(self):\n if self.is_sparse:\n adj_matrix = self.adj_matrix.toarray()\n else:\n adj_matrix = self.adj_matrix\n\n D = adj_matrix.sum(axis=-1, keepdims=True) * jnp.eye(adj_matrix.shape[-1])\n conditional_precision = jnp.expand_dims(self.conditional_precision, (-2, -1))\n correlation = jnp.expand_dims(self.correlation, (-2, -1))\n return conditional_precision * (D - correlation * adj_matrix)\n\n def tree_flatten(self):\n if self.is_sparse:\n return (self.loc, self.correlation, self.conditional_precision), (\n self.is_sparse,\n self.adj_matrix,\n )\n else:\n return (\n self.loc,\n self.correlation,\n self.conditional_precision,\n self.adj_matrix,\n ), (self.is_sparse,)\n\n @classmethod\n def tree_unflatten(cls, aux_data, params):\n is_sparse = aux_data[0]\n if is_sparse:\n loc, correlation, conditional_precision = params\n adj_matrix = aux_data[1]\n else:\n loc, correlation, conditional_precision, adj_matrix = params\n return cls(\n loc, correlation, conditional_precision, adj_matrix, is_sparse=is_sparse\n )\n\n @staticmethod\n def infer_shapes(loc, correlation, conditional_precision, adj_matrix):\n event_shape = adj_matrix[-1:]\n batch_shape = lax.broadcast_shapes(\n loc[:-1], correlation, conditional_precision, adj_matrix[:-2]\n )\n return batch_shape, event_shape\n\n\nclass MultivariateStudentT(Distribution):\n arg_constraints = {\n \"df\": constraints.positive,\n \"loc\": constraints.real_vector,\n \"scale_tril\": constraints.lower_cholesky,\n }\n support = constraints.real_vector\n reparametrized_params = [\"df\", \"loc\", \"scale_tril\"]\n\n def __init__(\n self,\n df,\n loc=0.0,\n scale_tril=None,\n validate_args=None,\n ):\n if jnp.ndim(loc) == 0:\n (loc,) = promote_shapes(loc, shape=(1,))\n batch_shape = lax.broadcast_shapes(\n jnp.shape(df), jnp.shape(loc)[:-1], jnp.shape(scale_tril)[:-2]\n )\n (self.df,) = promote_shapes(df, shape=batch_shape)\n (self.loc,) = promote_shapes(loc, shape=batch_shape + loc.shape[-1:])\n (self.scale_tril,) = promote_shapes(\n scale_tril, shape=batch_shape + scale_tril.shape[-2:]\n )\n event_shape = jnp.shape(self.scale_tril)[-1:]\n self._chi2 = Chi2(self.df)\n super(MultivariateStudentT, self).__init__(\n batch_shape=batch_shape,\n event_shape=event_shape,\n validate_args=validate_args,\n )\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n key_normal, key_chi2 = random.split(key)\n std_normal = random.normal(\n key_normal,\n shape=sample_shape + self.batch_shape + self.event_shape,\n )\n z = self._chi2.sample(key_chi2, sample_shape)\n y = std_normal * jnp.expand_dims(jnp.sqrt(self.df / z), -1)\n return self.loc + jnp.squeeze(\n jnp.matmul(self.scale_tril, y[..., jnp.newaxis]), axis=-1\n )\n\n @validate_sample\n def log_prob(self, value):\n n = self.scale_tril.shape[-1]\n Z = (\n jnp.log(jnp.diagonal(self.scale_tril, axis1=-2, axis2=-1)).sum(-1)\n + 0.5 * n * jnp.log(self.df)\n + 0.5 * n * jnp.log(jnp.pi)\n + gammaln(0.5 * self.df)\n - gammaln(0.5 * (self.df + n))\n )\n M = _batch_mahalanobis(self.scale_tril, value - self.loc)\n return -0.5 * (self.df + n) * jnp.log1p(M / self.df) - Z\n\n @lazy_property\n def covariance_matrix(self):\n # NB: this is not covariance of this distribution;\n # the actual covariance is df / (df - 2) * covariance_matrix\n return jnp.matmul(self.scale_tril, jnp.swapaxes(self.scale_tril, -1, -2))\n\n @lazy_property\n def precision_matrix(self):\n identity = jnp.broadcast_to(\n jnp.eye(self.scale_tril.shape[-1]), self.scale_tril.shape\n )\n return cho_solve((self.scale_tril, True), identity)\n\n @property\n def mean(self):\n # for df <= 1. should be jnp.nan (keeping jnp.inf for consistency with scipy)\n return jnp.broadcast_to(\n jnp.where(jnp.expand_dims(self.df, -1) <= 1, jnp.inf, self.loc),\n self.shape(),\n )\n\n @property\n def variance(self):\n df = jnp.expand_dims(self.df, -1)\n var = jnp.power(self.scale_tril, 2).sum(-1) * (df / (df - 2))\n var = jnp.where(df > 2, var, jnp.inf)\n var = jnp.where(df <= 1, jnp.nan, var)\n return jnp.broadcast_to(var, self.batch_shape + self.event_shape)\n\n @staticmethod\n def infer_shapes(df, loc, scale_tril):\n event_shape = (scale_tril[-1],)\n batch_shape = lax.broadcast_shapes(df, loc[:-1], scale_tril[:-2])\n return batch_shape, event_shape\n\n\ndef _batch_mv(bmat, bvec):\n r\"\"\"\n Performs a batched matrix-vector product, with compatible but different batch shapes.\n This function takes as input `bmat`, containing :math:`n \\times n` matrices, and\n `bvec`, containing length :math:`n` vectors.\n Both `bmat` and `bvec` may have any number of leading dimensions, which correspond\n to a batch shape. They are not necessarily assumed to have the same batch shape,\n just ones which can be broadcasted.\n \"\"\"\n return jnp.squeeze(jnp.matmul(bmat, jnp.expand_dims(bvec, axis=-1)), axis=-1)\n\n\ndef _batch_capacitance_tril(W, D):\n r\"\"\"\n Computes Cholesky of :math:`I + W.T @ inv(D) @ W` for a batch of matrices :math:`W`\n and a batch of vectors :math:`D`.\n \"\"\"\n Wt_Dinv = jnp.swapaxes(W, -1, -2) / jnp.expand_dims(D, -2)\n K = jnp.matmul(Wt_Dinv, W)\n # could be inefficient\n return jnp.linalg.cholesky(jnp.add(K, jnp.identity(K.shape[-1])))\n\n\ndef _batch_lowrank_logdet(W, D, capacitance_tril):\n r\"\"\"\n Uses \"matrix determinant lemma\"::\n log|W @ W.T + D| = log|C| + log|D|,\n where :math:`C` is the capacitance matrix :math:`I + W.T @ inv(D) @ W`, to compute\n the log determinant.\n \"\"\"\n return 2 * jnp.sum(\n jnp.log(jnp.diagonal(capacitance_tril, axis1=-2, axis2=-1)), axis=-1\n ) + jnp.log(D).sum(-1)\n\n\ndef _batch_lowrank_mahalanobis(W, D, x, capacitance_tril):\n r\"\"\"\n Uses \"Woodbury matrix identity\"::\n inv(W @ W.T + D) = inv(D) - inv(D) @ W @ inv(C) @ W.T @ inv(D),\n where :math:`C` is the capacitance matrix :math:`I + W.T @ inv(D) @ W`, to compute the squared\n Mahalanobis distance :math:`x.T @ inv(W @ W.T + D) @ x`.\n \"\"\"\n Wt_Dinv = jnp.swapaxes(W, -1, -2) / jnp.expand_dims(D, -2)\n Wt_Dinv_x = _batch_mv(Wt_Dinv, x)\n mahalanobis_term1 = jnp.sum(jnp.square(x) / D, axis=-1)\n mahalanobis_term2 = _batch_mahalanobis(capacitance_tril, Wt_Dinv_x)\n return mahalanobis_term1 - mahalanobis_term2\n\n\nclass LowRankMultivariateNormal(Distribution):\n arg_constraints = {\n \"loc\": constraints.real_vector,\n \"cov_factor\": constraints.independent(constraints.real, 2),\n \"cov_diag\": constraints.independent(constraints.positive, 1),\n }\n support = constraints.real_vector\n reparametrized_params = [\"loc\", \"cov_factor\", \"cov_diag\"]\n\n def __init__(self, loc, cov_factor, cov_diag, *, validate_args=None):\n if jnp.ndim(loc) < 1:\n raise ValueError(\"`loc` must be at least one-dimensional.\")\n event_shape = jnp.shape(loc)[-1:]\n if jnp.ndim(cov_factor) < 2:\n raise ValueError(\n \"`cov_factor` must be at least two-dimensional, \"\n \"with optional leading batch dimensions\"\n )\n if jnp.shape(cov_factor)[-2:-1] != event_shape:\n raise ValueError(\n \"`cov_factor` must be a batch of matrices with shape {} x m\".format(\n event_shape[0]\n )\n )\n if jnp.shape(cov_diag)[-1:] != event_shape:\n raise ValueError(\n \"`cov_diag` must be a batch of vectors with shape {}\".format(\n self.event_shape\n )\n )\n\n loc, cov_factor, cov_diag = promote_shapes(\n loc[..., jnp.newaxis], cov_factor, cov_diag[..., jnp.newaxis]\n )\n batch_shape = lax.broadcast_shapes(\n jnp.shape(loc), jnp.shape(cov_factor), jnp.shape(cov_diag)\n )[:-2]\n self.loc = loc[..., 0]\n self.cov_factor = cov_factor\n cov_diag = cov_diag[..., 0]\n self.cov_diag = cov_diag\n self._capacitance_tril = _batch_capacitance_tril(cov_factor, cov_diag)\n super(LowRankMultivariateNormal, self).__init__(\n batch_shape=batch_shape,\n event_shape=event_shape,\n validate_args=validate_args,\n )\n\n @property\n def mean(self):\n return self.loc\n\n @lazy_property\n def variance(self):\n raw_variance = jnp.square(self.cov_factor).sum(-1) + self.cov_diag\n return jnp.broadcast_to(raw_variance, self.batch_shape + self.event_shape)\n\n @lazy_property\n def scale_tril(self):\n # The following identity is used to increase the numerically computation stability\n # for Cholesky decomposition (see http://www.gaussianprocess.org/gpml/, Section 3.4.3):\n # W @ W.T + D = D1/2 @ (I + D-1/2 @ W @ W.T @ D-1/2) @ D1/2\n # The matrix \"I + D-1/2 @ W @ W.T @ D-1/2\" has eigenvalues bounded from below by 1,\n # hence it is well-conditioned and safe to take Cholesky decomposition.\n cov_diag_sqrt_unsqueeze = jnp.expand_dims(jnp.sqrt(self.cov_diag), axis=-1)\n Dinvsqrt_W = self.cov_factor / cov_diag_sqrt_unsqueeze\n K = jnp.matmul(Dinvsqrt_W, jnp.swapaxes(Dinvsqrt_W, -1, -2))\n K = jnp.add(K, jnp.identity(K.shape[-1]))\n scale_tril = cov_diag_sqrt_unsqueeze * jnp.linalg.cholesky(K)\n return scale_tril\n\n @lazy_property\n def covariance_matrix(self):\n # TODO: find a better solution to create a diagonal matrix\n new_diag = self.cov_diag[..., jnp.newaxis] * jnp.identity(self.loc.shape[-1])\n covariance_matrix = new_diag + jnp.matmul(\n self.cov_factor, jnp.swapaxes(self.cov_factor, -1, -2)\n )\n return covariance_matrix\n\n @lazy_property\n def precision_matrix(self):\n # We use \"Woodbury matrix identity\" to take advantage of low rank form::\n # inv(W @ W.T + D) = inv(D) - inv(D) @ W @ inv(C) @ W.T @ inv(D)\n # where :math:`C` is the capacitance matrix.\n Wt_Dinv = jnp.swapaxes(self.cov_factor, -1, -2) / jnp.expand_dims(\n self.cov_diag, axis=-2\n )\n A = solve_triangular(Wt_Dinv, self._capacitance_tril, lower=True)\n # TODO: find a better solution to create a diagonal matrix\n inverse_cov_diag = jnp.reciprocal(self.cov_diag)\n diag_embed = inverse_cov_diag[..., jnp.newaxis] * jnp.identity(\n self.loc.shape[-1]\n )\n return diag_embed - jnp.matmul(jnp.swapaxes(A, -1, -2), A)\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n key_W, key_D = random.split(key)\n batch_shape = sample_shape + self.batch_shape\n W_shape = batch_shape + self.cov_factor.shape[-1:]\n D_shape = batch_shape + self.cov_diag.shape[-1:]\n eps_W = random.normal(key_W, W_shape)\n eps_D = random.normal(key_D, D_shape)\n return (\n self.loc\n + _batch_mv(self.cov_factor, eps_W)\n + jnp.sqrt(self.cov_diag) * eps_D\n )\n\n @validate_sample\n def log_prob(self, value):\n diff = value - self.loc\n M = _batch_lowrank_mahalanobis(\n self.cov_factor, self.cov_diag, diff, self._capacitance_tril\n )\n log_det = _batch_lowrank_logdet(\n self.cov_factor, self.cov_diag, self._capacitance_tril\n )\n return -0.5 * (self.loc.shape[-1] * jnp.log(2 * jnp.pi) + log_det + M)\n\n def entropy(self):\n log_det = _batch_lowrank_logdet(\n self.cov_factor, self.cov_diag, self._capacitance_tril\n )\n H = 0.5 * (self.loc.shape[-1] * (1.0 + jnp.log(2 * jnp.pi)) + log_det)\n return jnp.broadcast_to(H, self.batch_shape)\n\n @staticmethod\n def infer_shapes(loc, cov_factor, cov_diag):\n event_shape = loc[-1:]\n batch_shape = lax.broadcast_shapes(loc[:-1], cov_factor[:-2], cov_diag[:-1])\n return batch_shape, event_shape\n\n\nclass Normal(Distribution):\n arg_constraints = {\"loc\": constraints.real, \"scale\": constraints.positive}\n support = constraints.real\n reparametrized_params = [\"loc\", \"scale\"]\n\n def __init__(self, loc=0.0, scale=1.0, *, validate_args=None):\n self.loc, self.scale = promote_shapes(loc, scale)\n batch_shape = lax.broadcast_shapes(jnp.shape(loc), jnp.shape(scale))\n super(Normal, self).__init__(\n batch_shape=batch_shape, validate_args=validate_args\n )\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n eps = random.normal(\n key, shape=sample_shape + self.batch_shape + self.event_shape\n )\n return self.loc + eps * self.scale\n\n @validate_sample\n def log_prob(self, value):\n normalize_term = jnp.log(jnp.sqrt(2 * jnp.pi) * self.scale)\n value_scaled = (value - self.loc) / self.scale\n return -0.5 * value_scaled**2 - normalize_term\n\n def cdf(self, value):\n scaled = (value - self.loc) / self.scale\n return ndtr(scaled)\n\n def icdf(self, q):\n return self.loc + self.scale * ndtri(q)\n\n @property\n def mean(self):\n return jnp.broadcast_to(self.loc, self.batch_shape)\n\n @property\n def variance(self):\n return jnp.broadcast_to(self.scale**2, self.batch_shape)\n\n\nclass Pareto(TransformedDistribution):\n arg_constraints = {\"scale\": constraints.positive, \"alpha\": constraints.positive}\n reparametrized_params = [\"scale\", \"alpha\"]\n\n def __init__(self, scale, alpha, *, validate_args=None):\n self.scale, self.alpha = promote_shapes(scale, alpha)\n batch_shape = lax.broadcast_shapes(jnp.shape(scale), jnp.shape(alpha))\n scale, alpha = jnp.broadcast_to(scale, batch_shape), jnp.broadcast_to(\n alpha, batch_shape\n )\n base_dist = Exponential(alpha)\n transforms = [ExpTransform(), AffineTransform(loc=0, scale=scale)]\n super(Pareto, self).__init__(base_dist, transforms, validate_args=validate_args)\n\n @property\n def mean(self):\n # mean is inf for alpha <= 1\n a = jnp.divide(self.alpha * self.scale, (self.alpha - 1))\n return jnp.where(self.alpha <= 1, jnp.inf, a)\n\n @property\n def variance(self):\n # var is inf for alpha <= 2\n a = jnp.divide(\n (self.scale**2) * self.alpha, (self.alpha - 1) ** 2 * (self.alpha - 2)\n )\n return jnp.where(self.alpha <= 2, jnp.inf, a)\n\n # override the default behaviour to save computations\n @constraints.dependent_property(is_discrete=False, event_dim=0)\n def support(self):\n return constraints.greater_than(self.scale)\n\n def cdf(self, value):\n return 1 - jnp.power(self.scale / value, self.alpha)\n\n def icdf(self, q):\n return self.scale / jnp.power(1 - q, 1 / self.alpha)\n\n def tree_flatten(self):\n return super(TransformedDistribution, self).tree_flatten()\n\n\nclass RelaxedBernoulliLogits(TransformedDistribution):\n arg_constraints = {\"temperature\": constraints.positive, \"logits\": constraints.real}\n support = constraints.unit_interval\n\n def __init__(self, temperature, logits, *, validate_args=None):\n self.temperature, self.logits = promote_shapes(temperature, logits)\n base_dist = Logistic(logits / temperature, 1 / temperature)\n transforms = [SigmoidTransform()]\n super().__init__(base_dist, transforms, validate_args=validate_args)\n\n def tree_flatten(self):\n return super(TransformedDistribution, self).tree_flatten()\n\n\ndef RelaxedBernoulli(temperature, probs=None, logits=None, *, validate_args=None):\n if probs is None and logits is None:\n raise ValueError(\"One of `probs` or `logits` must be specified.\")\n if probs is not None:\n logits = _to_logits_bernoulli(probs)\n return RelaxedBernoulliLogits(temperature, logits, validate_args=validate_args)\n\n\nclass SoftLaplace(Distribution):\n \"\"\"\n Smooth distribution with Laplace-like tail behavior.\n\n This distribution corresponds to the log-convex density::\n\n z = (value - loc) / scale\n log_prob = log(2 / pi) - log(scale) - logaddexp(z, -z)\n\n Like the Laplace density, this density has the heaviest possible tails\n (asymptotically) while still being log-convex. Unlike the Laplace\n distribution, this distribution is infinitely differentiable everywhere,\n and is thus suitable for HMC and Laplace approximation.\n\n :param loc: Location parameter.\n :param scale: Scale parameter.\n \"\"\"\n\n arg_constraints = {\"loc\": constraints.real, \"scale\": constraints.positive}\n support = constraints.real\n reparametrized_params = [\"loc\", \"scale\"]\n\n def __init__(self, loc, scale, *, validate_args=None):\n self.loc, self.scale = promote_shapes(loc, scale)\n batch_shape = lax.broadcast_shapes(jnp.shape(loc), jnp.shape(scale))\n super().__init__(batch_shape=batch_shape, validate_args=validate_args)\n\n @validate_sample\n def log_prob(self, value):\n z = (value - self.loc) / self.scale\n return jnp.log(2 / jnp.pi) - jnp.log(self.scale) - jnp.logaddexp(z, -z)\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n dtype = jnp.result_type(float)\n finfo = jnp.finfo(dtype)\n minval = finfo.tiny\n u = random.uniform(key, shape=sample_shape + self.batch_shape, minval=minval)\n return self.icdf(u)\n\n # TODO: refactor validate_sample to only does validation check and use it here\n def cdf(self, value):\n z = (value - self.loc) / self.scale\n return jnp.arctan(jnp.exp(z)) * (2 / jnp.pi)\n\n def icdf(self, value):\n return jnp.log(jnp.tan(value * (jnp.pi / 2))) * self.scale + self.loc\n\n @property\n def mean(self):\n return self.loc\n\n @property\n def variance(self):\n return (jnp.pi / 2 * self.scale) ** 2\n\n\nclass StudentT(Distribution):\n arg_constraints = {\n \"df\": constraints.positive,\n \"loc\": constraints.real,\n \"scale\": constraints.positive,\n }\n support = constraints.real\n reparametrized_params = [\"df\", \"loc\", \"scale\"]\n\n def __init__(self, df, loc=0.0, scale=1.0, *, validate_args=None):\n batch_shape = lax.broadcast_shapes(\n jnp.shape(df), jnp.shape(loc), jnp.shape(scale)\n )\n self.df, self.loc, self.scale = promote_shapes(\n df, loc, scale, shape=batch_shape\n )\n df = jnp.broadcast_to(df, batch_shape)\n self._chi2 = Chi2(df)\n super(StudentT, self).__init__(batch_shape, validate_args=validate_args)\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n key_normal, key_chi2 = random.split(key)\n std_normal = random.normal(key_normal, shape=sample_shape + self.batch_shape)\n z = self._chi2.sample(key_chi2, sample_shape)\n y = std_normal * jnp.sqrt(self.df / z)\n return self.loc + self.scale * y\n\n @validate_sample\n def log_prob(self, value):\n y = (value - self.loc) / self.scale\n z = (\n jnp.log(self.scale)\n + 0.5 * jnp.log(self.df)\n + 0.5 * jnp.log(jnp.pi)\n + gammaln(0.5 * self.df)\n - gammaln(0.5 * (self.df + 1.0))\n )\n return -0.5 * (self.df + 1.0) * jnp.log1p(y**2.0 / self.df) - z\n\n @property\n def mean(self):\n # for df <= 1. should be jnp.nan (keeping jnp.inf for consistency with scipy)\n return jnp.broadcast_to(\n jnp.where(self.df <= 1, jnp.inf, self.loc), self.batch_shape\n )\n\n @property\n def variance(self):\n var = jnp.where(\n self.df > 2, jnp.divide(self.scale**2 * self.df, self.df - 2.0), jnp.inf\n )\n var = jnp.where(self.df <= 1, jnp.nan, var)\n return jnp.broadcast_to(var, self.batch_shape)\n\n def cdf(self, value):\n # Ref: https://en.wikipedia.org/wiki/Student's_t-distribution#Related_distributions\n # X^2 ~ F(1, df) -> df / (df + X^2) ~ Beta(df/2, 0.5)\n scaled = (value - self.loc) / self.scale\n scaled_squared = scaled * scaled\n beta_value = self.df / (self.df + scaled_squared)\n\n # when scaled < 0, returns 0.5 * Beta(df/2, 0.5).cdf(beta_value)\n # when scaled > 0, returns 1 - 0.5 * Beta(df/2, 0.5).cdf(beta_value)\n return 0.5 * (\n 1\n + jnp.sign(scaled)\n - jnp.sign(scaled) * betainc(0.5 * self.df, 0.5, beta_value)\n )\n\n def icdf(self, q):\n beta_value = betaincinv(0.5 * self.df, 0.5, 1 - jnp.abs(1 - 2 * q))\n scaled_squared = self.df * (1 / beta_value - 1)\n scaled = jnp.sign(q - 0.5) * jnp.sqrt(scaled_squared)\n return scaled * self.scale + self.loc\n\n\nclass Uniform(Distribution):\n arg_constraints = {\"low\": constraints.dependent, \"high\": constraints.dependent}\n reparametrized_params = [\"low\", \"high\"]\n\n def __init__(self, low=0.0, high=1.0, *, validate_args=None):\n self.low, self.high = promote_shapes(low, high)\n batch_shape = lax.broadcast_shapes(jnp.shape(low), jnp.shape(high))\n self._support = constraints.interval(low, high)\n super().__init__(batch_shape, validate_args=validate_args)\n\n @constraints.dependent_property(is_discrete=False, event_dim=0)\n def support(self):\n return self._support\n\n def sample(self, key, sample_shape=()):\n shape = sample_shape + self.batch_shape\n return random.uniform(key, shape=shape, minval=self.low, maxval=self.high)\n\n @validate_sample\n def log_prob(self, value):\n shape = lax.broadcast_shapes(jnp.shape(value), self.batch_shape)\n return -jnp.broadcast_to(jnp.log(self.high - self.low), shape)\n\n def cdf(self, value):\n cdf = (value - self.low) / (self.high - self.low)\n return jnp.clip(cdf, a_min=0.0, a_max=1.0)\n\n def icdf(self, value):\n return self.low + value * (self.high - self.low)\n\n @property\n def mean(self):\n return self.low + (self.high - self.low) / 2.0\n\n @property\n def variance(self):\n return (self.high - self.low) ** 2 / 12.0\n\n def tree_flatten(self):\n if isinstance(self._support.lower_bound, (int, float)) and isinstance(\n self._support.upper_bound, (int, float)\n ):\n aux_data = (self._support.lower_bound, self._support.upper_bound)\n else:\n aux_data = None\n return (self.low, self.high), aux_data\n\n @classmethod\n def tree_unflatten(cls, aux_data, params):\n d = cls(*params)\n if aux_data is not None:\n d._support = constraints.interval(*aux_data)\n return d\n\n @staticmethod\n def infer_shapes(low=(), high=()):\n batch_shape = lax.broadcast_shapes(low, high)\n event_shape = ()\n return batch_shape, event_shape\n\n\nclass Weibull(Distribution):\n arg_constraints = {\n \"scale\": constraints.positive,\n \"concentration\": constraints.positive,\n }\n support = constraints.positive\n reparametrized_params = [\"scale\", \"concentration\"]\n\n def __init__(self, scale, concentration, *, validate_args=None):\n self.concentration, self.scale = promote_shapes(concentration, scale)\n batch_shape = lax.broadcast_shapes(jnp.shape(concentration), jnp.shape(scale))\n super().__init__(batch_shape=batch_shape, validate_args=validate_args)\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n return random.weibull_min(\n key,\n scale=self.scale,\n concentration=self.concentration,\n shape=sample_shape + self.batch_shape,\n )\n\n @validate_sample\n def log_prob(self, value):\n ll = -jnp.power(value / self.scale, self.concentration)\n ll += jnp.log(self.concentration)\n ll += (self.concentration - 1.0) * jnp.log(value)\n ll -= self.concentration * jnp.log(self.scale)\n return ll\n\n def cdf(self, value):\n return 1 - jnp.exp(-((value / self.scale) ** self.concentration))\n\n @property\n def mean(self):\n return self.scale * jnp.exp(gammaln(1.0 + 1.0 / self.concentration))\n\n @property\n def variance(self):\n return self.scale**2 * (\n jnp.exp(gammaln(1.0 + 2.0 / self.concentration))\n - jnp.exp(gammaln(1.0 + 1.0 / self.concentration)) ** 2\n )\n\n\nclass BetaProportion(Beta):\n \"\"\"\n The BetaProportion distribution is a reparameterization of the conventional\n Beta distribution in terms of a the variate mean and a\n precision parameter.\n\n **Reference:**\n `Beta regression for modelling rates and proportion`, Ferrari Silvia, and\n Francisco Cribari-Neto. Journal of Applied Statistics 31.7 (2004): 799-815.\n \"\"\"\n\n arg_constraints = {\n \"mean\": constraints.open_interval(0.0, 1.0),\n \"concentration\": constraints.positive,\n }\n reparametrized_params = [\"mean\", \"concentration\"]\n support = constraints.unit_interval\n\n def __init__(self, mean, concentration, *, validate_args=None):\n self.concentration = jnp.broadcast_to(\n concentration, lax.broadcast_shapes(jnp.shape(concentration))\n )\n super().__init__(\n mean * concentration,\n (1.0 - mean) * concentration,\n validate_args=validate_args,\n )\n\n\nclass AsymmetricLaplaceQuantile(Distribution):\n \"\"\"An alternative parameterization of AsymmetricLaplace commonly applied in\n Bayesian quantile regression.\n\n Instead of the `asymmetry` parameter employed by AsymmetricLaplace, to\n define the balance between left- versus right-hand sides of the\n distribution, this class utilizes a `quantile` parameter, which describes\n the proportion of probability density that falls to the left-hand side of\n the distribution.\n\n The `scale` parameter is also interpreted slightly differently than in\n AsymmetricLaplace. When `loc=0` and `scale=1`, AsymmetricLaplace(0,1,1)\n is equivalent to Laplace(0,1), while AsymmetricLaplaceQuantile(0,1,0.5) is\n equivalent to Laplace(0,2).\n \"\"\"\n\n arg_constraints = {\n \"loc\": constraints.real,\n \"scale\": constraints.positive,\n \"quantile\": constraints.open_interval(0.0, 1.0),\n }\n reparametrized_params = [\"loc\", \"scale\", \"quantile\"]\n support = constraints.real\n\n def __init__(self, loc=0.0, scale=1.0, quantile=0.5, *, validate_args=None):\n batch_shape = lax.broadcast_shapes(\n jnp.shape(loc), jnp.shape(scale), jnp.shape(quantile)\n )\n self.loc, self.scale, self.quantile = promote_shapes(\n loc, scale, quantile, shape=batch_shape\n )\n super(AsymmetricLaplaceQuantile, self).__init__(\n batch_shape=batch_shape, validate_args=validate_args\n )\n asymmetry = (1 / ((1 / quantile) - 1)) ** 0.5\n scale_classic = scale * asymmetry / quantile\n self._ald = AsymmetricLaplace(loc=loc, scale=scale_classic, asymmetry=asymmetry)\n\n def log_prob(self, value):\n if self._validate_args:\n self._validate_sample(value)\n return self._ald.log_prob(value)\n\n def sample(self, key, sample_shape=()):\n return self._ald.sample(key, sample_shape=sample_shape)\n\n @property\n def mean(self):\n return self._ald.mean\n\n @property\n def variance(self):\n return self._ald.variance\n\n def cdf(self, value):\n return self._ald.cdf(value)\n\n def icdf(self, value):\n return self._ald.icdf(value)\n", "path": "numpyro/distributions/continuous.py" }, { "content": "# Copyright Contributors to the Pyro project.\n# SPDX-License-Identifier: Apache-2.0\n\nfrom jax import lax\nimport jax.numpy as jnp\nimport jax.random as random\nfrom jax.scipy.special import logsumexp\nfrom jax.tree_util import tree_map\n\nfrom numpyro.distributions import constraints\nfrom numpyro.distributions.continuous import (\n Cauchy,\n Laplace,\n Logistic,\n Normal,\n SoftLaplace,\n StudentT,\n)\nfrom numpyro.distributions.distribution import Distribution\nfrom numpyro.distributions.util import (\n is_prng_key,\n lazy_property,\n promote_shapes,\n validate_sample,\n)\n\n\nclass LeftTruncatedDistribution(Distribution):\n arg_constraints = {\"low\": constraints.real}\n reparametrized_params = [\"low\"]\n supported_types = (Cauchy, Laplace, Logistic, Normal, SoftLaplace, StudentT)\n\n def __init__(self, base_dist, low=0.0, *, validate_args=None):\n assert isinstance(base_dist, self.supported_types)\n assert (\n base_dist.support is constraints.real\n ), \"The base distribution should be univariate and have real support.\"\n batch_shape = lax.broadcast_shapes(base_dist.batch_shape, jnp.shape(low))\n self.base_dist = tree_map(\n lambda p: promote_shapes(p, shape=batch_shape)[0], base_dist\n )\n (self.low,) = promote_shapes(low, shape=batch_shape)\n self._support = constraints.greater_than(low)\n super().__init__(batch_shape, validate_args=validate_args)\n\n @constraints.dependent_property(is_discrete=False, event_dim=0)\n def support(self):\n return self._support\n\n @lazy_property\n def _tail_prob_at_low(self):\n # if low < loc, returns cdf(low); otherwise returns 1 - cdf(low)\n loc = self.base_dist.loc\n sign = jnp.where(loc >= self.low, 1.0, -1.0)\n return self.base_dist.cdf(loc - sign * (loc - self.low))\n\n @lazy_property\n def _tail_prob_at_high(self):\n # if low < loc, returns cdf(high) = 1; otherwise returns 1 - cdf(high) = 0\n return jnp.where(self.low <= self.base_dist.loc, 1.0, 0.0)\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n dtype = jnp.result_type(float)\n finfo = jnp.finfo(dtype)\n minval = finfo.tiny\n u = random.uniform(key, shape=sample_shape + self.batch_shape, minval=minval)\n loc = self.base_dist.loc\n sign = jnp.where(loc >= self.low, 1.0, -1.0)\n return (1 - sign) * loc + sign * self.base_dist.icdf(\n (1 - u) * self._tail_prob_at_low + u * self._tail_prob_at_high\n )\n\n @validate_sample\n def log_prob(self, value):\n sign = jnp.where(self.base_dist.loc >= self.low, 1.0, -1.0)\n return self.base_dist.log_prob(value) - jnp.log(\n sign * (self._tail_prob_at_high - self._tail_prob_at_low)\n )\n\n def tree_flatten(self):\n base_flatten, base_aux = self.base_dist.tree_flatten()\n if isinstance(self._support.lower_bound, (int, float)):\n return base_flatten, (\n type(self.base_dist),\n base_aux,\n self._support.lower_bound,\n )\n else:\n return (base_flatten, self.low), (type(self.base_dist), base_aux)\n\n @classmethod\n def tree_unflatten(cls, aux_data, params):\n if len(aux_data) == 2:\n base_flatten, low = params\n base_cls, base_aux = aux_data\n else:\n base_flatten = params\n base_cls, base_aux, low = aux_data\n base_dist = base_cls.tree_unflatten(base_aux, base_flatten)\n return cls(base_dist, low=low)\n\n @property\n def mean(self):\n if isinstance(self.base_dist, Normal):\n low_prob = jnp.exp(self.log_prob(self.low))\n return self.base_dist.loc + low_prob * self.base_dist.scale**2\n elif isinstance(self.base_dist, Cauchy):\n return jnp.full(self.batch_shape, jnp.nan)\n else:\n return NotImplementedError(\"mean only available for Normal and Cauchy\")\n\n @property\n def var(self):\n if isinstance(self.base_dist, Normal):\n low_prob = jnp.exp(self.log_prob(self.low))\n return (self.base_dist.scale**2) * (\n 1\n + (self.low - self.base_dist.loc) * low_prob\n - (low_prob * self.base_dist.scale) ** 2\n )\n elif isinstance(self.base_dist, Cauchy):\n return jnp.full(self.batch_shape, jnp.nan)\n else:\n return NotImplementedError(\"var only available for Normal and Cauchy\")\n\n\nclass RightTruncatedDistribution(Distribution):\n arg_constraints = {\"high\": constraints.real}\n reparametrized_params = [\"high\"]\n supported_types = (Cauchy, Laplace, Logistic, Normal, SoftLaplace, StudentT)\n\n def __init__(self, base_dist, high=0.0, *, validate_args=None):\n assert isinstance(base_dist, self.supported_types)\n assert (\n base_dist.support is constraints.real\n ), \"The base distribution should be univariate and have real support.\"\n batch_shape = lax.broadcast_shapes(base_dist.batch_shape, jnp.shape(high))\n self.base_dist = tree_map(\n lambda p: promote_shapes(p, shape=batch_shape)[0], base_dist\n )\n (self.high,) = promote_shapes(high, shape=batch_shape)\n self._support = constraints.less_than(high)\n super().__init__(batch_shape, validate_args=validate_args)\n\n @constraints.dependent_property(is_discrete=False, event_dim=0)\n def support(self):\n return self._support\n\n @lazy_property\n def _cdf_at_high(self):\n return self.base_dist.cdf(self.high)\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n dtype = jnp.result_type(float)\n finfo = jnp.finfo(dtype)\n minval = finfo.tiny\n u = random.uniform(key, shape=sample_shape + self.batch_shape, minval=minval)\n return self.base_dist.icdf(u * self._cdf_at_high)\n\n @validate_sample\n def log_prob(self, value):\n return self.base_dist.log_prob(value) - jnp.log(self._cdf_at_high)\n\n def tree_flatten(self):\n base_flatten, base_aux = self.base_dist.tree_flatten()\n if isinstance(self._support.upper_bound, (int, float)):\n return base_flatten, (\n type(self.base_dist),\n base_aux,\n self._support.upper_bound,\n )\n else:\n return (base_flatten, self.high), (type(self.base_dist), base_aux)\n\n @classmethod\n def tree_unflatten(cls, aux_data, params):\n if len(aux_data) == 2:\n base_flatten, high = params\n base_cls, base_aux = aux_data\n else:\n base_flatten = params\n base_cls, base_aux, high = aux_data\n base_dist = base_cls.tree_unflatten(base_aux, base_flatten)\n return cls(base_dist, high=high)\n\n @property\n def mean(self):\n if isinstance(self.base_dist, Normal):\n high_prob = jnp.exp(self.log_prob(self.high))\n return self.base_dist.loc - high_prob * self.base_dist.scale**2\n elif isinstance(self.base_dist, Cauchy):\n return jnp.full(self.batch_shape, jnp.nan)\n else:\n return NotImplementedError(\"mean only available for Normal and Cauchy\")\n\n @property\n def var(self):\n if isinstance(self.base_dist, Normal):\n high_prob = jnp.exp(self.log_prob(self.high))\n return (self.base_dist.scale**2) * (\n 1\n - (self.high - self.base_dist.loc) * high_prob\n - (high_prob * self.base_dist.scale) ** 2\n )\n elif isinstance(self.base_dist, Cauchy):\n return jnp.full(self.batch_shape, jnp.nan)\n else:\n return NotImplementedError(\"var only available for Normal and Cauchy\")\n\n\nclass TwoSidedTruncatedDistribution(Distribution):\n arg_constraints = {\"low\": constraints.dependent, \"high\": constraints.dependent}\n reparametrized_params = [\"low\", \"high\"]\n supported_types = (Cauchy, Laplace, Logistic, Normal, SoftLaplace, StudentT)\n\n def __init__(self, base_dist, low=0.0, high=1.0, *, validate_args=None):\n assert isinstance(base_dist, self.supported_types)\n assert (\n base_dist.support is constraints.real\n ), \"The base distribution should be univariate and have real support.\"\n batch_shape = lax.broadcast_shapes(\n base_dist.batch_shape, jnp.shape(low), jnp.shape(high)\n )\n self.base_dist = tree_map(\n lambda p: promote_shapes(p, shape=batch_shape)[0], base_dist\n )\n (self.low,) = promote_shapes(low, shape=batch_shape)\n (self.high,) = promote_shapes(high, shape=batch_shape)\n self._support = constraints.interval(low, high)\n super().__init__(batch_shape, validate_args=validate_args)\n\n @constraints.dependent_property(is_discrete=False, event_dim=0)\n def support(self):\n return self._support\n\n @lazy_property\n def _tail_prob_at_low(self):\n # if low < loc, returns cdf(low); otherwise returns 1 - cdf(low)\n loc = self.base_dist.loc\n sign = jnp.where(loc >= self.low, 1.0, -1.0)\n return self.base_dist.cdf(loc - sign * (loc - self.low))\n\n @lazy_property\n def _tail_prob_at_high(self):\n # if low < loc, returns cdf(high); otherwise returns 1 - cdf(high)\n loc = self.base_dist.loc\n sign = jnp.where(loc >= self.low, 1.0, -1.0)\n return self.base_dist.cdf(loc - sign * (loc - self.high))\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n dtype = jnp.result_type(float)\n finfo = jnp.finfo(dtype)\n minval = finfo.tiny\n u = random.uniform(key, shape=sample_shape + self.batch_shape, minval=minval)\n\n # NB: we use a more numerically stable formula for a symmetric base distribution\n # A = icdf(cdf(low) + (cdf(high) - cdf(low)) * u) = icdf[(1 - u) * cdf(low) + u * cdf(high)]\n # will suffer by precision issues when low is large;\n # If low < loc:\n # A = icdf[(1 - u) * cdf(low) + u * cdf(high)]\n # Else\n # A = 2 * loc - icdf[(1 - u) * cdf(2*loc-low)) + u * cdf(2*loc - high)]\n loc = self.base_dist.loc\n sign = jnp.where(loc >= self.low, 1.0, -1.0)\n return (1 - sign) * loc + sign * self.base_dist.icdf(\n (1 - u) * self._tail_prob_at_low + u * self._tail_prob_at_high\n )\n\n @validate_sample\n def log_prob(self, value):\n # NB: we use a more numerically stable formula for a symmetric base distribution\n # if low < loc\n # cdf(high) - cdf(low) = as-is\n # if low > loc\n # cdf(high) - cdf(low) = cdf(2 * loc - low) - cdf(2 * loc - high)\n sign = jnp.where(self.base_dist.loc >= self.low, 1.0, -1.0)\n return self.base_dist.log_prob(value) - jnp.log(\n sign * (self._tail_prob_at_high - self._tail_prob_at_low)\n )\n\n def tree_flatten(self):\n base_flatten, base_aux = self.base_dist.tree_flatten()\n if isinstance(self._support.lower_bound, (int, float)) and isinstance(\n self._support.upper_bound, (int, float)\n ):\n return base_flatten, (\n type(self.base_dist),\n base_aux,\n self._support.lower_bound,\n self._support.upper_bound,\n )\n else:\n return (base_flatten, self.low, self.high), (type(self.base_dist), base_aux)\n\n @classmethod\n def tree_unflatten(cls, aux_data, params):\n if len(aux_data) == 2:\n base_flatten, low, high = params\n base_cls, base_aux = aux_data\n else:\n base_flatten = params\n base_cls, base_aux, low, high = aux_data\n base_dist = base_cls.tree_unflatten(base_aux, base_flatten)\n return cls(base_dist, low=low, high=high)\n\n @property\n def mean(self):\n if isinstance(self.base_dist, Normal):\n low_prob = jnp.exp(self.log_prob(self.low))\n high_prob = jnp.exp(self.log_prob(self.high))\n return (\n self.base_dist.loc + (low_prob - high_prob) * self.base_dist.scale**2\n )\n elif isinstance(self.base_dist, Cauchy):\n return jnp.full(self.batch_shape, jnp.nan)\n else:\n return NotImplementedError(\"mean only available for Normal and Cauchy\")\n\n @property\n def var(self):\n if isinstance(self.base_dist, Normal):\n low_prob = jnp.exp(self.log_prob(self.low))\n high_prob = jnp.exp(self.log_prob(self.high))\n return (self.base_dist.scale**2) * (\n 1\n + (self.low - self.base_dist.loc) * low_prob\n - (self.high - self.base_dist.loc) * high_prob\n - ((low_prob - high_prob) * self.base_dist.scale) ** 2\n )\n elif isinstance(self.base_dist, Cauchy):\n return jnp.full(self.batch_shape, jnp.nan)\n else:\n return NotImplementedError(\"var only available for Normal and Cauchy\")\n\n\ndef TruncatedDistribution(base_dist, low=None, high=None, *, validate_args=None):\n \"\"\"\n A function to generate a truncated distribution.\n\n :param base_dist: The base distribution to be truncated. This should be a univariate\n distribution. Currently, only the following distributions are supported:\n Cauchy, Laplace, Logistic, Normal, and StudentT.\n :param low: the value which is used to truncate the base distribution from below.\n Setting this parameter to None to not truncate from below.\n :param high: the value which is used to truncate the base distribution from above.\n Setting this parameter to None to not truncate from above.\n \"\"\"\n if high is None:\n if low is None:\n return base_dist\n else:\n return LeftTruncatedDistribution(\n base_dist, low=low, validate_args=validate_args\n )\n elif low is None:\n return RightTruncatedDistribution(\n base_dist, high=high, validate_args=validate_args\n )\n else:\n return TwoSidedTruncatedDistribution(\n base_dist, low=low, high=high, validate_args=validate_args\n )\n\n\ndef TruncatedCauchy(loc=0.0, scale=1.0, *, low=None, high=None, validate_args=None):\n return TruncatedDistribution(\n Cauchy(loc, scale), low=low, high=high, validate_args=validate_args\n )\n\n\ndef TruncatedNormal(loc=0.0, scale=1.0, *, low=None, high=None, validate_args=None):\n return TruncatedDistribution(\n Normal(loc, scale), low=low, high=high, validate_args=validate_args\n )\n\n\nclass TruncatedPolyaGamma(Distribution):\n truncation_point = 2.5\n num_log_prob_terms = 7\n num_gamma_variates = 8\n assert num_log_prob_terms % 2 == 1\n\n arg_constraints = {}\n support = constraints.interval(0.0, truncation_point)\n\n def __init__(self, batch_shape=(), *, validate_args=None):\n super(TruncatedPolyaGamma, self).__init__(\n batch_shape, validate_args=validate_args\n )\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n denom = jnp.square(jnp.arange(0.5, self.num_gamma_variates))\n x = random.gamma(\n key, jnp.ones(self.batch_shape + sample_shape + (self.num_gamma_variates,))\n )\n x = jnp.sum(x / denom, axis=-1)\n return jnp.clip(x * (0.5 / jnp.pi**2), a_max=self.truncation_point)\n\n @validate_sample\n def log_prob(self, value):\n value = value[..., None]\n all_indices = jnp.arange(0, self.num_log_prob_terms)\n two_n_plus_one = 2.0 * all_indices + 1.0\n log_terms = (\n jnp.log(two_n_plus_one)\n - 1.5 * jnp.log(value)\n - 0.125 * jnp.square(two_n_plus_one) / value\n )\n even_terms = jnp.take(log_terms, all_indices[::2], axis=-1)\n odd_terms = jnp.take(log_terms, all_indices[1::2], axis=-1)\n sum_even = jnp.exp(logsumexp(even_terms, axis=-1))\n sum_odd = jnp.exp(logsumexp(odd_terms, axis=-1))\n return jnp.log(sum_even - sum_odd) - 0.5 * jnp.log(2.0 * jnp.pi)\n\n def tree_flatten(self):\n return (), self.batch_shape\n\n @classmethod\n def tree_unflatten(cls, aux_data, params):\n return cls(batch_shape=aux_data)\n", "path": "numpyro/distributions/truncated.py" } ]
[ { "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 (Soumith Chintala)\n# Copyright (c) 2011-2014 Idiap Research Institute (Ronan Collobert)\n# Copyright (c) 2012-2014 Deepmind Technologies (Koray Kavukcuoglu)\n# Copyright (c) 2011-2012 NEC Laboratories America (Koray Kavukcuoglu)\n# Copyright (c) 2011-2013 NYU (Clement Farabet)\n# Copyright (c) 2006-2010 NEC Laboratories America (Ronan Collobert, Leon Bottou, Iain Melvin, Jason Weston)\n# Copyright (c) 2006 Idiap Research Institute (Samy Bengio)\n# Copyright (c) 2001-2004 Idiap Research Institute (Ronan Collobert, Samy Bengio, Johnny Mariethoz)\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\nimport numpy as np\n\nfrom jax import lax, vmap\nfrom jax.experimental.sparse import BCOO\nfrom jax.lax import scan\nimport jax.nn as nn\nimport jax.numpy as jnp\nimport jax.random as random\nfrom jax.scipy.linalg import cho_solve, solve_triangular\nfrom jax.scipy.special import (\n betaln,\n expi,\n expit,\n gammainc,\n gammaln,\n logit,\n multigammaln,\n ndtr,\n ndtri,\n xlog1py,\n xlogy,\n)\nfrom jax.scipy.stats import norm as jax_norm\n\nfrom numpyro.distributions import constraints\nfrom numpyro.distributions.discrete import _to_logits_bernoulli\nfrom numpyro.distributions.distribution import Distribution, TransformedDistribution\nfrom numpyro.distributions.transforms import (\n AffineTransform,\n CorrMatrixCholeskyTransform,\n ExpTransform,\n PowerTransform,\n SigmoidTransform,\n)\nfrom numpyro.distributions.util import (\n betainc,\n betaincinv,\n cholesky_of_inverse,\n gammaincinv,\n is_prng_key,\n lazy_property,\n matrix_to_tril_vec,\n promote_shapes,\n signed_stick_breaking_tril,\n validate_sample,\n vec_to_tril_matrix,\n)\n\n\nclass AsymmetricLaplace(Distribution):\n arg_constraints = {\n \"loc\": constraints.real,\n \"scale\": constraints.positive,\n \"asymmetry\": constraints.positive,\n }\n reparametrized_params = [\"loc\", \"scale\", \"asymmetry\"]\n support = constraints.real\n\n def __init__(self, loc=0.0, scale=1.0, asymmetry=1.0, *, validate_args=None):\n batch_shape = lax.broadcast_shapes(\n jnp.shape(loc), jnp.shape(scale), jnp.shape(asymmetry)\n )\n self.loc, self.scale, self.asymmetry = promote_shapes(\n loc, scale, asymmetry, shape=batch_shape\n )\n super(AsymmetricLaplace, self).__init__(\n batch_shape=batch_shape, validate_args=validate_args\n )\n\n @lazy_property\n def left_scale(self):\n return self.scale * self.asymmetry\n\n @lazy_property\n def right_scale(self):\n return self.scale / self.asymmetry\n\n def log_prob(self, value):\n if self._validate_args:\n self._validate_sample(value)\n z = value - self.loc\n z = -jnp.abs(z) / jnp.where(z < 0, self.left_scale, self.right_scale)\n return z - jnp.log(self.left_scale + self.right_scale)\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n shape = (2,) + sample_shape + self.batch_shape + self.event_shape\n u, v = random.exponential(key, shape=shape)\n return self.loc - self.left_scale * u + self.right_scale * v\n\n @property\n def mean(self):\n total_scale = self.left_scale + self.right_scale\n mean = self.loc + (self.right_scale**2 - self.left_scale**2) / total_scale\n return jnp.broadcast_to(mean, self.batch_shape)\n\n @property\n def variance(self):\n left = self.left_scale\n right = self.right_scale\n total = left + right\n p = left / total\n q = right / total\n variance = p * left**2 + q * right**2 + p * q * total**2\n return jnp.broadcast_to(variance, self.batch_shape)\n\n def cdf(self, value):\n z = value - self.loc\n k = self.asymmetry\n return jnp.where(\n z >= 0,\n 1 - (1 / (1 + k**2)) * jnp.exp(-jnp.abs(z) / self.right_scale),\n k**2 / (1 + k**2) * jnp.exp(-jnp.abs(z) / self.left_scale),\n )\n\n def icdf(self, value):\n k = self.asymmetry\n temp = k**2 / (1 + k**2)\n return jnp.where(\n value <= temp,\n self.loc + self.left_scale * jnp.log(value / temp),\n self.loc - self.right_scale * jnp.log((1 + k**2) * (1 - value)),\n )\n\n\nclass Beta(Distribution):\n arg_constraints = {\n \"concentration1\": constraints.positive,\n \"concentration0\": constraints.positive,\n }\n reparametrized_params = [\"concentration1\", \"concentration0\"]\n support = constraints.unit_interval\n\n def __init__(self, concentration1, concentration0, *, validate_args=None):\n self.concentration1, self.concentration0 = promote_shapes(\n concentration1, concentration0\n )\n batch_shape = lax.broadcast_shapes(\n jnp.shape(concentration1), jnp.shape(concentration0)\n )\n concentration1 = jnp.broadcast_to(concentration1, batch_shape)\n concentration0 = jnp.broadcast_to(concentration0, batch_shape)\n super(Beta, self).__init__(batch_shape=batch_shape, validate_args=validate_args)\n self._dirichlet = Dirichlet(\n jnp.stack([concentration1, concentration0], axis=-1)\n )\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n return self._dirichlet.sample(key, sample_shape)[..., 0]\n\n @validate_sample\n def log_prob(self, value):\n return self._dirichlet.log_prob(jnp.stack([value, 1.0 - value], -1))\n\n @property\n def mean(self):\n return self.concentration1 / (self.concentration1 + self.concentration0)\n\n @property\n def variance(self):\n total = self.concentration1 + self.concentration0\n return self.concentration1 * self.concentration0 / (total**2 * (total + 1))\n\n def cdf(self, value):\n return betainc(self.concentration1, self.concentration0, value)\n\n def icdf(self, q):\n return betaincinv(self.concentration1, self.concentration0, q)\n\n\nclass Cauchy(Distribution):\n arg_constraints = {\"loc\": constraints.real, \"scale\": constraints.positive}\n support = constraints.real\n reparametrized_params = [\"loc\", \"scale\"]\n\n def __init__(self, loc=0.0, scale=1.0, *, validate_args=None):\n self.loc, self.scale = promote_shapes(loc, scale)\n batch_shape = lax.broadcast_shapes(jnp.shape(loc), jnp.shape(scale))\n super(Cauchy, self).__init__(\n batch_shape=batch_shape, validate_args=validate_args\n )\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n eps = random.cauchy(key, shape=sample_shape + self.batch_shape)\n return self.loc + eps * self.scale\n\n @validate_sample\n def log_prob(self, value):\n return (\n -jnp.log(jnp.pi)\n - jnp.log(self.scale)\n - jnp.log1p(((value - self.loc) / self.scale) ** 2)\n )\n\n @property\n def mean(self):\n return jnp.full(self.batch_shape, jnp.nan)\n\n @property\n def variance(self):\n return jnp.full(self.batch_shape, jnp.nan)\n\n def cdf(self, value):\n scaled = (value - self.loc) / self.scale\n return jnp.arctan(scaled) / jnp.pi + 0.5\n\n def icdf(self, q):\n return self.loc + self.scale * jnp.tan(jnp.pi * (q - 0.5))\n\n\nclass Dirichlet(Distribution):\n arg_constraints = {\n \"concentration\": constraints.independent(constraints.positive, 1)\n }\n reparametrized_params = [\"concentration\"]\n support = constraints.simplex\n\n def __init__(self, concentration, *, validate_args=None):\n if jnp.ndim(concentration) < 1:\n raise ValueError(\n \"`concentration` parameter must be at least one-dimensional.\"\n )\n self.concentration = concentration\n batch_shape, event_shape = concentration.shape[:-1], concentration.shape[-1:]\n super(Dirichlet, self).__init__(\n batch_shape=batch_shape,\n event_shape=event_shape,\n validate_args=validate_args,\n )\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n shape = sample_shape + self.batch_shape\n samples = random.dirichlet(key, self.concentration, shape=shape)\n return jnp.clip(\n samples, a_min=jnp.finfo(samples).tiny, a_max=1 - jnp.finfo(samples).eps\n )\n\n @validate_sample\n def log_prob(self, value):\n normalize_term = jnp.sum(gammaln(self.concentration), axis=-1) - gammaln(\n jnp.sum(self.concentration, axis=-1)\n )\n return (\n jnp.sum(jnp.log(value) * (self.concentration - 1.0), axis=-1)\n - normalize_term\n )\n\n @property\n def mean(self):\n return self.concentration / jnp.sum(self.concentration, axis=-1, keepdims=True)\n\n @property\n def variance(self):\n con0 = jnp.sum(self.concentration, axis=-1, keepdims=True)\n return (\n self.concentration * (con0 - self.concentration) / (con0**2 * (con0 + 1))\n )\n\n @staticmethod\n def infer_shapes(concentration):\n batch_shape = concentration[:-1]\n event_shape = concentration[-1:]\n return batch_shape, event_shape\n\n\nclass EulerMaruyama(Distribution):\n \"\"\"\n Euler–Maruyama method is a method for the approximate numerical solution\n of a stochastic differential equation (SDE)\n\n :param ndarray t: discretized time\n :param callable sde_fn: function returning the drift and diffusion coefficients of SDE\n :param Distribution init_dist: Distribution for initial values.\n\n **References**\n\n [1] https://en.wikipedia.org/wiki/Euler-Maruyama_method\n \"\"\"\n\n arg_constraints = {\"t\": constraints.ordered_vector}\n\n def __init__(self, t, sde_fn, init_dist, *, validate_args=None):\n self.t = t\n self.sde_fn = sde_fn\n self.init_dist = init_dist\n\n if not isinstance(init_dist, Distribution):\n raise TypeError(\"Init distribution is expected to be Distribution class.\")\n\n batch_shape_t = jnp.shape(t)[:-1]\n batch_shape = lax.broadcast_shapes(batch_shape_t, init_dist.batch_shape)\n event_shape = (jnp.shape(t)[-1],) + init_dist.event_shape\n\n super(EulerMaruyama, self).__init__(\n batch_shape, event_shape, validate_args=validate_args\n )\n\n @constraints.dependent_property(is_discrete=False)\n def support(self):\n return constraints.independent(constraints.real, self.event_dim)\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n batch_shape = sample_shape + self.batch_shape\n\n def step(y_curr, xs):\n noise_curr, t_curr, dt_curr = xs\n f, g = self.sde_fn(y_curr, t_curr)\n mu = y_curr + dt_curr * f\n sigma = jnp.sqrt(dt_curr) * g\n y_next = mu + sigma * noise_curr\n return y_next, y_next\n\n rng_noise, rng_init = random.split(key)\n noises = random.normal(\n rng_noise,\n shape=batch_shape + (self.event_shape[0] - 1,) + self.event_shape[1:],\n )\n inits = self.init_dist.expand(batch_shape).sample(rng_init)\n\n def scan_fn(init, noise, tm1, dt):\n return scan(step, init, (noise, tm1, dt))\n\n batch_dim = len(batch_shape)\n if batch_dim:\n inits = inits.reshape((-1,) + inits.shape[batch_dim:])\n noises = noises.reshape((-1,) + noises.shape[batch_dim:])\n t = jnp.broadcast_to(self.t, batch_shape + (self.event_shape[0],))\n t = t.reshape((-1,) + t.shape[batch_dim:])\n dt = jnp.diff(t, axis=-1)\n _, sde_out = vmap(scan_fn)(inits, noises, t[..., :-1], dt)\n sde_out = jnp.concatenate([inits[:, None], sde_out], axis=1)\n sde_out = jnp.reshape(sde_out, batch_shape + self.event_shape)\n else:\n dt = jnp.diff(self.t, axis=-1)\n _, sde_out = scan_fn(inits, noises, self.t[:-1], dt)\n sde_out = jnp.concatenate([inits[None], sde_out], axis=0)\n\n return sde_out\n\n @validate_sample\n def log_prob(self, value):\n sample_shape = lax.broadcast_shapes(\n value.shape[: -self.event_dim], self.batch_shape\n )\n value = jnp.broadcast_to(value, sample_shape + self.event_shape)\n\n if sample_shape:\n reshaped_value = value.reshape((-1,) + self.event_shape)\n xtm1, xt = reshaped_value[:, :-1], reshaped_value[:, 1:]\n value0 = reshaped_value[:, 0]\n t = jnp.broadcast_to(self.t, sample_shape + (self.event_shape[0],))\n t = t.reshape((-1,) + (self.event_shape[0],))\n\n f, g = vmap(vmap(self.sde_fn))(xtm1, t[:, :-1])\n\n f = f.reshape(sample_shape + f.shape[1:])\n g = g.reshape(sample_shape + g.shape[1:])\n xtm1 = xtm1.reshape(sample_shape + xtm1.shape[1:])\n xt = xt.reshape(sample_shape + xt.shape[1:])\n value0 = value0.reshape(sample_shape + value0.shape[1:])\n\n else:\n xtm1, xt = value[:-1], value[1:]\n value0 = value[0]\n\n f, g = vmap(self.sde_fn)(xtm1, self.t[:-1])\n\n # add missing event dimensions\n batch_dim = len(sample_shape)\n f = f.reshape(\n f.shape[: batch_dim + 1]\n + (1,) * (xt.ndim - f.ndim)\n + f.shape[batch_dim + 1 :]\n )\n g = g.reshape(\n g.shape[: batch_dim + 1]\n + (1,) * (xt.ndim - g.ndim)\n + g.shape[batch_dim + 1 :]\n )\n\n dt = jnp.diff(self.t, axis=-1)\n dt = dt.reshape(dt.shape + (1,) * (self.event_dim - 1))\n mu = xtm1 + dt * f\n sigma = jnp.sqrt(dt) * g\n\n sde_log_prob = Normal(mu, sigma).to_event(self.event_dim).log_prob(xt)\n init_log_prob = self.init_dist.log_prob(value0)\n\n return sde_log_prob + init_log_prob\n\n\nclass Exponential(Distribution):\n reparametrized_params = [\"rate\"]\n arg_constraints = {\"rate\": constraints.positive}\n support = constraints.positive\n\n def __init__(self, rate=1.0, *, validate_args=None):\n self.rate = rate\n super(Exponential, self).__init__(\n batch_shape=jnp.shape(rate), validate_args=validate_args\n )\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n return (\n random.exponential(key, shape=sample_shape + self.batch_shape) / self.rate\n )\n\n @validate_sample\n def log_prob(self, value):\n return jnp.log(self.rate) - self.rate * value\n\n @property\n def mean(self):\n return jnp.reciprocal(self.rate)\n\n @property\n def variance(self):\n return jnp.reciprocal(self.rate**2)\n\n def cdf(self, value):\n return -jnp.expm1(-self.rate * value)\n\n def icdf(self, q):\n return -jnp.log1p(-q) / self.rate\n\n\nclass Gamma(Distribution):\n arg_constraints = {\n \"concentration\": constraints.positive,\n \"rate\": constraints.positive,\n }\n support = constraints.positive\n reparametrized_params = [\"concentration\", \"rate\"]\n\n def __init__(self, concentration, rate=1.0, *, validate_args=None):\n self.concentration, self.rate = promote_shapes(concentration, rate)\n batch_shape = lax.broadcast_shapes(jnp.shape(concentration), jnp.shape(rate))\n super(Gamma, self).__init__(\n batch_shape=batch_shape, validate_args=validate_args\n )\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n shape = sample_shape + self.batch_shape + self.event_shape\n return random.gamma(key, self.concentration, shape=shape) / self.rate\n\n @validate_sample\n def log_prob(self, value):\n normalize_term = gammaln(self.concentration) - self.concentration * jnp.log(\n self.rate\n )\n return (\n (self.concentration - 1) * jnp.log(value)\n - self.rate * value\n - normalize_term\n )\n\n @property\n def mean(self):\n return self.concentration / self.rate\n\n @property\n def variance(self):\n return self.concentration / jnp.power(self.rate, 2)\n\n def cdf(self, x):\n return gammainc(self.concentration, self.rate * x)\n\n def icdf(self, q):\n return gammaincinv(self.concentration, q) / self.rate\n\n\nclass Chi2(Gamma):\n arg_constraints = {\"df\": constraints.positive}\n reparametrized_params = [\"df\"]\n\n def __init__(self, df, *, validate_args=None):\n self.df = df\n super(Chi2, self).__init__(0.5 * df, 0.5, validate_args=validate_args)\n\n\nclass GaussianRandomWalk(Distribution):\n arg_constraints = {\"scale\": constraints.positive}\n support = constraints.real_vector\n reparametrized_params = [\"scale\"]\n\n def __init__(self, scale=1.0, num_steps=1, *, validate_args=None):\n assert (\n isinstance(num_steps, int) and num_steps > 0\n ), \"`num_steps` argument should be an positive integer.\"\n self.scale = scale\n self.num_steps = num_steps\n batch_shape, event_shape = jnp.shape(scale), (num_steps,)\n super(GaussianRandomWalk, self).__init__(\n batch_shape, event_shape, validate_args=validate_args\n )\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n shape = sample_shape + self.batch_shape + self.event_shape\n walks = random.normal(key, shape=shape)\n return jnp.cumsum(walks, axis=-1) * jnp.expand_dims(self.scale, axis=-1)\n\n @validate_sample\n def log_prob(self, value):\n init_prob = Normal(0.0, self.scale).log_prob(value[..., 0])\n scale = jnp.expand_dims(self.scale, -1)\n step_probs = Normal(value[..., :-1], scale).log_prob(value[..., 1:])\n return init_prob + jnp.sum(step_probs, axis=-1)\n\n @property\n def mean(self):\n return jnp.zeros(self.batch_shape + self.event_shape)\n\n @property\n def variance(self):\n return jnp.broadcast_to(\n jnp.expand_dims(self.scale, -1) ** 2 * jnp.arange(1, self.num_steps + 1),\n self.batch_shape + self.event_shape,\n )\n\n def tree_flatten(self):\n return (self.scale,), self.num_steps\n\n @classmethod\n def tree_unflatten(cls, aux_data, params):\n return cls(*params, num_steps=aux_data)\n\n\nclass HalfCauchy(Distribution):\n reparametrized_params = [\"scale\"]\n support = constraints.positive\n arg_constraints = {\"scale\": constraints.positive}\n\n def __init__(self, scale=1.0, *, validate_args=None):\n self._cauchy = Cauchy(0.0, scale)\n self.scale = scale\n super(HalfCauchy, self).__init__(\n batch_shape=jnp.shape(scale), validate_args=validate_args\n )\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n return jnp.abs(self._cauchy.sample(key, sample_shape))\n\n @validate_sample\n def log_prob(self, value):\n return self._cauchy.log_prob(value) + jnp.log(2)\n\n def cdf(self, value):\n return self._cauchy.cdf(value) * 2 - 1\n\n def icdf(self, q):\n return self._cauchy.icdf((q + 1) / 2)\n\n @property\n def mean(self):\n return jnp.full(self.batch_shape, jnp.inf)\n\n @property\n def variance(self):\n return jnp.full(self.batch_shape, jnp.inf)\n\n\nclass HalfNormal(Distribution):\n reparametrized_params = [\"scale\"]\n support = constraints.positive\n arg_constraints = {\"scale\": constraints.positive}\n\n def __init__(self, scale=1.0, *, validate_args=None):\n self._normal = Normal(0.0, scale)\n self.scale = scale\n super(HalfNormal, self).__init__(\n batch_shape=jnp.shape(scale), validate_args=validate_args\n )\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n return jnp.abs(self._normal.sample(key, sample_shape))\n\n @validate_sample\n def log_prob(self, value):\n return self._normal.log_prob(value) + jnp.log(2)\n\n def cdf(self, value):\n return self._normal.cdf(value) * 2 - 1\n\n def icdf(self, q):\n return self._normal.icdf((q + 1) / 2)\n\n @property\n def mean(self):\n return jnp.sqrt(2 / jnp.pi) * self.scale\n\n @property\n def variance(self):\n return (1 - 2 / jnp.pi) * self.scale**2\n\n\nclass InverseGamma(TransformedDistribution):\n \"\"\"\n .. note:: We keep the same notation `rate` as in Pyro but\n it plays the role of scale parameter of InverseGamma in literatures\n (e.g. wikipedia: https://en.wikipedia.org/wiki/Inverse-gamma_distribution)\n \"\"\"\n\n arg_constraints = {\n \"concentration\": constraints.positive,\n \"rate\": constraints.positive,\n }\n reparametrized_params = [\"concentration\", \"rate\"]\n support = constraints.positive\n\n def __init__(self, concentration, rate=1.0, *, validate_args=None):\n base_dist = Gamma(concentration, rate)\n self.concentration = base_dist.concentration\n self.rate = base_dist.rate\n super(InverseGamma, self).__init__(\n base_dist, PowerTransform(-1.0), validate_args=validate_args\n )\n\n @property\n def mean(self):\n # mean is inf for alpha <= 1\n a = self.rate / (self.concentration - 1)\n return jnp.where(self.concentration <= 1, jnp.inf, a)\n\n @property\n def variance(self):\n # var is inf for alpha <= 2\n a = (self.rate / (self.concentration - 1)) ** 2 / (self.concentration - 2)\n return jnp.where(self.concentration <= 2, jnp.inf, a)\n\n def tree_flatten(self):\n return super(TransformedDistribution, self).tree_flatten()\n\n def cdf(self, x):\n return 1 - self.base_dist.cdf(1 / x)\n\n\nclass Gompertz(Distribution):\n r\"\"\"Gompertz Distribution.\n\n The Gompertz distribution is a distribution with support on the positive real line that is closely\n related to the Gumbel distribution. This implementation follows the notation used in the Wikipedia\n entry for the Gompertz distribution. See https://en.wikipedia.org/wiki/Gompertz_distribution.\n\n However, we call the parameter \"eta\" a concentration parameter and the parameter\n \"b\" a rate parameter (as opposed to scale parameter as in wikipedia description.)\n\n The CDF, in terms of `concentration` (`con`) and `rate`, is\n\n .. math::\n F(x) = 1 - \\exp \\left\\{ - \\text{con} * \\left [ \\exp\\{x * rate \\} - 1 \\right ] \\right\\}\n \"\"\"\n\n arg_constraints = {\n \"concentration\": constraints.positive,\n \"rate\": constraints.positive,\n }\n support = constraints.positive\n reparametrized_params = [\"concentration\", \"rate\"]\n\n def __init__(self, concentration, rate=1.0, *, validate_args=None):\n self.concentration, self.rate = promote_shapes(concentration, rate)\n super(Gompertz, self).__init__(\n batch_shape=lax.broadcast_shapes(jnp.shape(concentration), jnp.shape(rate)),\n validate_args=validate_args,\n )\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n random_shape = sample_shape + self.batch_shape + self.event_shape\n unifs = random.uniform(key, shape=random_shape)\n return self.icdf(unifs)\n\n @validate_sample\n def log_prob(self, value):\n scaled_value = value * self.rate\n return (\n jnp.log(self.concentration)\n + jnp.log(self.rate)\n + scaled_value\n - self.concentration * jnp.expm1(scaled_value)\n )\n\n def cdf(self, value):\n return -jnp.expm1(-self.concentration * jnp.expm1(value * self.rate))\n\n def icdf(self, q):\n return jnp.log1p(-jnp.log1p(-q) / self.concentration) / self.rate\n\n @property\n def mean(self):\n return -jnp.exp(self.concentration) * expi(-self.concentration) / self.rate\n\n\nclass Gumbel(Distribution):\n arg_constraints = {\"loc\": constraints.real, \"scale\": constraints.positive}\n support = constraints.real\n reparametrized_params = [\"loc\", \"scale\"]\n\n def __init__(self, loc=0.0, scale=1.0, *, validate_args=None):\n self.loc, self.scale = promote_shapes(loc, scale)\n batch_shape = lax.broadcast_shapes(jnp.shape(loc), jnp.shape(scale))\n\n super(Gumbel, self).__init__(\n batch_shape=batch_shape, validate_args=validate_args\n )\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n standard_gumbel_sample = random.gumbel(\n key, shape=sample_shape + self.batch_shape + self.event_shape\n )\n return self.loc + self.scale * standard_gumbel_sample\n\n @validate_sample\n def log_prob(self, value):\n z = (value - self.loc) / self.scale\n return -(z + jnp.exp(-z)) - jnp.log(self.scale)\n\n @property\n def mean(self):\n return jnp.broadcast_to(\n self.loc + self.scale * jnp.euler_gamma, self.batch_shape\n )\n\n @property\n def variance(self):\n return jnp.broadcast_to(jnp.pi**2 / 6.0 * self.scale**2, self.batch_shape)\n\n def cdf(self, value):\n return jnp.exp(-jnp.exp((self.loc - value) / self.scale))\n\n def icdf(self, q):\n return self.loc - self.scale * jnp.log(-jnp.log(q))\n\n\nclass Kumaraswamy(TransformedDistribution):\n arg_constraints = {\n \"concentration1\": constraints.positive,\n \"concentration0\": constraints.positive,\n }\n reparametrized_params = [\"concentration1\", \"concentration0\"]\n support = constraints.unit_interval\n # XXX: This flag is used to approximate the Taylor expansion\n # of KL(Kumaraswamy||Beta) following\n # https://arxiv.org/abs/1605.06197 Formula (12)\n # We follow the paper and set this to 10 but to get more precise KL,\n # we can set this flag to 1000.\n KL_KUMARASWAMY_BETA_TAYLOR_ORDER = 10\n\n def __init__(self, concentration1, concentration0, *, validate_args=None):\n self.concentration1, self.concentration0 = promote_shapes(\n concentration1, concentration0\n )\n batch_shape = lax.broadcast_shapes(\n jnp.shape(concentration1), jnp.shape(concentration0)\n )\n base_dist = Uniform(0, 1).expand(batch_shape)\n transforms = [\n PowerTransform(1 / concentration0),\n AffineTransform(1, -1),\n PowerTransform(1 / concentration1),\n ]\n super().__init__(base_dist, transforms, validate_args=validate_args)\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n minval = jnp.finfo(jnp.result_type(float)).tiny\n u = random.uniform(key, shape=sample_shape + self.batch_shape, minval=minval)\n log_sample = jnp.log1p(-(u ** (1 / self.concentration0))) / self.concentration1\n finfo = jnp.finfo(u)\n return jnp.clip(jnp.exp(log_sample), a_min=finfo.tiny, a_max=1 - finfo.eps)\n\n @validate_sample\n def log_prob(self, value):\n normalize_term = jnp.log(self.concentration0) + jnp.log(self.concentration1)\n return (\n xlogy(self.concentration1 - 1, value)\n + xlog1py(self.concentration0 - 1, -(value**self.concentration1))\n + normalize_term\n )\n\n @property\n def mean(self):\n log_beta = betaln(1 + 1 / self.concentration1, self.concentration0)\n return self.concentration0 * jnp.exp(log_beta)\n\n @property\n def variance(self):\n log_beta = betaln(1 + 2 / self.concentration1, self.concentration0)\n return self.concentration0 * jnp.exp(log_beta) - jnp.square(self.mean)\n\n def tree_flatten(self):\n return super(TransformedDistribution, self).tree_flatten()\n\n\nclass Laplace(Distribution):\n arg_constraints = {\"loc\": constraints.real, \"scale\": constraints.positive}\n support = constraints.real\n reparametrized_params = [\"loc\", \"scale\"]\n\n def __init__(self, loc=0.0, scale=1.0, *, validate_args=None):\n self.loc, self.scale = promote_shapes(loc, scale)\n batch_shape = lax.broadcast_shapes(jnp.shape(loc), jnp.shape(scale))\n super(Laplace, self).__init__(\n batch_shape=batch_shape, validate_args=validate_args\n )\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n eps = random.laplace(\n key, shape=sample_shape + self.batch_shape + self.event_shape\n )\n return self.loc + eps * self.scale\n\n @validate_sample\n def log_prob(self, value):\n normalize_term = jnp.log(2 * self.scale)\n value_scaled = jnp.abs(value - self.loc) / self.scale\n return -value_scaled - normalize_term\n\n @property\n def mean(self):\n return jnp.broadcast_to(self.loc, self.batch_shape)\n\n @property\n def variance(self):\n return jnp.broadcast_to(2 * self.scale**2, self.batch_shape)\n\n def cdf(self, value):\n scaled = (value - self.loc) / self.scale\n return 0.5 - 0.5 * jnp.sign(scaled) * jnp.expm1(-jnp.abs(scaled))\n\n def icdf(self, q):\n a = q - 0.5\n return self.loc - self.scale * jnp.sign(a) * jnp.log1p(-2 * jnp.abs(a))\n\n\nclass LKJ(TransformedDistribution):\n r\"\"\"\n LKJ distribution for correlation matrices. The distribution is controlled by ``concentration``\n parameter :math:`\\eta` to make the probability of the correlation matrix :math:`M` proportional\n to :math:`\\det(M)^{\\eta - 1}`. Because of that, when ``concentration == 1``, we have a\n uniform distribution over correlation matrices.\n\n When ``concentration > 1``, the distribution favors samples with large large determinent. This\n is useful when we know a priori that the underlying variables are not correlated.\n\n When ``concentration < 1``, the distribution favors samples with small determinent. This is\n useful when we know a priori that some underlying variables are correlated.\n\n Sample code for using LKJ in the context of multivariate normal sample::\n\n def model(y): # y has dimension N x d\n d = y.shape[1]\n N = y.shape[0]\n # Vector of variances for each of the d variables\n theta = numpyro.sample(\"theta\", dist.HalfCauchy(jnp.ones(d)))\n\n concentration = jnp.ones(1) # Implies a uniform distribution over correlation matrices\n corr_mat = numpyro.sample(\"corr_mat\", dist.LKJ(d, concentration))\n sigma = jnp.sqrt(theta)\n # we can also use a faster formula `cov_mat = jnp.outer(theta, theta) * corr_mat`\n cov_mat = jnp.matmul(jnp.matmul(jnp.diag(sigma), corr_mat), jnp.diag(sigma))\n\n # Vector of expectations\n mu = jnp.zeros(d)\n\n with numpyro.plate(\"observations\", N):\n obs = numpyro.sample(\"obs\", dist.MultivariateNormal(mu, covariance_matrix=cov_mat), obs=y)\n return obs\n\n :param int dimension: dimension of the matrices\n :param ndarray concentration: concentration/shape parameter of the\n distribution (often referred to as eta)\n :param str sample_method: Either \"cvine\" or \"onion\". Both methods are proposed in [1] and\n offer the same distribution over correlation matrices. But they are different in how\n to generate samples. Defaults to \"onion\".\n\n **References**\n\n [1] `Generating random correlation matrices based on vines and extended onion method`,\n Daniel Lewandowski, Dorota Kurowicka, Harry Joe\n \"\"\"\n arg_constraints = {\"concentration\": constraints.positive}\n reparametrized_params = [\"concentration\"]\n support = constraints.corr_matrix\n\n def __init__(\n self, dimension, concentration=1.0, sample_method=\"onion\", *, validate_args=None\n ):\n base_dist = LKJCholesky(dimension, concentration, sample_method)\n self.dimension, self.concentration = (\n base_dist.dimension,\n base_dist.concentration,\n )\n self.sample_method = sample_method\n super(LKJ, self).__init__(\n base_dist, CorrMatrixCholeskyTransform().inv, validate_args=validate_args\n )\n\n @property\n def mean(self):\n return jnp.broadcast_to(\n jnp.identity(self.dimension),\n self.batch_shape + (self.dimension, self.dimension),\n )\n\n def tree_flatten(self):\n return (self.concentration,), (self.dimension, self.sample_method)\n\n @classmethod\n def tree_unflatten(cls, aux_data, params):\n dimension, sample_method = aux_data\n return cls(dimension, *params, sample_method=sample_method)\n\n\nclass LKJCholesky(Distribution):\n r\"\"\"\n LKJ distribution for lower Cholesky factors of correlation matrices. The distribution is\n controlled by ``concentration`` parameter :math:`\\eta` to make the probability of the\n correlation matrix :math:`M` generated from a Cholesky factor propotional to\n :math:`\\det(M)^{\\eta - 1}`. Because of that, when ``concentration == 1``, we have a\n uniform distribution over Cholesky factors of correlation matrices.\n\n When ``concentration > 1``, the distribution favors samples with large diagonal entries\n (hence large determinent). This is useful when we know a priori that the underlying\n variables are not correlated.\n\n When ``concentration < 1``, the distribution favors samples with small diagonal entries\n (hence small determinent). This is useful when we know a priori that some underlying\n variables are correlated.\n\n Sample code for using LKJCholesky in the context of multivariate normal sample::\n\n def model(y): # y has dimension N x d\n d = y.shape[1]\n N = y.shape[0]\n # Vector of variances for each of the d variables\n theta = numpyro.sample(\"theta\", dist.HalfCauchy(jnp.ones(d)))\n # Lower cholesky factor of a correlation matrix\n concentration = jnp.ones(1) # Implies a uniform distribution over correlation matrices\n L_omega = numpyro.sample(\"L_omega\", dist.LKJCholesky(d, concentration))\n # Lower cholesky factor of the covariance matrix\n sigma = jnp.sqrt(theta)\n # we can also use a faster formula `L_Omega = sigma[..., None] * L_omega`\n L_Omega = jnp.matmul(jnp.diag(sigma), L_omega)\n\n # Vector of expectations\n mu = jnp.zeros(d)\n\n with numpyro.plate(\"observations\", N):\n obs = numpyro.sample(\"obs\", dist.MultivariateNormal(mu, scale_tril=L_Omega), obs=y)\n return obs\n\n :param int dimension: dimension of the matrices\n :param ndarray concentration: concentration/shape parameter of the\n distribution (often referred to as eta)\n :param str sample_method: Either \"cvine\" or \"onion\". Both methods are proposed in [1] and\n offer the same distribution over correlation matrices. But they are different in how\n to generate samples. Defaults to \"onion\".\n\n **References**\n\n [1] `Generating random correlation matrices based on vines and extended onion method`,\n Daniel Lewandowski, Dorota Kurowicka, Harry Joe\n \"\"\"\n arg_constraints = {\"concentration\": constraints.positive}\n reparametrized_params = [\"concentration\"]\n support = constraints.corr_cholesky\n\n def __init__(\n self, dimension, concentration=1.0, sample_method=\"onion\", *, validate_args=None\n ):\n if dimension < 2:\n raise ValueError(\"Dimension must be greater than or equal to 2.\")\n self.dimension = dimension\n self.concentration = concentration\n batch_shape = jnp.shape(concentration)\n event_shape = (dimension, dimension)\n\n # We construct base distributions to generate samples for each method.\n # The purpose of this base distribution is to generate a distribution for\n # correlation matrices which is propotional to `det(M)^{\\eta - 1}`.\n # (note that this is not a unique way to define base distribution)\n # Both of the following methods have marginal distribution of each off-diagonal\n # element of sampled correlation matrices is Beta(eta + (D-2) / 2, eta + (D-2) / 2)\n # (up to a linear transform: x -> 2x - 1)\n Dm1 = self.dimension - 1\n marginal_concentration = concentration + 0.5 * (self.dimension - 2)\n offset = 0.5 * jnp.arange(Dm1)\n if sample_method == \"onion\":\n # The following construction follows from the algorithm in Section 3.2 of [1]:\n # NB: in [1], the method for case k > 1 can also work for the case k = 1.\n beta_concentration0 = (\n jnp.expand_dims(marginal_concentration, axis=-1) - offset\n )\n beta_concentration1 = offset + 0.5\n self._beta = Beta(beta_concentration1, beta_concentration0)\n elif sample_method == \"cvine\":\n # The following construction follows from the algorithm in Section 2.4 of [1]:\n # offset_tril is [0, 1, 1, 2, 2, 2,...] / 2\n offset_tril = matrix_to_tril_vec(jnp.broadcast_to(offset, (Dm1, Dm1)))\n beta_concentration = (\n jnp.expand_dims(marginal_concentration, axis=-1) - offset_tril\n )\n self._beta = Beta(beta_concentration, beta_concentration)\n else:\n raise ValueError(\"`method` should be one of 'cvine' or 'onion'.\")\n self.sample_method = sample_method\n\n super(LKJCholesky, self).__init__(\n batch_shape=batch_shape,\n event_shape=event_shape,\n validate_args=validate_args,\n )\n\n def _cvine(self, key, size):\n # C-vine method first uses beta_dist to generate partial correlations,\n # then apply signed stick breaking to transform to cholesky factor.\n # Here is an attempt to prove that using signed stick breaking to\n # generate correlation matrices is the same as the C-vine method in [1]\n # for the entry r_32.\n #\n # With notations follow from [1], we define\n # p: partial correlation matrix,\n # c: cholesky factor,\n # r: correlation matrix.\n # From recursive formula (2) in [1], we have\n # r_32 = p_32 * sqrt{(1 - p_21^2)*(1 - p_31^2)} + p_21 * p_31 =: I\n # On the other hand, signed stick breaking process gives:\n # l_21 = p_21, l_31 = p_31, l_22 = sqrt(1 - p_21^2), l_32 = p_32 * sqrt(1 - p_31^2)\n # r_32 = l_21 * l_31 + l_22 * l_32\n # = p_21 * p_31 + p_32 * sqrt{(1 - p_21^2)*(1 - p_31^2)} = I\n beta_sample = self._beta.sample(key, size)\n partial_correlation = 2 * beta_sample - 1 # scale to domain to (-1, 1)\n return signed_stick_breaking_tril(partial_correlation)\n\n def _onion(self, key, size):\n key_beta, key_normal = random.split(key)\n # Now we generate w term in Algorithm 3.2 of [1].\n beta_sample = self._beta.sample(key_beta, size)\n # The following Normal distribution is used to create a uniform distribution on\n # a hypershere (ref: http://mathworld.wolfram.com/HyperspherePointPicking.html)\n normal_sample = random.normal(\n key_normal,\n shape=size\n + self.batch_shape\n + (self.dimension * (self.dimension - 1) // 2,),\n )\n normal_sample = vec_to_tril_matrix(normal_sample, diagonal=0)\n u_hypershere = normal_sample / jnp.linalg.norm(\n normal_sample, axis=-1, keepdims=True\n )\n w = jnp.expand_dims(jnp.sqrt(beta_sample), axis=-1) * u_hypershere\n\n # put w into the off-diagonal triangular part\n cholesky = jnp.zeros(size + self.batch_shape + self.event_shape)\n cholesky = cholesky.at[..., 1:, :-1].set(w)\n # correct the diagonal\n # NB: beta_sample = sum(w ** 2) because norm 2 of u is 1.\n diag = jnp.ones(cholesky.shape[:-1]).at[..., 1:].set(jnp.sqrt(1 - beta_sample))\n cholesky = cholesky + jnp.expand_dims(diag, axis=-1) * jnp.identity(\n self.dimension\n )\n return cholesky\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n if self.sample_method == \"onion\":\n return self._onion(key, sample_shape)\n else:\n return self._cvine(key, sample_shape)\n\n @validate_sample\n def log_prob(self, value):\n # Note about computing Jacobian of the transformation from Cholesky factor to\n # correlation matrix:\n #\n # Assume C = L@Lt and L = (1 0 0; a \\sqrt(1-a^2) 0; b c \\sqrt(1-b^2-c^2)), we have\n # Then off-diagonal lower triangular vector of L is transformed to the off-diagonal\n # lower triangular vector of C by the transform:\n # (a, b, c) -> (a, b, ab + c\\sqrt(1-a^2))\n # Hence, Jacobian = 1 * 1 * \\sqrt(1 - a^2) = \\sqrt(1 - a^2) = L22, where L22\n # is the 2th diagonal element of L\n # Generally, for a D dimensional matrix, we have:\n # Jacobian = L22^(D-2) * L33^(D-3) * ... * Ldd^0\n #\n # From [1], we know that probability of a correlation matrix is propotional to\n # determinant ** (concentration - 1) = prod(L_ii ^ 2(concentration - 1))\n # On the other hand, Jabobian of the transformation from Cholesky factor to\n # correlation matrix is:\n # prod(L_ii ^ (D - i))\n # So the probability of a Cholesky factor is propotional to\n # prod(L_ii ^ (2 * concentration - 2 + D - i)) =: prod(L_ii ^ order_i)\n # with order_i = 2 * concentration - 2 + D - i,\n # i = 2..D (we omit the element i = 1 because L_11 = 1)\n\n # Compute `order` vector (note that we need to reindex i -> i-2):\n one_to_D = jnp.arange(1, self.dimension)\n order_offset = (3 - self.dimension) + one_to_D\n order = 2 * jnp.expand_dims(self.concentration, axis=-1) - order_offset\n\n # Compute unnormalized log_prob:\n value_diag = jnp.asarray(value)[..., one_to_D, one_to_D]\n unnormalized = jnp.sum(order * jnp.log(value_diag), axis=-1)\n\n # Compute normalization constant (on the first proof of page 1999 of [1])\n Dm1 = self.dimension - 1\n alpha = self.concentration + 0.5 * Dm1\n denominator = gammaln(alpha) * Dm1\n numerator = multigammaln(alpha - 0.5, Dm1)\n # pi_constant in [1] is D * (D - 1) / 4 * log(pi)\n # pi_constant in multigammaln is (D - 1) * (D - 2) / 4 * log(pi)\n # hence, we need to add a pi_constant = (D - 1) * log(pi) / 2\n pi_constant = 0.5 * Dm1 * jnp.log(jnp.pi)\n normalize_term = pi_constant + numerator - denominator\n return unnormalized - normalize_term\n\n def tree_flatten(self):\n return (self.concentration,), (self.dimension, self.sample_method)\n\n @classmethod\n def tree_unflatten(cls, aux_data, params):\n dimension, sample_method = aux_data\n return cls(dimension, *params, sample_method=sample_method)\n\n\nclass LogNormal(TransformedDistribution):\n arg_constraints = {\"loc\": constraints.real, \"scale\": constraints.positive}\n support = constraints.positive\n reparametrized_params = [\"loc\", \"scale\"]\n\n def __init__(self, loc=0.0, scale=1.0, *, validate_args=None):\n base_dist = Normal(loc, scale)\n self.loc, self.scale = base_dist.loc, base_dist.scale\n super(LogNormal, self).__init__(\n base_dist, ExpTransform(), validate_args=validate_args\n )\n\n @property\n def mean(self):\n return jnp.exp(self.loc + self.scale**2 / 2)\n\n @property\n def variance(self):\n return (jnp.exp(self.scale**2) - 1) * jnp.exp(2 * self.loc + self.scale**2)\n\n def tree_flatten(self):\n return super(TransformedDistribution, self).tree_flatten()\n\n def cdf(self, x):\n return self.base_dist.cdf(jnp.log(x))\n\n\nclass Logistic(Distribution):\n arg_constraints = {\"loc\": constraints.real, \"scale\": constraints.positive}\n support = constraints.real\n reparametrized_params = [\"loc\", \"scale\"]\n\n def __init__(self, loc=0.0, scale=1.0, *, validate_args=None):\n self.loc, self.scale = promote_shapes(loc, scale)\n batch_shape = lax.broadcast_shapes(jnp.shape(loc), jnp.shape(scale))\n super(Logistic, self).__init__(batch_shape, validate_args=validate_args)\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n z = random.logistic(\n key, shape=sample_shape + self.batch_shape + self.event_shape\n )\n return self.loc + z * self.scale\n\n @validate_sample\n def log_prob(self, value):\n log_exponent = (self.loc - value) / self.scale\n log_denominator = jnp.log(self.scale) + 2 * nn.softplus(log_exponent)\n return log_exponent - log_denominator\n\n @property\n def mean(self):\n return jnp.broadcast_to(self.loc, self.batch_shape)\n\n @property\n def variance(self):\n var = (self.scale**2) * (jnp.pi**2) / 3\n return jnp.broadcast_to(var, self.batch_shape)\n\n def cdf(self, value):\n scaled = (value - self.loc) / self.scale\n return expit(scaled)\n\n def icdf(self, q):\n return self.loc + self.scale * logit(q)\n\n\nclass LogUniform(TransformedDistribution):\n arg_constraints = {\"low\": constraints.positive, \"high\": constraints.positive}\n reparametrized_params = [\"low\", \"high\"]\n\n def __init__(self, low, high, *, validate_args=None):\n base_dist = Uniform(jnp.log(low), jnp.log(high))\n self.low, self.high = promote_shapes(low, high)\n self._support = constraints.interval(self.low, self.high)\n super(LogUniform, self).__init__(\n base_dist, ExpTransform(), validate_args=validate_args\n )\n\n @constraints.dependent_property(is_discrete=False, event_dim=0)\n def support(self):\n return self._support\n\n @property\n def mean(self):\n return (self.high - self.low) / jnp.log(self.high / self.low)\n\n @property\n def variance(self):\n return (\n 0.5 * (self.high**2 - self.low**2) / jnp.log(self.high / self.low)\n - self.mean**2\n )\n\n def tree_flatten(self):\n return super(TransformedDistribution, self).tree_flatten()\n\n def cdf(self, x):\n return self.base_dist.cdf(jnp.log(x))\n\n\ndef _batch_solve_triangular(A, B):\n \"\"\"\n Extende solve_triangular for the case that B.ndim > A.ndim.\n This is achived by first flattening the leading B.ndim - A.ndim dimensions of B and then\n moving the first dimension to the end.\n\n\n :param jnp.ndarray (...,M,M) A: An array with lower triangular structure in the last two dimensions.\n :param jnp.ndarray (...,M,N) B: Right-hand side matrix in A x = B.\n\n :return: Solution of A x = B.\n \"\"\"\n event_shape = B.shape[-2:]\n batch_shape = lax.broadcast_shapes(A.shape[:-2], B.shape[-A.ndim : -2])\n sample_shape = B.shape[: -A.ndim]\n n, p = event_shape\n\n A = jnp.broadcast_to(A, batch_shape + A.shape[-2:])\n B = jnp.broadcast_to(B, sample_shape + batch_shape + event_shape)\n\n B_flat = jnp.moveaxis(B.reshape((-1,) + batch_shape + event_shape), 0, -2).reshape(\n batch_shape + (n,) + (-1,)\n )\n\n X_flat = solve_triangular(A, B_flat, lower=True)\n\n sample_shape_dim = len(sample_shape)\n src_axes = tuple([-2 - i for i in range(sample_shape_dim)])\n src_axes = src_axes[::-1]\n dest_axes = tuple([i for i in range(sample_shape_dim)])\n\n X = jnp.moveaxis(\n X_flat.reshape(batch_shape + (n,) + sample_shape + (p,)),\n src_axes,\n dest_axes,\n )\n return X\n\n\nclass MatrixNormal(Distribution):\n \"\"\"\n Matrix variate normal distribution as described in [1] but with a lower_triangular parametrization,\n i.e. :math:`U=scale_tril_row @ scale_tril_row^{T}` and :math:`V=scale_tril_column @ scale_tril_column^{T}`.\n The distribution is related to the multivariate normal distribution in the following way.\n If :math:`X ~ MN(loc,U,V)` then :math:`vec(X) ~ MVN(vec(loc), kron(V,U) )`.\n\n :param array_like loc: Location of the distribution.\n :param array_like scale_tril_row: Lower cholesky of rows correlation matrix.\n :param array_like scale_tril_column: Lower cholesky of columns correlation matrix.\n\n **References**\n\n [1] https://en.wikipedia.org/wiki/Matrix_normal_distribution\n \"\"\"\n\n arg_constraints = {\n \"loc\": constraints.real_vector,\n \"scale_tril_row\": constraints.lower_cholesky,\n \"scale_tril_column\": constraints.lower_cholesky,\n }\n support = constraints.real_matrix\n reparametrized_params = [\n \"loc\",\n \"scale_tril_row\",\n \"scale_tril_column\",\n ]\n\n def __init__(self, loc, scale_tril_row, scale_tril_column, validate_args=None):\n event_shape = loc.shape[-2:]\n batch_shape = lax.broadcast_shapes(\n jnp.shape(loc)[:-2],\n jnp.shape(scale_tril_row)[:-2],\n jnp.shape(scale_tril_column)[:-2],\n )\n (self.loc,) = promote_shapes(loc, shape=batch_shape + loc.shape[-2:])\n (self.scale_tril_row,) = promote_shapes(\n scale_tril_row, shape=batch_shape + scale_tril_row.shape[-2:]\n )\n (self.scale_tril_column,) = promote_shapes(\n scale_tril_column, shape=batch_shape + scale_tril_column.shape[-2:]\n )\n super(MatrixNormal, self).__init__(\n batch_shape=batch_shape,\n event_shape=event_shape,\n validate_args=validate_args,\n )\n\n @property\n def mean(self):\n return jnp.broadcast_to(self.loc, self.shape())\n\n def sample(self, key, sample_shape=()):\n eps = random.normal(\n key, shape=sample_shape + self.batch_shape + self.event_shape\n )\n samples = self.loc + self.scale_tril_row @ eps @ jnp.swapaxes(\n self.scale_tril_column, -2, -1\n )\n\n return samples\n\n @validate_sample\n def log_prob(self, values):\n n, p = self.event_shape\n\n row_log_det = jnp.log(\n jnp.diagonal(self.scale_tril_row, axis1=-2, axis2=-1)\n ).sum(-1)\n col_log_det = jnp.log(\n jnp.diagonal(self.scale_tril_column, axis1=-2, axis2=-1)\n ).sum(-1)\n log_det_term = (\n p * row_log_det + n * col_log_det + 0.5 * n * p * jnp.log(2 * jnp.pi)\n )\n\n # compute the trace term\n diff = values - self.loc\n diff_row_solve = _batch_solve_triangular(A=self.scale_tril_row, B=diff)\n diff_col_solve = _batch_solve_triangular(\n A=self.scale_tril_column, B=jnp.swapaxes(diff_row_solve, -2, -1)\n )\n batched_trace_term = jnp.square(\n diff_col_solve.reshape(diff_col_solve.shape[:-2] + (-1,))\n ).sum(-1)\n\n log_prob = -0.5 * batched_trace_term - log_det_term\n\n return log_prob\n\n\ndef _batch_mahalanobis(bL, bx):\n if bL.shape[:-1] == bx.shape:\n # no need to use the below optimization procedure\n solve_bL_bx = solve_triangular(bL, bx[..., None], lower=True).squeeze(-1)\n return jnp.sum(jnp.square(solve_bL_bx), -1)\n\n # NB: The following procedure handles the case: bL.shape = (i, 1, n, n), bx.shape = (i, j, n)\n # because we don't want to broadcast bL to the shape (i, j, n, n).\n\n # Assume that bL.shape = (i, 1, n, n), bx.shape = (..., i, j, n),\n # we are going to make bx have shape (..., 1, j, i, 1, n) to apply batched tril_solve\n sample_ndim = bx.ndim - bL.ndim + 1 # size of sample_shape\n out_shape = jnp.shape(bx)[:-1] # shape of output\n # Reshape bx with the shape (..., 1, i, j, 1, n)\n bx_new_shape = out_shape[:sample_ndim]\n for sL, sx in zip(bL.shape[:-2], out_shape[sample_ndim:]):\n bx_new_shape += (sx // sL, sL)\n bx_new_shape += (-1,)\n bx = jnp.reshape(bx, bx_new_shape)\n # Permute bx to make it have shape (..., 1, j, i, 1, n)\n permute_dims = (\n tuple(range(sample_ndim))\n + tuple(range(sample_ndim, bx.ndim - 1, 2))\n + tuple(range(sample_ndim + 1, bx.ndim - 1, 2))\n + (bx.ndim - 1,)\n )\n bx = jnp.transpose(bx, permute_dims)\n\n # reshape to (-1, i, 1, n)\n xt = jnp.reshape(bx, (-1,) + bL.shape[:-1])\n # permute to (i, 1, n, -1)\n xt = jnp.moveaxis(xt, 0, -1)\n solve_bL_bx = solve_triangular(bL, xt, lower=True) # shape: (i, 1, n, -1)\n M = jnp.sum(solve_bL_bx**2, axis=-2) # shape: (i, 1, -1)\n # permute back to (-1, i, 1)\n M = jnp.moveaxis(M, -1, 0)\n # reshape back to (..., 1, j, i, 1)\n M = jnp.reshape(M, bx.shape[:-1])\n # permute back to (..., 1, i, j, 1)\n permute_inv_dims = tuple(range(sample_ndim))\n for i in range(bL.ndim - 2):\n permute_inv_dims += (sample_ndim + i, len(out_shape) + i)\n M = jnp.transpose(M, permute_inv_dims)\n return jnp.reshape(M, out_shape)\n\n\nclass MultivariateNormal(Distribution):\n arg_constraints = {\n \"loc\": constraints.real_vector,\n \"covariance_matrix\": constraints.positive_definite,\n \"precision_matrix\": constraints.positive_definite,\n \"scale_tril\": constraints.lower_cholesky,\n }\n support = constraints.real_vector\n reparametrized_params = [\n \"loc\",\n \"covariance_matrix\",\n \"precision_matrix\",\n \"scale_tril\",\n ]\n\n def __init__(\n self,\n loc=0.0,\n covariance_matrix=None,\n precision_matrix=None,\n scale_tril=None,\n validate_args=None,\n ):\n if jnp.ndim(loc) == 0:\n (loc,) = promote_shapes(loc, shape=(1,))\n # temporary append a new axis to loc\n loc = loc[..., jnp.newaxis]\n if covariance_matrix is not None:\n loc, self.covariance_matrix = promote_shapes(loc, covariance_matrix)\n self.scale_tril = jnp.linalg.cholesky(self.covariance_matrix)\n elif precision_matrix is not None:\n loc, self.precision_matrix = promote_shapes(loc, precision_matrix)\n self.scale_tril = cholesky_of_inverse(self.precision_matrix)\n elif scale_tril is not None:\n loc, self.scale_tril = promote_shapes(loc, scale_tril)\n else:\n raise ValueError(\n \"One of `covariance_matrix`, `precision_matrix`, `scale_tril`\"\n \" must be specified.\"\n )\n batch_shape = lax.broadcast_shapes(\n jnp.shape(loc)[:-2], jnp.shape(self.scale_tril)[:-2]\n )\n event_shape = jnp.shape(self.scale_tril)[-1:]\n self.loc = loc[..., 0]\n super(MultivariateNormal, self).__init__(\n batch_shape=batch_shape,\n event_shape=event_shape,\n validate_args=validate_args,\n )\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n eps = random.normal(\n key, shape=sample_shape + self.batch_shape + self.event_shape\n )\n return self.loc + jnp.squeeze(\n jnp.matmul(self.scale_tril, eps[..., jnp.newaxis]), axis=-1\n )\n\n @validate_sample\n def log_prob(self, value):\n M = _batch_mahalanobis(self.scale_tril, value - self.loc)\n half_log_det = jnp.log(jnp.diagonal(self.scale_tril, axis1=-2, axis2=-1)).sum(\n -1\n )\n normalize_term = half_log_det + 0.5 * self.scale_tril.shape[-1] * jnp.log(\n 2 * jnp.pi\n )\n return -0.5 * M - normalize_term\n\n @lazy_property\n def covariance_matrix(self):\n return jnp.matmul(self.scale_tril, jnp.swapaxes(self.scale_tril, -1, -2))\n\n @lazy_property\n def precision_matrix(self):\n identity = jnp.broadcast_to(\n jnp.eye(self.scale_tril.shape[-1]), self.scale_tril.shape\n )\n return cho_solve((self.scale_tril, True), identity)\n\n @property\n def mean(self):\n return jnp.broadcast_to(self.loc, self.shape())\n\n @property\n def variance(self):\n return jnp.broadcast_to(\n jnp.sum(self.scale_tril**2, axis=-1), self.batch_shape + self.event_shape\n )\n\n def tree_flatten(self):\n return (self.loc, self.scale_tril), None\n\n @classmethod\n def tree_unflatten(cls, aux_data, params):\n loc, scale_tril = params\n return cls(loc, scale_tril=scale_tril)\n\n @staticmethod\n def infer_shapes(\n loc=(), covariance_matrix=None, precision_matrix=None, scale_tril=None\n ):\n batch_shape, event_shape = loc[:-1], loc[-1:]\n for matrix in [covariance_matrix, precision_matrix, scale_tril]:\n if matrix is not None:\n batch_shape = lax.broadcast_shapes(batch_shape, matrix[:-2])\n event_shape = lax.broadcast_shapes(event_shape, matrix[-1:])\n return batch_shape, event_shape\n\n\ndef _is_sparse(A):\n from scipy import sparse\n\n return sparse.issparse(A)\n\n\ndef _to_sparse(A):\n from scipy import sparse\n\n return sparse.csr_matrix(A)\n\n\nclass CAR(Distribution):\n r\"\"\"\n The Conditional Autoregressive (CAR) distribution is a special case of the multivariate\n normal in which the precision matrix is structured according to the adjacency matrix of\n sites. The amount of autocorrelation between sites is controlled by ``correlation``. The\n distribution is a popular prior for areal spatial data.\n\n :param float or ndarray loc: mean of the multivariate normal\n :param float correlation: autoregression parameter. For most cases, the value should lie\n between 0 (sites are independent, collapses to an iid multivariate normal) and\n 1 (perfect autocorrelation between sites), but the specification allows for negative\n correlations.\n :param float conditional_precision: positive precision for the multivariate normal\n :param ndarray or scipy.sparse.csr_matrix adj_matrix: symmetric adjacency matrix where 1\n indicates adjacency between sites and 0 otherwise. :class:`jax.numpy.ndarray` ``adj_matrix`` is\n supported but is **not** recommended over :class:`numpy.ndarray` or :class:`scipy.sparse.spmatrix`.\n :param bool is_sparse: whether to use a sparse form of ``adj_matrix`` in calculations (must be True if\n ``adj_matrix`` is a :class:`scipy.sparse.spmatrix`)\n \"\"\"\n\n arg_constraints = {\n \"loc\": constraints.real_vector,\n \"correlation\": constraints.open_interval(-1, 1),\n \"conditional_precision\": constraints.positive,\n \"adj_matrix\": constraints.dependent(is_discrete=False, event_dim=2),\n }\n support = constraints.real_vector\n reparametrized_params = [\n \"loc\",\n \"correlation\",\n \"conditional_precision\",\n \"adj_matrix\",\n ]\n\n def __init__(\n self,\n loc,\n correlation,\n conditional_precision,\n adj_matrix,\n *,\n is_sparse=False,\n validate_args=None,\n ):\n if jnp.ndim(loc) == 0:\n (loc,) = promote_shapes(loc, shape=(1,))\n\n self.is_sparse = is_sparse\n\n batch_shape = lax.broadcast_shapes(\n jnp.shape(loc)[:-1],\n jnp.shape(correlation),\n jnp.shape(conditional_precision),\n jnp.shape(adj_matrix)[:-2],\n )\n\n if self.is_sparse:\n if adj_matrix.ndim != 2:\n raise ValueError(\n \"Currently, we only support 2-dimensional adj_matrix. Please make a feature request\",\n \" if you need higher dimensional adj_matrix.\",\n )\n if not (isinstance(adj_matrix, np.ndarray) or _is_sparse(adj_matrix)):\n raise ValueError(\n \"adj_matrix needs to be a numpy array or a scipy sparse matrix. Please make a feature\",\n \" request if you need to support jax ndarrays.\",\n )\n # TODO: look into future jax sparse csr functionality and other developments\n self.adj_matrix = _to_sparse(adj_matrix)\n else:\n assert not _is_sparse(\n adj_matrix\n ), \"adj_matrix is a sparse matrix so please specify `is_sparse=True`.\"\n # TODO: look into static jax ndarray representation\n (self.adj_matrix,) = promote_shapes(\n adj_matrix, shape=batch_shape + adj_matrix.shape[-2:]\n )\n\n event_shape = jnp.shape(self.adj_matrix)[-1:]\n (self.loc,) = promote_shapes(loc, shape=batch_shape + event_shape)\n self.correlation, self.conditional_precision = promote_shapes(\n correlation, conditional_precision, shape=batch_shape\n )\n\n super(CAR, self).__init__(\n batch_shape=batch_shape,\n event_shape=event_shape,\n validate_args=validate_args,\n )\n\n if self._validate_args and (isinstance(adj_matrix, np.ndarray) or is_sparse):\n assert (\n self.adj_matrix.sum(axis=-1) > 0\n ).all() > 0, \"all sites in adjacency matrix must have neighbours\"\n\n if self.is_sparse:\n assert (\n self.adj_matrix != self.adj_matrix.T\n ).nnz == 0, \"adjacency matrix must be symmetric\"\n else:\n assert np.array_equal(\n self.adj_matrix, np.swapaxes(self.adj_matrix, -2, -1)\n ), \"adjacency matrix must be symmetric\"\n\n def sample(self, key, sample_shape=()):\n # TODO: look into a sparse sampling method\n mvn = MultivariateNormal(self.mean, precision_matrix=self.precision_matrix)\n return mvn.sample(key, sample_shape=sample_shape)\n\n @validate_sample\n def log_prob(self, value):\n phi = value - self.loc\n adj_matrix = self.adj_matrix\n\n if self.is_sparse:\n D = np.asarray(adj_matrix.sum(axis=-1)).squeeze(axis=-1)\n D_rsqrt = D ** (-0.5)\n\n adj_matrix_scaled = (\n adj_matrix.multiply(D_rsqrt).multiply(D_rsqrt[:, np.newaxis]).toarray()\n )\n\n adj_matrix = BCOO.from_scipy_sparse(adj_matrix)\n\n else:\n D = adj_matrix.sum(axis=-1)\n D_rsqrt = D ** (-0.5)\n\n adj_matrix_scaled = adj_matrix * (\n D_rsqrt[..., None, :] * D_rsqrt[..., None]\n )\n\n # TODO: look into sparse eignvalue methods\n if isinstance(adj_matrix_scaled, np.ndarray):\n lam = np.linalg.eigvalsh(adj_matrix_scaled)\n else:\n lam = jnp.linalg.eigvalsh(adj_matrix_scaled)\n\n n = D.shape[-1]\n\n logprec = n * jnp.log(self.conditional_precision)\n logdet = jnp.log1p(-jnp.expand_dims(self.correlation, -1) * lam).sum(-1)\n logdet = logdet + jnp.log(D).sum(-1)\n\n logquad = self.conditional_precision * jnp.sum(\n phi\n * (\n D * phi\n - jnp.expand_dims(self.correlation, -1)\n * (adj_matrix @ phi[..., jnp.newaxis]).squeeze(axis=-1)\n ),\n -1,\n )\n\n return 0.5 * (-n * jnp.log(2 * jnp.pi) + logprec + logdet - logquad)\n\n @property\n def mean(self):\n return jnp.broadcast_to(self.loc, self.shape())\n\n @lazy_property\n def precision_matrix(self):\n if self.is_sparse:\n adj_matrix = self.adj_matrix.toarray()\n else:\n adj_matrix = self.adj_matrix\n\n D = adj_matrix.sum(axis=-1, keepdims=True) * jnp.eye(adj_matrix.shape[-1])\n conditional_precision = jnp.expand_dims(self.conditional_precision, (-2, -1))\n correlation = jnp.expand_dims(self.correlation, (-2, -1))\n return conditional_precision * (D - correlation * adj_matrix)\n\n def tree_flatten(self):\n if self.is_sparse:\n return (self.loc, self.correlation, self.conditional_precision), (\n self.is_sparse,\n self.adj_matrix,\n )\n else:\n return (\n self.loc,\n self.correlation,\n self.conditional_precision,\n self.adj_matrix,\n ), (self.is_sparse,)\n\n @classmethod\n def tree_unflatten(cls, aux_data, params):\n is_sparse = aux_data[0]\n if is_sparse:\n loc, correlation, conditional_precision = params\n adj_matrix = aux_data[1]\n else:\n loc, correlation, conditional_precision, adj_matrix = params\n return cls(\n loc, correlation, conditional_precision, adj_matrix, is_sparse=is_sparse\n )\n\n @staticmethod\n def infer_shapes(loc, correlation, conditional_precision, adj_matrix):\n event_shape = adj_matrix[-1:]\n batch_shape = lax.broadcast_shapes(\n loc[:-1], correlation, conditional_precision, adj_matrix[:-2]\n )\n return batch_shape, event_shape\n\n\nclass MultivariateStudentT(Distribution):\n arg_constraints = {\n \"df\": constraints.positive,\n \"loc\": constraints.real_vector,\n \"scale_tril\": constraints.lower_cholesky,\n }\n support = constraints.real_vector\n reparametrized_params = [\"df\", \"loc\", \"scale_tril\"]\n\n def __init__(\n self,\n df,\n loc=0.0,\n scale_tril=None,\n validate_args=None,\n ):\n if jnp.ndim(loc) == 0:\n (loc,) = promote_shapes(loc, shape=(1,))\n batch_shape = lax.broadcast_shapes(\n jnp.shape(df), jnp.shape(loc)[:-1], jnp.shape(scale_tril)[:-2]\n )\n (self.df,) = promote_shapes(df, shape=batch_shape)\n (self.loc,) = promote_shapes(loc, shape=batch_shape + loc.shape[-1:])\n (self.scale_tril,) = promote_shapes(\n scale_tril, shape=batch_shape + scale_tril.shape[-2:]\n )\n event_shape = jnp.shape(self.scale_tril)[-1:]\n self._chi2 = Chi2(self.df)\n super(MultivariateStudentT, self).__init__(\n batch_shape=batch_shape,\n event_shape=event_shape,\n validate_args=validate_args,\n )\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n key_normal, key_chi2 = random.split(key)\n std_normal = random.normal(\n key_normal,\n shape=sample_shape + self.batch_shape + self.event_shape,\n )\n z = self._chi2.sample(key_chi2, sample_shape)\n y = std_normal * jnp.expand_dims(jnp.sqrt(self.df / z), -1)\n return self.loc + jnp.squeeze(\n jnp.matmul(self.scale_tril, y[..., jnp.newaxis]), axis=-1\n )\n\n @validate_sample\n def log_prob(self, value):\n n = self.scale_tril.shape[-1]\n Z = (\n jnp.log(jnp.diagonal(self.scale_tril, axis1=-2, axis2=-1)).sum(-1)\n + 0.5 * n * jnp.log(self.df)\n + 0.5 * n * jnp.log(jnp.pi)\n + gammaln(0.5 * self.df)\n - gammaln(0.5 * (self.df + n))\n )\n M = _batch_mahalanobis(self.scale_tril, value - self.loc)\n return -0.5 * (self.df + n) * jnp.log1p(M / self.df) - Z\n\n @lazy_property\n def covariance_matrix(self):\n # NB: this is not covariance of this distribution;\n # the actual covariance is df / (df - 2) * covariance_matrix\n return jnp.matmul(self.scale_tril, jnp.swapaxes(self.scale_tril, -1, -2))\n\n @lazy_property\n def precision_matrix(self):\n identity = jnp.broadcast_to(\n jnp.eye(self.scale_tril.shape[-1]), self.scale_tril.shape\n )\n return cho_solve((self.scale_tril, True), identity)\n\n @property\n def mean(self):\n # for df <= 1. should be jnp.nan (keeping jnp.inf for consistency with scipy)\n return jnp.broadcast_to(\n jnp.where(jnp.expand_dims(self.df, -1) <= 1, jnp.inf, self.loc),\n self.shape(),\n )\n\n @property\n def variance(self):\n df = jnp.expand_dims(self.df, -1)\n var = jnp.power(self.scale_tril, 2).sum(-1) * (df / (df - 2))\n var = jnp.where(df > 2, var, jnp.inf)\n var = jnp.where(df <= 1, jnp.nan, var)\n return jnp.broadcast_to(var, self.batch_shape + self.event_shape)\n\n @staticmethod\n def infer_shapes(df, loc, scale_tril):\n event_shape = (scale_tril[-1],)\n batch_shape = lax.broadcast_shapes(df, loc[:-1], scale_tril[:-2])\n return batch_shape, event_shape\n\n\ndef _batch_mv(bmat, bvec):\n r\"\"\"\n Performs a batched matrix-vector product, with compatible but different batch shapes.\n This function takes as input `bmat`, containing :math:`n \\times n` matrices, and\n `bvec`, containing length :math:`n` vectors.\n Both `bmat` and `bvec` may have any number of leading dimensions, which correspond\n to a batch shape. They are not necessarily assumed to have the same batch shape,\n just ones which can be broadcasted.\n \"\"\"\n return jnp.squeeze(jnp.matmul(bmat, jnp.expand_dims(bvec, axis=-1)), axis=-1)\n\n\ndef _batch_capacitance_tril(W, D):\n r\"\"\"\n Computes Cholesky of :math:`I + W.T @ inv(D) @ W` for a batch of matrices :math:`W`\n and a batch of vectors :math:`D`.\n \"\"\"\n Wt_Dinv = jnp.swapaxes(W, -1, -2) / jnp.expand_dims(D, -2)\n K = jnp.matmul(Wt_Dinv, W)\n # could be inefficient\n return jnp.linalg.cholesky(jnp.add(K, jnp.identity(K.shape[-1])))\n\n\ndef _batch_lowrank_logdet(W, D, capacitance_tril):\n r\"\"\"\n Uses \"matrix determinant lemma\"::\n log|W @ W.T + D| = log|C| + log|D|,\n where :math:`C` is the capacitance matrix :math:`I + W.T @ inv(D) @ W`, to compute\n the log determinant.\n \"\"\"\n return 2 * jnp.sum(\n jnp.log(jnp.diagonal(capacitance_tril, axis1=-2, axis2=-1)), axis=-1\n ) + jnp.log(D).sum(-1)\n\n\ndef _batch_lowrank_mahalanobis(W, D, x, capacitance_tril):\n r\"\"\"\n Uses \"Woodbury matrix identity\"::\n inv(W @ W.T + D) = inv(D) - inv(D) @ W @ inv(C) @ W.T @ inv(D),\n where :math:`C` is the capacitance matrix :math:`I + W.T @ inv(D) @ W`, to compute the squared\n Mahalanobis distance :math:`x.T @ inv(W @ W.T + D) @ x`.\n \"\"\"\n Wt_Dinv = jnp.swapaxes(W, -1, -2) / jnp.expand_dims(D, -2)\n Wt_Dinv_x = _batch_mv(Wt_Dinv, x)\n mahalanobis_term1 = jnp.sum(jnp.square(x) / D, axis=-1)\n mahalanobis_term2 = _batch_mahalanobis(capacitance_tril, Wt_Dinv_x)\n return mahalanobis_term1 - mahalanobis_term2\n\n\nclass LowRankMultivariateNormal(Distribution):\n arg_constraints = {\n \"loc\": constraints.real_vector,\n \"cov_factor\": constraints.independent(constraints.real, 2),\n \"cov_diag\": constraints.independent(constraints.positive, 1),\n }\n support = constraints.real_vector\n reparametrized_params = [\"loc\", \"cov_factor\", \"cov_diag\"]\n\n def __init__(self, loc, cov_factor, cov_diag, *, validate_args=None):\n if jnp.ndim(loc) < 1:\n raise ValueError(\"`loc` must be at least one-dimensional.\")\n event_shape = jnp.shape(loc)[-1:]\n if jnp.ndim(cov_factor) < 2:\n raise ValueError(\n \"`cov_factor` must be at least two-dimensional, \"\n \"with optional leading batch dimensions\"\n )\n if jnp.shape(cov_factor)[-2:-1] != event_shape:\n raise ValueError(\n \"`cov_factor` must be a batch of matrices with shape {} x m\".format(\n event_shape[0]\n )\n )\n if jnp.shape(cov_diag)[-1:] != event_shape:\n raise ValueError(\n \"`cov_diag` must be a batch of vectors with shape {}\".format(\n self.event_shape\n )\n )\n\n loc, cov_factor, cov_diag = promote_shapes(\n loc[..., jnp.newaxis], cov_factor, cov_diag[..., jnp.newaxis]\n )\n batch_shape = lax.broadcast_shapes(\n jnp.shape(loc), jnp.shape(cov_factor), jnp.shape(cov_diag)\n )[:-2]\n self.loc = loc[..., 0]\n self.cov_factor = cov_factor\n cov_diag = cov_diag[..., 0]\n self.cov_diag = cov_diag\n self._capacitance_tril = _batch_capacitance_tril(cov_factor, cov_diag)\n super(LowRankMultivariateNormal, self).__init__(\n batch_shape=batch_shape,\n event_shape=event_shape,\n validate_args=validate_args,\n )\n\n @property\n def mean(self):\n return self.loc\n\n @lazy_property\n def variance(self):\n raw_variance = jnp.square(self.cov_factor).sum(-1) + self.cov_diag\n return jnp.broadcast_to(raw_variance, self.batch_shape + self.event_shape)\n\n @lazy_property\n def scale_tril(self):\n # The following identity is used to increase the numerically computation stability\n # for Cholesky decomposition (see http://www.gaussianprocess.org/gpml/, Section 3.4.3):\n # W @ W.T + D = D1/2 @ (I + D-1/2 @ W @ W.T @ D-1/2) @ D1/2\n # The matrix \"I + D-1/2 @ W @ W.T @ D-1/2\" has eigenvalues bounded from below by 1,\n # hence it is well-conditioned and safe to take Cholesky decomposition.\n cov_diag_sqrt_unsqueeze = jnp.expand_dims(jnp.sqrt(self.cov_diag), axis=-1)\n Dinvsqrt_W = self.cov_factor / cov_diag_sqrt_unsqueeze\n K = jnp.matmul(Dinvsqrt_W, jnp.swapaxes(Dinvsqrt_W, -1, -2))\n K = jnp.add(K, jnp.identity(K.shape[-1]))\n scale_tril = cov_diag_sqrt_unsqueeze * jnp.linalg.cholesky(K)\n return scale_tril\n\n @lazy_property\n def covariance_matrix(self):\n # TODO: find a better solution to create a diagonal matrix\n new_diag = self.cov_diag[..., jnp.newaxis] * jnp.identity(self.loc.shape[-1])\n covariance_matrix = new_diag + jnp.matmul(\n self.cov_factor, jnp.swapaxes(self.cov_factor, -1, -2)\n )\n return covariance_matrix\n\n @lazy_property\n def precision_matrix(self):\n # We use \"Woodbury matrix identity\" to take advantage of low rank form::\n # inv(W @ W.T + D) = inv(D) - inv(D) @ W @ inv(C) @ W.T @ inv(D)\n # where :math:`C` is the capacitance matrix.\n Wt_Dinv = jnp.swapaxes(self.cov_factor, -1, -2) / jnp.expand_dims(\n self.cov_diag, axis=-2\n )\n A = solve_triangular(Wt_Dinv, self._capacitance_tril, lower=True)\n # TODO: find a better solution to create a diagonal matrix\n inverse_cov_diag = jnp.reciprocal(self.cov_diag)\n diag_embed = inverse_cov_diag[..., jnp.newaxis] * jnp.identity(\n self.loc.shape[-1]\n )\n return diag_embed - jnp.matmul(jnp.swapaxes(A, -1, -2), A)\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n key_W, key_D = random.split(key)\n batch_shape = sample_shape + self.batch_shape\n W_shape = batch_shape + self.cov_factor.shape[-1:]\n D_shape = batch_shape + self.cov_diag.shape[-1:]\n eps_W = random.normal(key_W, W_shape)\n eps_D = random.normal(key_D, D_shape)\n return (\n self.loc\n + _batch_mv(self.cov_factor, eps_W)\n + jnp.sqrt(self.cov_diag) * eps_D\n )\n\n @validate_sample\n def log_prob(self, value):\n diff = value - self.loc\n M = _batch_lowrank_mahalanobis(\n self.cov_factor, self.cov_diag, diff, self._capacitance_tril\n )\n log_det = _batch_lowrank_logdet(\n self.cov_factor, self.cov_diag, self._capacitance_tril\n )\n return -0.5 * (self.loc.shape[-1] * jnp.log(2 * jnp.pi) + log_det + M)\n\n def entropy(self):\n log_det = _batch_lowrank_logdet(\n self.cov_factor, self.cov_diag, self._capacitance_tril\n )\n H = 0.5 * (self.loc.shape[-1] * (1.0 + jnp.log(2 * jnp.pi)) + log_det)\n return jnp.broadcast_to(H, self.batch_shape)\n\n @staticmethod\n def infer_shapes(loc, cov_factor, cov_diag):\n event_shape = loc[-1:]\n batch_shape = lax.broadcast_shapes(loc[:-1], cov_factor[:-2], cov_diag[:-1])\n return batch_shape, event_shape\n\n\nclass Normal(Distribution):\n arg_constraints = {\"loc\": constraints.real, \"scale\": constraints.positive}\n support = constraints.real\n reparametrized_params = [\"loc\", \"scale\"]\n\n def __init__(self, loc=0.0, scale=1.0, *, validate_args=None):\n self.loc, self.scale = promote_shapes(loc, scale)\n batch_shape = lax.broadcast_shapes(jnp.shape(loc), jnp.shape(scale))\n super(Normal, self).__init__(\n batch_shape=batch_shape, validate_args=validate_args\n )\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n eps = random.normal(\n key, shape=sample_shape + self.batch_shape + self.event_shape\n )\n return self.loc + eps * self.scale\n\n @validate_sample\n def log_prob(self, value):\n normalize_term = jnp.log(jnp.sqrt(2 * jnp.pi) * self.scale)\n value_scaled = (value - self.loc) / self.scale\n return -0.5 * value_scaled**2 - normalize_term\n\n def cdf(self, value):\n scaled = (value - self.loc) / self.scale\n return ndtr(scaled)\n\n def log_cdf(self, value):\n return jax_norm.logcdf(value, loc=self.loc, scale=self.scale)\n\n def icdf(self, q):\n return self.loc + self.scale * ndtri(q)\n\n @property\n def mean(self):\n return jnp.broadcast_to(self.loc, self.batch_shape)\n\n @property\n def variance(self):\n return jnp.broadcast_to(self.scale**2, self.batch_shape)\n\n\nclass Pareto(TransformedDistribution):\n arg_constraints = {\"scale\": constraints.positive, \"alpha\": constraints.positive}\n reparametrized_params = [\"scale\", \"alpha\"]\n\n def __init__(self, scale, alpha, *, validate_args=None):\n self.scale, self.alpha = promote_shapes(scale, alpha)\n batch_shape = lax.broadcast_shapes(jnp.shape(scale), jnp.shape(alpha))\n scale, alpha = jnp.broadcast_to(scale, batch_shape), jnp.broadcast_to(\n alpha, batch_shape\n )\n base_dist = Exponential(alpha)\n transforms = [ExpTransform(), AffineTransform(loc=0, scale=scale)]\n super(Pareto, self).__init__(base_dist, transforms, validate_args=validate_args)\n\n @property\n def mean(self):\n # mean is inf for alpha <= 1\n a = jnp.divide(self.alpha * self.scale, (self.alpha - 1))\n return jnp.where(self.alpha <= 1, jnp.inf, a)\n\n @property\n def variance(self):\n # var is inf for alpha <= 2\n a = jnp.divide(\n (self.scale**2) * self.alpha, (self.alpha - 1) ** 2 * (self.alpha - 2)\n )\n return jnp.where(self.alpha <= 2, jnp.inf, a)\n\n # override the default behaviour to save computations\n @constraints.dependent_property(is_discrete=False, event_dim=0)\n def support(self):\n return constraints.greater_than(self.scale)\n\n def cdf(self, value):\n return 1 - jnp.power(self.scale / value, self.alpha)\n\n def icdf(self, q):\n return self.scale / jnp.power(1 - q, 1 / self.alpha)\n\n def tree_flatten(self):\n return super(TransformedDistribution, self).tree_flatten()\n\n\nclass RelaxedBernoulliLogits(TransformedDistribution):\n arg_constraints = {\"temperature\": constraints.positive, \"logits\": constraints.real}\n support = constraints.unit_interval\n\n def __init__(self, temperature, logits, *, validate_args=None):\n self.temperature, self.logits = promote_shapes(temperature, logits)\n base_dist = Logistic(logits / temperature, 1 / temperature)\n transforms = [SigmoidTransform()]\n super().__init__(base_dist, transforms, validate_args=validate_args)\n\n def tree_flatten(self):\n return super(TransformedDistribution, self).tree_flatten()\n\n\ndef RelaxedBernoulli(temperature, probs=None, logits=None, *, validate_args=None):\n if probs is None and logits is None:\n raise ValueError(\"One of `probs` or `logits` must be specified.\")\n if probs is not None:\n logits = _to_logits_bernoulli(probs)\n return RelaxedBernoulliLogits(temperature, logits, validate_args=validate_args)\n\n\nclass SoftLaplace(Distribution):\n \"\"\"\n Smooth distribution with Laplace-like tail behavior.\n\n This distribution corresponds to the log-convex density::\n\n z = (value - loc) / scale\n log_prob = log(2 / pi) - log(scale) - logaddexp(z, -z)\n\n Like the Laplace density, this density has the heaviest possible tails\n (asymptotically) while still being log-convex. Unlike the Laplace\n distribution, this distribution is infinitely differentiable everywhere,\n and is thus suitable for HMC and Laplace approximation.\n\n :param loc: Location parameter.\n :param scale: Scale parameter.\n \"\"\"\n\n arg_constraints = {\"loc\": constraints.real, \"scale\": constraints.positive}\n support = constraints.real\n reparametrized_params = [\"loc\", \"scale\"]\n\n def __init__(self, loc, scale, *, validate_args=None):\n self.loc, self.scale = promote_shapes(loc, scale)\n batch_shape = lax.broadcast_shapes(jnp.shape(loc), jnp.shape(scale))\n super().__init__(batch_shape=batch_shape, validate_args=validate_args)\n\n @validate_sample\n def log_prob(self, value):\n z = (value - self.loc) / self.scale\n return jnp.log(2 / jnp.pi) - jnp.log(self.scale) - jnp.logaddexp(z, -z)\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n dtype = jnp.result_type(float)\n finfo = jnp.finfo(dtype)\n minval = finfo.tiny\n u = random.uniform(key, shape=sample_shape + self.batch_shape, minval=minval)\n return self.icdf(u)\n\n # TODO: refactor validate_sample to only does validation check and use it here\n def cdf(self, value):\n z = (value - self.loc) / self.scale\n return jnp.arctan(jnp.exp(z)) * (2 / jnp.pi)\n\n def icdf(self, value):\n return jnp.log(jnp.tan(value * (jnp.pi / 2))) * self.scale + self.loc\n\n @property\n def mean(self):\n return self.loc\n\n @property\n def variance(self):\n return (jnp.pi / 2 * self.scale) ** 2\n\n\nclass StudentT(Distribution):\n arg_constraints = {\n \"df\": constraints.positive,\n \"loc\": constraints.real,\n \"scale\": constraints.positive,\n }\n support = constraints.real\n reparametrized_params = [\"df\", \"loc\", \"scale\"]\n\n def __init__(self, df, loc=0.0, scale=1.0, *, validate_args=None):\n batch_shape = lax.broadcast_shapes(\n jnp.shape(df), jnp.shape(loc), jnp.shape(scale)\n )\n self.df, self.loc, self.scale = promote_shapes(\n df, loc, scale, shape=batch_shape\n )\n df = jnp.broadcast_to(df, batch_shape)\n self._chi2 = Chi2(df)\n super(StudentT, self).__init__(batch_shape, validate_args=validate_args)\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n key_normal, key_chi2 = random.split(key)\n std_normal = random.normal(key_normal, shape=sample_shape + self.batch_shape)\n z = self._chi2.sample(key_chi2, sample_shape)\n y = std_normal * jnp.sqrt(self.df / z)\n return self.loc + self.scale * y\n\n @validate_sample\n def log_prob(self, value):\n y = (value - self.loc) / self.scale\n z = (\n jnp.log(self.scale)\n + 0.5 * jnp.log(self.df)\n + 0.5 * jnp.log(jnp.pi)\n + gammaln(0.5 * self.df)\n - gammaln(0.5 * (self.df + 1.0))\n )\n return -0.5 * (self.df + 1.0) * jnp.log1p(y**2.0 / self.df) - z\n\n @property\n def mean(self):\n # for df <= 1. should be jnp.nan (keeping jnp.inf for consistency with scipy)\n return jnp.broadcast_to(\n jnp.where(self.df <= 1, jnp.inf, self.loc), self.batch_shape\n )\n\n @property\n def variance(self):\n var = jnp.where(\n self.df > 2, jnp.divide(self.scale**2 * self.df, self.df - 2.0), jnp.inf\n )\n var = jnp.where(self.df <= 1, jnp.nan, var)\n return jnp.broadcast_to(var, self.batch_shape)\n\n def cdf(self, value):\n # Ref: https://en.wikipedia.org/wiki/Student's_t-distribution#Related_distributions\n # X^2 ~ F(1, df) -> df / (df + X^2) ~ Beta(df/2, 0.5)\n scaled = (value - self.loc) / self.scale\n scaled_squared = scaled * scaled\n beta_value = self.df / (self.df + scaled_squared)\n\n # when scaled < 0, returns 0.5 * Beta(df/2, 0.5).cdf(beta_value)\n # when scaled > 0, returns 1 - 0.5 * Beta(df/2, 0.5).cdf(beta_value)\n return 0.5 * (\n 1\n + jnp.sign(scaled)\n - jnp.sign(scaled) * betainc(0.5 * self.df, 0.5, beta_value)\n )\n\n def icdf(self, q):\n beta_value = betaincinv(0.5 * self.df, 0.5, 1 - jnp.abs(1 - 2 * q))\n scaled_squared = self.df * (1 / beta_value - 1)\n scaled = jnp.sign(q - 0.5) * jnp.sqrt(scaled_squared)\n return scaled * self.scale + self.loc\n\n\nclass Uniform(Distribution):\n arg_constraints = {\"low\": constraints.dependent, \"high\": constraints.dependent}\n reparametrized_params = [\"low\", \"high\"]\n\n def __init__(self, low=0.0, high=1.0, *, validate_args=None):\n self.low, self.high = promote_shapes(low, high)\n batch_shape = lax.broadcast_shapes(jnp.shape(low), jnp.shape(high))\n self._support = constraints.interval(low, high)\n super().__init__(batch_shape, validate_args=validate_args)\n\n @constraints.dependent_property(is_discrete=False, event_dim=0)\n def support(self):\n return self._support\n\n def sample(self, key, sample_shape=()):\n shape = sample_shape + self.batch_shape\n return random.uniform(key, shape=shape, minval=self.low, maxval=self.high)\n\n @validate_sample\n def log_prob(self, value):\n shape = lax.broadcast_shapes(jnp.shape(value), self.batch_shape)\n return -jnp.broadcast_to(jnp.log(self.high - self.low), shape)\n\n def cdf(self, value):\n cdf = (value - self.low) / (self.high - self.low)\n return jnp.clip(cdf, a_min=0.0, a_max=1.0)\n\n def icdf(self, value):\n return self.low + value * (self.high - self.low)\n\n @property\n def mean(self):\n return self.low + (self.high - self.low) / 2.0\n\n @property\n def variance(self):\n return (self.high - self.low) ** 2 / 12.0\n\n def tree_flatten(self):\n if isinstance(self._support.lower_bound, (int, float)) and isinstance(\n self._support.upper_bound, (int, float)\n ):\n aux_data = (self._support.lower_bound, self._support.upper_bound)\n else:\n aux_data = None\n return (self.low, self.high), aux_data\n\n @classmethod\n def tree_unflatten(cls, aux_data, params):\n d = cls(*params)\n if aux_data is not None:\n d._support = constraints.interval(*aux_data)\n return d\n\n @staticmethod\n def infer_shapes(low=(), high=()):\n batch_shape = lax.broadcast_shapes(low, high)\n event_shape = ()\n return batch_shape, event_shape\n\n\nclass Weibull(Distribution):\n arg_constraints = {\n \"scale\": constraints.positive,\n \"concentration\": constraints.positive,\n }\n support = constraints.positive\n reparametrized_params = [\"scale\", \"concentration\"]\n\n def __init__(self, scale, concentration, *, validate_args=None):\n self.concentration, self.scale = promote_shapes(concentration, scale)\n batch_shape = lax.broadcast_shapes(jnp.shape(concentration), jnp.shape(scale))\n super().__init__(batch_shape=batch_shape, validate_args=validate_args)\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n return random.weibull_min(\n key,\n scale=self.scale,\n concentration=self.concentration,\n shape=sample_shape + self.batch_shape,\n )\n\n @validate_sample\n def log_prob(self, value):\n ll = -jnp.power(value / self.scale, self.concentration)\n ll += jnp.log(self.concentration)\n ll += (self.concentration - 1.0) * jnp.log(value)\n ll -= self.concentration * jnp.log(self.scale)\n return ll\n\n def cdf(self, value):\n return 1 - jnp.exp(-((value / self.scale) ** self.concentration))\n\n @property\n def mean(self):\n return self.scale * jnp.exp(gammaln(1.0 + 1.0 / self.concentration))\n\n @property\n def variance(self):\n return self.scale**2 * (\n jnp.exp(gammaln(1.0 + 2.0 / self.concentration))\n - jnp.exp(gammaln(1.0 + 1.0 / self.concentration)) ** 2\n )\n\n\nclass BetaProportion(Beta):\n \"\"\"\n The BetaProportion distribution is a reparameterization of the conventional\n Beta distribution in terms of a the variate mean and a\n precision parameter.\n\n **Reference:**\n `Beta regression for modelling rates and proportion`, Ferrari Silvia, and\n Francisco Cribari-Neto. Journal of Applied Statistics 31.7 (2004): 799-815.\n \"\"\"\n\n arg_constraints = {\n \"mean\": constraints.open_interval(0.0, 1.0),\n \"concentration\": constraints.positive,\n }\n reparametrized_params = [\"mean\", \"concentration\"]\n support = constraints.unit_interval\n\n def __init__(self, mean, concentration, *, validate_args=None):\n self.concentration = jnp.broadcast_to(\n concentration, lax.broadcast_shapes(jnp.shape(concentration))\n )\n super().__init__(\n mean * concentration,\n (1.0 - mean) * concentration,\n validate_args=validate_args,\n )\n\n\nclass AsymmetricLaplaceQuantile(Distribution):\n \"\"\"An alternative parameterization of AsymmetricLaplace commonly applied in\n Bayesian quantile regression.\n\n Instead of the `asymmetry` parameter employed by AsymmetricLaplace, to\n define the balance between left- versus right-hand sides of the\n distribution, this class utilizes a `quantile` parameter, which describes\n the proportion of probability density that falls to the left-hand side of\n the distribution.\n\n The `scale` parameter is also interpreted slightly differently than in\n AsymmetricLaplace. When `loc=0` and `scale=1`, AsymmetricLaplace(0,1,1)\n is equivalent to Laplace(0,1), while AsymmetricLaplaceQuantile(0,1,0.5) is\n equivalent to Laplace(0,2).\n \"\"\"\n\n arg_constraints = {\n \"loc\": constraints.real,\n \"scale\": constraints.positive,\n \"quantile\": constraints.open_interval(0.0, 1.0),\n }\n reparametrized_params = [\"loc\", \"scale\", \"quantile\"]\n support = constraints.real\n\n def __init__(self, loc=0.0, scale=1.0, quantile=0.5, *, validate_args=None):\n batch_shape = lax.broadcast_shapes(\n jnp.shape(loc), jnp.shape(scale), jnp.shape(quantile)\n )\n self.loc, self.scale, self.quantile = promote_shapes(\n loc, scale, quantile, shape=batch_shape\n )\n super(AsymmetricLaplaceQuantile, self).__init__(\n batch_shape=batch_shape, validate_args=validate_args\n )\n asymmetry = (1 / ((1 / quantile) - 1)) ** 0.5\n scale_classic = scale * asymmetry / quantile\n self._ald = AsymmetricLaplace(loc=loc, scale=scale_classic, asymmetry=asymmetry)\n\n def log_prob(self, value):\n if self._validate_args:\n self._validate_sample(value)\n return self._ald.log_prob(value)\n\n def sample(self, key, sample_shape=()):\n return self._ald.sample(key, sample_shape=sample_shape)\n\n @property\n def mean(self):\n return self._ald.mean\n\n @property\n def variance(self):\n return self._ald.variance\n\n def cdf(self, value):\n return self._ald.cdf(value)\n\n def icdf(self, value):\n return self._ald.icdf(value)\n", "path": "numpyro/distributions/continuous.py" }, { "content": "# Copyright Contributors to the Pyro project.\n# SPDX-License-Identifier: Apache-2.0\n\nfrom jax import lax\nimport jax.numpy as jnp\nimport jax.random as random\nfrom jax.scipy.special import logsumexp\nfrom jax.tree_util import tree_map\n\nfrom numpyro.distributions import constraints\nfrom numpyro.distributions.continuous import (\n Cauchy,\n Laplace,\n Logistic,\n Normal,\n SoftLaplace,\n StudentT,\n)\nfrom numpyro.distributions.distribution import Distribution\nfrom numpyro.distributions.util import (\n clamp_probs,\n is_prng_key,\n lazy_property,\n promote_shapes,\n validate_sample,\n)\n\n\nclass LeftTruncatedDistribution(Distribution):\n arg_constraints = {\"low\": constraints.real}\n reparametrized_params = [\"low\"]\n supported_types = (Cauchy, Laplace, Logistic, Normal, SoftLaplace, StudentT)\n\n def __init__(self, base_dist, low=0.0, *, validate_args=None):\n assert isinstance(base_dist, self.supported_types)\n assert (\n base_dist.support is constraints.real\n ), \"The base distribution should be univariate and have real support.\"\n batch_shape = lax.broadcast_shapes(base_dist.batch_shape, jnp.shape(low))\n self.base_dist = tree_map(\n lambda p: promote_shapes(p, shape=batch_shape)[0], base_dist\n )\n (self.low,) = promote_shapes(low, shape=batch_shape)\n self._support = constraints.greater_than(low)\n super().__init__(batch_shape, validate_args=validate_args)\n\n @constraints.dependent_property(is_discrete=False, event_dim=0)\n def support(self):\n return self._support\n\n @lazy_property\n def _tail_prob_at_low(self):\n # if low < loc, returns cdf(low); otherwise returns 1 - cdf(low)\n loc = self.base_dist.loc\n sign = jnp.where(loc >= self.low, 1.0, -1.0)\n return self.base_dist.cdf(loc - sign * (loc - self.low))\n\n @lazy_property\n def _tail_prob_at_high(self):\n # if low < loc, returns cdf(high) = 1; otherwise returns 1 - cdf(high) = 0\n return jnp.where(self.low <= self.base_dist.loc, 1.0, 0.0)\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n dtype = jnp.result_type(float)\n finfo = jnp.finfo(dtype)\n minval = finfo.tiny\n u = random.uniform(key, shape=sample_shape + self.batch_shape, minval=minval)\n loc = self.base_dist.loc\n sign = jnp.where(loc >= self.low, 1.0, -1.0)\n return (1 - sign) * loc + sign * self.base_dist.icdf(\n (1 - u) * self._tail_prob_at_low + u * self._tail_prob_at_high\n )\n\n @validate_sample\n def log_prob(self, value):\n sign = jnp.where(self.base_dist.loc >= self.low, 1.0, -1.0)\n return self.base_dist.log_prob(value) - jnp.log(\n sign * (self._tail_prob_at_high - self._tail_prob_at_low)\n )\n\n def tree_flatten(self):\n base_flatten, base_aux = self.base_dist.tree_flatten()\n if isinstance(self._support.lower_bound, (int, float)):\n return base_flatten, (\n type(self.base_dist),\n base_aux,\n self._support.lower_bound,\n )\n else:\n return (base_flatten, self.low), (type(self.base_dist), base_aux)\n\n @classmethod\n def tree_unflatten(cls, aux_data, params):\n if len(aux_data) == 2:\n base_flatten, low = params\n base_cls, base_aux = aux_data\n else:\n base_flatten = params\n base_cls, base_aux, low = aux_data\n base_dist = base_cls.tree_unflatten(base_aux, base_flatten)\n return cls(base_dist, low=low)\n\n @property\n def mean(self):\n if isinstance(self.base_dist, Normal):\n low_prob = jnp.exp(self.log_prob(self.low))\n return self.base_dist.loc + low_prob * self.base_dist.scale**2\n elif isinstance(self.base_dist, Cauchy):\n return jnp.full(self.batch_shape, jnp.nan)\n else:\n return NotImplementedError(\"mean only available for Normal and Cauchy\")\n\n @property\n def var(self):\n if isinstance(self.base_dist, Normal):\n low_prob = jnp.exp(self.log_prob(self.low))\n return (self.base_dist.scale**2) * (\n 1\n + (self.low - self.base_dist.loc) * low_prob\n - (low_prob * self.base_dist.scale) ** 2\n )\n elif isinstance(self.base_dist, Cauchy):\n return jnp.full(self.batch_shape, jnp.nan)\n else:\n return NotImplementedError(\"var only available for Normal and Cauchy\")\n\n\nclass RightTruncatedDistribution(Distribution):\n arg_constraints = {\"high\": constraints.real}\n reparametrized_params = [\"high\"]\n supported_types = (Cauchy, Laplace, Logistic, Normal, SoftLaplace, StudentT)\n\n def __init__(self, base_dist, high=0.0, *, validate_args=None):\n assert isinstance(base_dist, self.supported_types)\n assert (\n base_dist.support is constraints.real\n ), \"The base distribution should be univariate and have real support.\"\n batch_shape = lax.broadcast_shapes(base_dist.batch_shape, jnp.shape(high))\n self.base_dist = tree_map(\n lambda p: promote_shapes(p, shape=batch_shape)[0], base_dist\n )\n (self.high,) = promote_shapes(high, shape=batch_shape)\n self._support = constraints.less_than(high)\n super().__init__(batch_shape, validate_args=validate_args)\n\n @constraints.dependent_property(is_discrete=False, event_dim=0)\n def support(self):\n return self._support\n\n @lazy_property\n def _cdf_at_high(self):\n return self.base_dist.cdf(self.high)\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n dtype = jnp.result_type(float)\n finfo = jnp.finfo(dtype)\n minval = finfo.tiny\n u = random.uniform(key, shape=sample_shape + self.batch_shape, minval=minval)\n return self.base_dist.icdf(u * self._cdf_at_high)\n\n @validate_sample\n def log_prob(self, value):\n return self.base_dist.log_prob(value) - jnp.log(self._cdf_at_high)\n\n def tree_flatten(self):\n base_flatten, base_aux = self.base_dist.tree_flatten()\n if isinstance(self._support.upper_bound, (int, float)):\n return base_flatten, (\n type(self.base_dist),\n base_aux,\n self._support.upper_bound,\n )\n else:\n return (base_flatten, self.high), (type(self.base_dist), base_aux)\n\n @classmethod\n def tree_unflatten(cls, aux_data, params):\n if len(aux_data) == 2:\n base_flatten, high = params\n base_cls, base_aux = aux_data\n else:\n base_flatten = params\n base_cls, base_aux, high = aux_data\n base_dist = base_cls.tree_unflatten(base_aux, base_flatten)\n return cls(base_dist, high=high)\n\n @property\n def mean(self):\n if isinstance(self.base_dist, Normal):\n high_prob = jnp.exp(self.log_prob(self.high))\n return self.base_dist.loc - high_prob * self.base_dist.scale**2\n elif isinstance(self.base_dist, Cauchy):\n return jnp.full(self.batch_shape, jnp.nan)\n else:\n return NotImplementedError(\"mean only available for Normal and Cauchy\")\n\n @property\n def var(self):\n if isinstance(self.base_dist, Normal):\n high_prob = jnp.exp(self.log_prob(self.high))\n return (self.base_dist.scale**2) * (\n 1\n - (self.high - self.base_dist.loc) * high_prob\n - (high_prob * self.base_dist.scale) ** 2\n )\n elif isinstance(self.base_dist, Cauchy):\n return jnp.full(self.batch_shape, jnp.nan)\n else:\n return NotImplementedError(\"var only available for Normal and Cauchy\")\n\n\nclass TwoSidedTruncatedDistribution(Distribution):\n arg_constraints = {\"low\": constraints.dependent, \"high\": constraints.dependent}\n reparametrized_params = [\"low\", \"high\"]\n supported_types = (Cauchy, Laplace, Logistic, Normal, SoftLaplace, StudentT)\n\n def __init__(self, base_dist, low=0.0, high=1.0, *, validate_args=None):\n assert isinstance(base_dist, self.supported_types)\n assert (\n base_dist.support is constraints.real\n ), \"The base distribution should be univariate and have real support.\"\n batch_shape = lax.broadcast_shapes(\n base_dist.batch_shape, jnp.shape(low), jnp.shape(high)\n )\n self.base_dist = tree_map(\n lambda p: promote_shapes(p, shape=batch_shape)[0], base_dist\n )\n (self.low,) = promote_shapes(low, shape=batch_shape)\n (self.high,) = promote_shapes(high, shape=batch_shape)\n self._support = constraints.interval(low, high)\n super().__init__(batch_shape, validate_args=validate_args)\n\n @constraints.dependent_property(is_discrete=False, event_dim=0)\n def support(self):\n return self._support\n\n @lazy_property\n def _tail_prob_at_low(self):\n # if low < loc, returns cdf(low); otherwise returns 1 - cdf(low)\n loc = self.base_dist.loc\n sign = jnp.where(loc >= self.low, 1.0, -1.0)\n return self.base_dist.cdf(loc - sign * (loc - self.low))\n\n @lazy_property\n def _tail_prob_at_high(self):\n # if low < loc, returns cdf(high); otherwise returns 1 - cdf(high)\n loc = self.base_dist.loc\n sign = jnp.where(loc >= self.low, 1.0, -1.0)\n return self.base_dist.cdf(loc - sign * (loc - self.high))\n\n @lazy_property\n def _log_diff_tail_probs(self):\n # use log_cdf method, if available, to avoid inf's in log_prob\n # fall back to cdf, if log_cdf not available\n log_cdf = getattr(self.base_dist, \"log_cdf\", None)\n if callable(log_cdf):\n return logsumexp(\n a=jnp.stack([log_cdf(self.high), log_cdf(self.low)], axis=-1),\n axis=-1,\n b=jnp.array([1, -1]), # subtract low from high\n )\n\n else:\n loc = self.base_dist.loc\n sign = jnp.where(loc >= self.low, 1.0, -1.0)\n return jnp.log(sign * (self._tail_prob_at_high - self._tail_prob_at_low))\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n dtype = jnp.result_type(float)\n finfo = jnp.finfo(dtype)\n minval = finfo.tiny\n u = random.uniform(key, shape=sample_shape + self.batch_shape, minval=minval)\n\n # NB: we use a more numerically stable formula for a symmetric base distribution\n # A = icdf(cdf(low) + (cdf(high) - cdf(low)) * u) = icdf[(1 - u) * cdf(low) + u * cdf(high)]\n # will suffer by precision issues when low is large;\n # If low < loc:\n # A = icdf[(1 - u) * cdf(low) + u * cdf(high)]\n # Else\n # A = 2 * loc - icdf[(1 - u) * cdf(2*loc-low)) + u * cdf(2*loc - high)]\n loc = self.base_dist.loc\n sign = jnp.where(loc >= self.low, 1.0, -1.0)\n return (1 - sign) * loc + sign * self.base_dist.icdf(\n clamp_probs((1 - u) * self._tail_prob_at_low + u * self._tail_prob_at_high)\n )\n\n @validate_sample\n def log_prob(self, value):\n # NB: we use a more numerically stable formula for a symmetric base distribution\n # if low < loc\n # cdf(high) - cdf(low) = as-is\n # if low > loc\n # cdf(high) - cdf(low) = cdf(2 * loc - low) - cdf(2 * loc - high)\n return self.base_dist.log_prob(value) - self._log_diff_tail_probs\n\n def tree_flatten(self):\n base_flatten, base_aux = self.base_dist.tree_flatten()\n if isinstance(self._support.lower_bound, (int, float)) and isinstance(\n self._support.upper_bound, (int, float)\n ):\n return base_flatten, (\n type(self.base_dist),\n base_aux,\n self._support.lower_bound,\n self._support.upper_bound,\n )\n else:\n return (base_flatten, self.low, self.high), (type(self.base_dist), base_aux)\n\n @classmethod\n def tree_unflatten(cls, aux_data, params):\n if len(aux_data) == 2:\n base_flatten, low, high = params\n base_cls, base_aux = aux_data\n else:\n base_flatten = params\n base_cls, base_aux, low, high = aux_data\n base_dist = base_cls.tree_unflatten(base_aux, base_flatten)\n return cls(base_dist, low=low, high=high)\n\n @property\n def mean(self):\n if isinstance(self.base_dist, Normal):\n low_prob = jnp.exp(self.log_prob(self.low))\n high_prob = jnp.exp(self.log_prob(self.high))\n return (\n self.base_dist.loc + (low_prob - high_prob) * self.base_dist.scale**2\n )\n elif isinstance(self.base_dist, Cauchy):\n return jnp.full(self.batch_shape, jnp.nan)\n else:\n return NotImplementedError(\"mean only available for Normal and Cauchy\")\n\n @property\n def var(self):\n if isinstance(self.base_dist, Normal):\n low_prob = jnp.exp(self.log_prob(self.low))\n high_prob = jnp.exp(self.log_prob(self.high))\n return (self.base_dist.scale**2) * (\n 1\n + (self.low - self.base_dist.loc) * low_prob\n - (self.high - self.base_dist.loc) * high_prob\n - ((low_prob - high_prob) * self.base_dist.scale) ** 2\n )\n elif isinstance(self.base_dist, Cauchy):\n return jnp.full(self.batch_shape, jnp.nan)\n else:\n return NotImplementedError(\"var only available for Normal and Cauchy\")\n\n\ndef TruncatedDistribution(base_dist, low=None, high=None, *, validate_args=None):\n \"\"\"\n A function to generate a truncated distribution.\n\n :param base_dist: The base distribution to be truncated. This should be a univariate\n distribution. Currently, only the following distributions are supported:\n Cauchy, Laplace, Logistic, Normal, and StudentT.\n :param low: the value which is used to truncate the base distribution from below.\n Setting this parameter to None to not truncate from below.\n :param high: the value which is used to truncate the base distribution from above.\n Setting this parameter to None to not truncate from above.\n \"\"\"\n if high is None:\n if low is None:\n return base_dist\n else:\n return LeftTruncatedDistribution(\n base_dist, low=low, validate_args=validate_args\n )\n elif low is None:\n return RightTruncatedDistribution(\n base_dist, high=high, validate_args=validate_args\n )\n else:\n return TwoSidedTruncatedDistribution(\n base_dist, low=low, high=high, validate_args=validate_args\n )\n\n\ndef TruncatedCauchy(loc=0.0, scale=1.0, *, low=None, high=None, validate_args=None):\n return TruncatedDistribution(\n Cauchy(loc, scale), low=low, high=high, validate_args=validate_args\n )\n\n\ndef TruncatedNormal(loc=0.0, scale=1.0, *, low=None, high=None, validate_args=None):\n return TruncatedDistribution(\n Normal(loc, scale), low=low, high=high, validate_args=validate_args\n )\n\n\nclass TruncatedPolyaGamma(Distribution):\n truncation_point = 2.5\n num_log_prob_terms = 7\n num_gamma_variates = 8\n assert num_log_prob_terms % 2 == 1\n\n arg_constraints = {}\n support = constraints.interval(0.0, truncation_point)\n\n def __init__(self, batch_shape=(), *, validate_args=None):\n super(TruncatedPolyaGamma, self).__init__(\n batch_shape, validate_args=validate_args\n )\n\n def sample(self, key, sample_shape=()):\n assert is_prng_key(key)\n denom = jnp.square(jnp.arange(0.5, self.num_gamma_variates))\n x = random.gamma(\n key, jnp.ones(self.batch_shape + sample_shape + (self.num_gamma_variates,))\n )\n x = jnp.sum(x / denom, axis=-1)\n return jnp.clip(x * (0.5 / jnp.pi**2), a_max=self.truncation_point)\n\n @validate_sample\n def log_prob(self, value):\n value = value[..., None]\n all_indices = jnp.arange(0, self.num_log_prob_terms)\n two_n_plus_one = 2.0 * all_indices + 1.0\n log_terms = (\n jnp.log(two_n_plus_one)\n - 1.5 * jnp.log(value)\n - 0.125 * jnp.square(two_n_plus_one) / value\n )\n even_terms = jnp.take(log_terms, all_indices[::2], axis=-1)\n odd_terms = jnp.take(log_terms, all_indices[1::2], axis=-1)\n sum_even = jnp.exp(logsumexp(even_terms, axis=-1))\n sum_odd = jnp.exp(logsumexp(odd_terms, axis=-1))\n return jnp.log(sum_even - sum_odd) - 0.5 * jnp.log(2.0 * jnp.pi)\n\n def tree_flatten(self):\n return (), self.batch_shape\n\n @classmethod\n def tree_unflatten(cls, aux_data, params):\n return cls(batch_shape=aux_data)\n", "path": "numpyro/distributions/truncated.py" } ]
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) + + [email protected]( + "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_update\nfrom jax.scipy.linalg import solve_triangular\nfrom jax.scipy.special import expit\nfrom jax.tree_util import tree_flatten, tree_map, tree_multimap\n\nimport numpyro.distributions as dist\nfrom numpyro.util import cond, identity, while_loop\n\nAdaptWindow = namedtuple(\"AdaptWindow\", [\"start\", \"end\"])\n# XXX: we need to store rng_key here in case we use find_reasonable_step_size functionality\nHMCAdaptState = namedtuple(\n \"HMCAdaptState\",\n [\n \"step_size\",\n \"inverse_mass_matrix\",\n \"mass_matrix_sqrt\",\n \"mass_matrix_sqrt_inv\",\n \"ss_state\",\n \"mm_state\",\n \"window_idx\",\n \"rng_key\",\n ],\n)\nIntegratorState = namedtuple(\n \"IntegratorState\", [\"z\", \"r\", \"potential_energy\", \"z_grad\"]\n)\nIntegratorState.__new__.__defaults__ = (None,) * len(IntegratorState._fields)\n\nTreeInfo = namedtuple(\n \"TreeInfo\",\n [\n \"z_left\",\n \"r_left\",\n \"z_left_grad\",\n \"z_right\",\n \"r_right\",\n \"z_right_grad\",\n \"z_proposal\",\n \"z_proposal_pe\",\n \"z_proposal_grad\",\n \"z_proposal_energy\",\n \"depth\",\n \"weight\",\n \"r_sum\",\n \"turning\",\n \"diverging\",\n \"sum_accept_probs\",\n \"num_proposals\",\n ],\n)\n\n\ndef dual_averaging(t0=10, kappa=0.75, gamma=0.05):\n \"\"\"\n Dual Averaging is a scheme to solve convex optimization problems. It\n belongs to a class of subgradient methods which uses subgradients (which\n lie in a dual space) to update states (in primal space) of a model. Under\n some conditions, the averages of generated parameters during the scheme are\n guaranteed to converge to an optimal value. However, a counter-intuitive\n aspect of traditional subgradient methods is \"new subgradients enter the\n model with decreasing weights\" (see reference [1]). Dual Averaging scheme\n resolves that issue by updating parameters using weights equally for\n subgradients, hence we have the name \"dual averaging\".\n\n This class implements a dual averaging scheme which is adapted for Markov\n chain Monte Carlo (MCMC) algorithms. To be more precise, we will replace\n subgradients by some statistics calculated at the end of MCMC trajectories.\n Following [2], we introduce some free parameters such as ``t0`` and\n ``kappa``, which is helpful and still guarantees the convergence of the\n scheme.\n\n **References:**\n\n 1. *Primal-dual subgradient methods for convex problems*,\n Yurii Nesterov\n 2. *The No-U-turn sampler: adaptively setting path lengths in Hamiltonian Monte Carlo*,\n Matthew D. Hoffman, Andrew Gelman\n\n :param int t0: A free parameter introduced in reference [2] that stabilizes\n the initial steps of the scheme. Defaults to 10.\n :param float kappa: A free parameter introduced in reference [2] that\n controls the weights of steps of the scheme. For a small ``kappa``, the\n scheme will quickly forget states from early steps. This should be a\n number in :math:`(0.5, 1]`. Defaults to 0.75.\n :param float gamma: A free parameter introduced in reference [1] which\n controls the speed of the convergence of the scheme. Defaults to 0.05.\n :return: a (`init_fn`, `update_fn`) pair.\n \"\"\"\n\n def init_fn(prox_center=0.0):\n \"\"\"\n :param float prox_center: A parameter introduced in reference [1] which\n pulls the primal sequence towards it. Defaults to 0.\n :return: initial state for the scheme.\n \"\"\"\n x_t = jnp.zeros(())\n x_avg = jnp.zeros(()) # average of primal sequence\n g_avg = jnp.zeros(()) # average of dual sequence\n t = jnp.array(0, dtype=jnp.result_type(int))\n return x_t, x_avg, g_avg, t, prox_center\n\n def update_fn(g, state):\n \"\"\"\n :param float g: The current subgradient or statistics calculated during\n an MCMC trajectory.\n :param state: Current state of the scheme.\n :return: new state for the scheme.\n \"\"\"\n x_t, x_avg, g_avg, t, prox_center = state\n t = t + 1\n # g_avg = (g_1 + ... + g_t) / t\n g_avg = (1 - 1 / (t + t0)) * g_avg + g / (t + t0)\n # According to formula (3.4) of [1], we have\n # x_t = argmin{ g_avg . x + loc_t . |x - x0|^2 },\n # hence x_t = x0 - g_avg / (2 * loc_t),\n # where loc_t := beta_t / t, beta_t := (gamma/2) * sqrt(t).\n x_t = prox_center - (t ** 0.5) / gamma * g_avg\n # weight for the new x_t\n weight_t = t ** (-kappa)\n x_avg = (1 - weight_t) * x_avg + weight_t * x_t\n return x_t, x_avg, g_avg, t, prox_center\n\n return init_fn, update_fn\n\n\ndef welford_covariance(diagonal=True):\n \"\"\"\n Implements Welford's online method for estimating (co)variance. Useful for\n adapting diagonal and dense mass structures for HMC. It is required that\n each sample is a 1-dimensional array.\n\n **References:**\n\n 1. *The Art of Computer Programming*,\n Donald E. Knuth\n\n :param bool diagonal: If True, we estimate the variance of samples.\n Otherwise, we estimate the covariance of the samples. Defaults to True.\n :return: a (`init_fn`, `update_fn`, `final_fn`) triple.\n \"\"\"\n\n def init_fn(size):\n \"\"\"\n :param int size: size of each sample. For a structured mass matrix,\n this is a dict mapping from tuples of site names to the shape\n of the mass matrix.\n :return: initial state for the scheme.\n \"\"\"\n if isinstance(size, dict):\n state = {}\n for site_names, size_block in size.items():\n state[site_names] = init_fn(size_block)\n return state\n\n if isinstance(size, int):\n shape = (size,) if diagonal else (size, size)\n else:\n shape = size\n\n mean = jnp.zeros(shape[-1])\n m2 = jnp.zeros(shape)\n n = 0\n return mean, m2, n\n\n def update_fn(sample, state):\n \"\"\"\n :param sample: A new sample.\n :param state: Current state of the scheme.\n :return: new state for the scheme.\n \"\"\"\n if isinstance(state, dict):\n assert isinstance(sample, dict)\n new_state = {}\n for site_names, state_block in state.items():\n sample_block = tuple(sample[k] for k in site_names)\n new_state[site_names] = update_fn(sample_block, state_block)\n return new_state\n\n sample, _ = ravel_pytree(sample)\n mean, m2, n = state\n n = n + 1\n delta_pre = sample - mean\n mean = mean + delta_pre / n\n delta_post = sample - mean\n if jnp.ndim(m2) == 1:\n m2 = m2 + delta_pre * delta_post\n else:\n m2 = m2 + jnp.outer(delta_post, delta_pre)\n return mean, m2, n\n\n def final_fn(state, regularize=False):\n \"\"\"\n :param state: Current state of the scheme.\n :param bool regularize: Whether to adjust diagonal for numerical stability.\n :return: a triple of estimated covariance, the square root of precision, and\n the inverse of that square root.\n \"\"\"\n if isinstance(state, dict):\n cov, cov_inv_sqrt, tril_inv = {}, {}, {}\n for site_names, state_block in state.items():\n cov_block, cov_inv_sqrt_block, tril_inv_block = final_fn(\n state_block, regularize=regularize\n )\n cov[site_names] = cov_block\n cov_inv_sqrt[site_names] = cov_inv_sqrt_block\n tril_inv[site_names] = tril_inv_block\n return cov, cov_inv_sqrt, tril_inv\n\n mean, m2, n = state\n # XXX it is not necessary to check for the case n=1\n cov = m2 / (n - 1)\n if regularize:\n # Regularization from Stan\n scaled_cov = (n / (n + 5)) * cov\n shrinkage = 1e-3 * (5 / (n + 5))\n if jnp.ndim(scaled_cov) == 1:\n cov = scaled_cov + shrinkage\n else:\n cov = scaled_cov + shrinkage * jnp.identity(mean.shape[0])\n if jnp.ndim(cov) == 2:\n # copy the implementation of distributions.util.cholesky_of_inverse here\n tril_inv = jnp.swapaxes(\n jnp.linalg.cholesky(cov[..., ::-1, ::-1])[..., ::-1, ::-1], -2, -1\n )\n identity = jnp.identity(cov.shape[-1])\n cov_inv_sqrt = solve_triangular(tril_inv, identity, lower=True)\n else:\n tril_inv = jnp.sqrt(cov)\n cov_inv_sqrt = jnp.reciprocal(tril_inv)\n return cov, cov_inv_sqrt, tril_inv\n\n return init_fn, update_fn, final_fn\n\n\ndef _value_and_grad(f, x, forward_mode_differentiation=False):\n if forward_mode_differentiation:\n return f(x), jacfwd(f)(x)\n else:\n return value_and_grad(f)(x)\n\n\ndef _kinetic_grad(kinetic_fn, inverse_mass_matrix, r):\n if hasattr(kinetic_fn, \"_kinetic_grad\"):\n return kinetic_fn._kinetic_grad(inverse_mass_matrix, r)\n else:\n return grad(kinetic_fn, argnums=1)(inverse_mass_matrix, r)\n\n\ndef velocity_verlet(potential_fn, kinetic_fn, forward_mode_differentiation=False):\n r\"\"\"\n Second order symplectic integrator that uses the velocity verlet algorithm\n for position `z` and momentum `r`.\n\n :param potential_fn: Python callable that computes the potential energy\n given input parameters. The input parameters to `potential_fn` can be\n any python collection type.\n :param kinetic_fn: Python callable that returns the kinetic energy given\n inverse mass matrix and momentum.\n :return: a pair of (`init_fn`, `update_fn`).\n \"\"\"\n\n def init_fn(z, r, potential_energy=None, z_grad=None):\n \"\"\"\n :param z: Position of the particle.\n :param r: Momentum of the particle.\n :param potential_energy: Potential energy at `z`.\n :param z_grad: gradient of potential energy at `z`.\n :return: initial state for the integrator.\n \"\"\"\n if potential_energy is None or z_grad is None:\n potential_energy, z_grad = _value_and_grad(\n potential_fn, z, forward_mode_differentiation\n )\n return IntegratorState(z, r, potential_energy, z_grad)\n\n def update_fn(step_size, inverse_mass_matrix, state):\n \"\"\"\n :param float step_size: Size of a single step.\n :param inverse_mass_matrix: Inverse of mass matrix, which is used to\n calculate kinetic energy.\n :param state: Current state of the integrator.\n :return: new state for the integrator.\n \"\"\"\n z, r, _, z_grad = state\n r = tree_multimap(\n lambda r, z_grad: r - 0.5 * step_size * z_grad, r, z_grad\n ) # r(n+1/2)\n r_grad = _kinetic_grad(kinetic_fn, inverse_mass_matrix, r)\n z = tree_multimap(lambda z, r_grad: z + step_size * r_grad, z, r_grad) # z(n+1)\n potential_energy, z_grad = _value_and_grad(\n potential_fn, z, forward_mode_differentiation\n )\n r = tree_multimap(\n lambda r, z_grad: r - 0.5 * step_size * z_grad, r, z_grad\n ) # r(n+1)\n return IntegratorState(z, r, potential_energy, z_grad)\n\n return init_fn, update_fn\n\n\ndef find_reasonable_step_size(\n potential_fn,\n kinetic_fn,\n momentum_generator,\n init_step_size,\n inverse_mass_matrix,\n z_info,\n rng_key,\n):\n \"\"\"\n Finds a reasonable step size by tuning `init_step_size`. This function is used\n to avoid working with a too large or too small step size in HMC.\n\n **References:**\n\n 1. *The No-U-Turn Sampler: Adaptively Setting Path Lengths in Hamiltonian Monte Carlo*,\n Matthew D. Hoffman, Andrew Gelman\n\n :param potential_fn: A callable to compute potential energy.\n :param kinetic_fn: A callable to compute kinetic energy.\n :param momentum_generator: A generator to get a random momentum variable.\n :param float init_step_size: Initial step size to be tuned.\n :param inverse_mass_matrix: Inverse of mass matrix.\n :param IntegratorState z_info: The current integrator state.\n :param jax.random.PRNGKey rng_key: Random key to be used as the source of randomness.\n :return: a reasonable value for step size.\n :rtype: float\n \"\"\"\n # We are going to find a step_size which make accept_prob (Metropolis correction)\n # near the target_accept_prob. If accept_prob:=exp(-delta_energy) is small,\n # then we have to decrease step_size; otherwise, increase step_size.\n target_accept_prob = jnp.log(0.8)\n\n _, vv_update = velocity_verlet(potential_fn, kinetic_fn)\n z, _, potential_energy, z_grad = z_info\n if potential_energy is None or z_grad is None:\n potential_energy, z_grad = value_and_grad(potential_fn)(z)\n finfo = jnp.finfo(jnp.result_type(init_step_size))\n\n def _body_fn(state):\n step_size, _, direction, rng_key = state\n rng_key, rng_key_momentum = random.split(rng_key)\n # scale step_size: increase 2x or decrease 2x depends on direction;\n # direction=1 means keep increasing step_size, otherwise decreasing step_size.\n # Note that the direction is -1 if delta_energy is `NaN`, which may be the\n # case for a diverging trajectory (e.g. in the case of evaluating log prob\n # of a value simulated using a large step size for a constrained sample site).\n step_size = (2.0 ** direction) * step_size\n r = momentum_generator(z, inverse_mass_matrix, rng_key_momentum)\n _, r_new, potential_energy_new, _ = vv_update(\n step_size, inverse_mass_matrix, (z, r, potential_energy, z_grad)\n )\n energy_current = kinetic_fn(inverse_mass_matrix, r) + potential_energy\n energy_new = kinetic_fn(inverse_mass_matrix, r_new) + potential_energy_new\n delta_energy = energy_new - energy_current\n direction_new = jnp.where(target_accept_prob < -delta_energy, 1, -1)\n return step_size, direction, direction_new, rng_key\n\n def _cond_fn(state):\n step_size, last_direction, direction, _ = state\n # condition to run only if step_size is not too small or we are not decreasing step_size\n not_small_step_size_cond = (step_size > finfo.tiny) | (direction >= 0)\n # condition to run only if step_size is not too large or we are not increasing step_size\n not_large_step_size_cond = (step_size < finfo.max) | (direction <= 0)\n not_extreme_cond = not_small_step_size_cond & not_large_step_size_cond\n return not_extreme_cond & (\n (last_direction == 0) | (direction == last_direction)\n )\n\n step_size, _, _, _ = while_loop(_cond_fn, _body_fn, (init_step_size, 0, 0, rng_key))\n return step_size\n\n\ndef build_adaptation_schedule(num_steps):\n \"\"\"\n Builds a window adaptation schedule to be used during warmup phase of HMC.\n\n :param int num_steps: Number of warmup steps.\n :return: a list of contiguous windows, each has attributes `start` and `end`,\n where `start` is the starting index and `end` is the ending index of the window.\n\n **References:**\n\n 1. *Stan Reference Manual version 2.18*,\n Stan Development Team\n \"\"\"\n adaptation_schedule = []\n # from Stan, for small num_steps\n if num_steps < 20:\n adaptation_schedule.append(AdaptWindow(0, num_steps - 1))\n return adaptation_schedule\n\n # We separate num_steps into windows:\n # start_buffer + window 1 + window 2 + window 3 + ... + end_buffer\n # where the length of each window will be doubled for the next window.\n # We won't adapt mass matrix during start and end buffers; and mass\n # matrix will be updated at the end of each window. This is helpful\n # for dealing with the intense computation of sampling momentum from the\n # inverse of mass matrix.\n start_buffer_size = 75 # from Stan\n end_buffer_size = 50 # from Stan\n init_window_size = 25 # from Stan\n if (start_buffer_size + end_buffer_size + init_window_size) > num_steps:\n start_buffer_size = int(0.15 * num_steps)\n end_buffer_size = int(0.1 * num_steps)\n init_window_size = num_steps - start_buffer_size - end_buffer_size\n\n adaptation_schedule.append(AdaptWindow(start=0, end=start_buffer_size - 1))\n end_window_start = num_steps - end_buffer_size\n\n next_window_size = init_window_size\n next_window_start = start_buffer_size\n while next_window_start < end_window_start:\n cur_window_start, cur_window_size = next_window_start, next_window_size\n # Ensure that slow adaptation windows are monotonically increasing\n if 3 * cur_window_size <= end_window_start - cur_window_start:\n next_window_size = 2 * cur_window_size\n else:\n cur_window_size = end_window_start - cur_window_start\n next_window_start = cur_window_start + cur_window_size\n adaptation_schedule.append(AdaptWindow(cur_window_start, next_window_start - 1))\n adaptation_schedule.append(AdaptWindow(end_window_start, num_steps - 1))\n return adaptation_schedule\n\n\ndef _initialize_mass_matrix(z, inverse_mass_matrix, dense_mass):\n if isinstance(dense_mass, list):\n if inverse_mass_matrix is None:\n inverse_mass_matrix = {}\n # if user specifies an ndarray mass matrix, then we convert it to a dict\n elif not isinstance(inverse_mass_matrix, dict):\n inverse_mass_matrix = {tuple(sorted(z)): inverse_mass_matrix}\n mass_matrix_sqrt = {}\n mass_matrix_sqrt_inv = {}\n for site_names in dense_mass:\n inverse_mm = inverse_mass_matrix.get(site_names)\n z_block = tuple(z[k] for k in site_names)\n inverse_mm, mm_sqrt, mm_sqrt_inv = _initialize_mass_matrix(\n z_block, inverse_mm, True\n )\n inverse_mass_matrix[site_names] = inverse_mm\n mass_matrix_sqrt[site_names] = mm_sqrt\n mass_matrix_sqrt_inv[site_names] = mm_sqrt_inv\n # NB: this branch only happens when users want to use block diagonal\n # inverse_mass_matrix, for example, {(\"a\",): jnp.ones(3), (\"b\",): jnp.ones(3)}.\n for site_names, inverse_mm in inverse_mass_matrix.items():\n if site_names in dense_mass:\n continue\n z_block = tuple(z[k] for k in site_names)\n inverse_mm, mm_sqrt, mm_sqrt_inv = _initialize_mass_matrix(\n z_block, inverse_mm, False\n )\n inverse_mass_matrix[site_names] = inverse_mm\n mass_matrix_sqrt[site_names] = mm_sqrt\n mass_matrix_sqrt_inv[site_names] = mm_sqrt_inv\n remaining_sites = tuple(sorted(set(z) - set().union(*inverse_mass_matrix)))\n if len(remaining_sites) > 0:\n z_block = tuple(z[k] for k in remaining_sites)\n inverse_mm, mm_sqrt, mm_sqrt_inv = _initialize_mass_matrix(\n z_block, None, False\n )\n inverse_mass_matrix[remaining_sites] = inverse_mm\n mass_matrix_sqrt[remaining_sites] = mm_sqrt\n mass_matrix_sqrt_inv[remaining_sites] = mm_sqrt_inv\n expected_site_names = sorted(z)\n actual_site_names = sorted(\n [k for site_names in inverse_mass_matrix for k in site_names]\n )\n assert actual_site_names == expected_site_names, (\n \"There seems to be a conflict of sites names specified in the initial\"\n \" `inverse_mass_matrix` and in `dense_mass` argument.\"\n )\n return inverse_mass_matrix, mass_matrix_sqrt, mass_matrix_sqrt_inv\n\n mass_matrix_size = jnp.size(ravel_pytree(z)[0])\n if inverse_mass_matrix is None:\n if dense_mass:\n inverse_mass_matrix = jnp.identity(mass_matrix_size)\n else:\n inverse_mass_matrix = jnp.ones(mass_matrix_size)\n mass_matrix_sqrt = mass_matrix_sqrt_inv = inverse_mass_matrix\n else:\n if dense_mass:\n if jnp.ndim(inverse_mass_matrix) == 1:\n inverse_mass_matrix = jnp.diag(inverse_mass_matrix)\n mass_matrix_sqrt_inv = jnp.swapaxes(\n jnp.linalg.cholesky(inverse_mass_matrix[..., ::-1, ::-1])[\n ..., ::-1, ::-1\n ],\n -2,\n -1,\n )\n identity = jnp.identity(inverse_mass_matrix.shape[-1])\n mass_matrix_sqrt = solve_triangular(\n mass_matrix_sqrt_inv, identity, lower=True\n )\n else:\n if jnp.ndim(inverse_mass_matrix) == 2:\n inverse_mass_matrix = jnp.diag(inverse_mass_matrix)\n mass_matrix_sqrt_inv = jnp.sqrt(inverse_mass_matrix)\n mass_matrix_sqrt = jnp.reciprocal(mass_matrix_sqrt_inv)\n return inverse_mass_matrix, mass_matrix_sqrt, mass_matrix_sqrt_inv\n\n\ndef warmup_adapter(\n num_adapt_steps,\n find_reasonable_step_size=None,\n adapt_step_size=True,\n adapt_mass_matrix=True,\n dense_mass=False,\n target_accept_prob=0.8,\n):\n \"\"\"\n A scheme to adapt tunable parameters, namely step size and mass matrix, during\n the warmup phase of HMC.\n\n :param int num_adapt_steps: Number of warmup steps.\n :param find_reasonable_step_size: A callable to find a reasonable step size\n at the beginning of each adaptation window.\n :param bool adapt_step_size: A flag to decide if we want to adapt step_size\n during warm-up phase using Dual Averaging scheme (defaults to ``True``).\n :param bool adapt_mass_matrix: A flag to decide if we want to adapt mass\n matrix during warm-up phase using Welford scheme (defaults to ``True``).\n :param bool dense_mass: A flag to decide if mass matrix is dense or\n diagonal (defaults to ``False``).\n :param float target_accept_prob: Target acceptance probability for step size\n adaptation using Dual Averaging. Increasing this value will lead to a smaller\n step size, hence the sampling will be slower but more robust. Default to 0.8.\n :return: a pair of (`init_fn`, `update_fn`).\n \"\"\"\n if find_reasonable_step_size is None:\n find_reasonable_step_size = identity\n ss_init, ss_update = dual_averaging()\n mm_init, mm_update, mm_final = welford_covariance(diagonal=not dense_mass)\n adaptation_schedule = jnp.array(build_adaptation_schedule(num_adapt_steps))\n num_windows = len(adaptation_schedule)\n\n def init_fn(\n z_info, rng_key, step_size=1.0, inverse_mass_matrix=None, mass_matrix_size=None\n ):\n \"\"\"\n :param IntegratorState z_info: The initial integrator state.\n :param jax.random.PRNGKey rng_key: Random key to be used as the source of randomness.\n :param float step_size: Initial step size.\n :param inverse_mass_matrix: Inverse of the initial mass matrix. If ``None``,\n inverse of mass matrix will be an identity matrix with size is decided\n by the argument `mass_matrix_size`.\n :param int mass_matrix_size: Size of the mass matrix.\n :return: initial state of the adapt scheme.\n \"\"\"\n rng_key, rng_key_ss = random.split(rng_key)\n (\n inverse_mass_matrix,\n mass_matrix_sqrt,\n mass_matrix_sqrt_inv,\n ) = _initialize_mass_matrix(z_info[0], inverse_mass_matrix, dense_mass)\n\n if adapt_step_size:\n step_size = find_reasonable_step_size(\n step_size, inverse_mass_matrix, z_info, rng_key_ss\n )\n ss_state = ss_init(jnp.log(10 * step_size))\n\n if isinstance(inverse_mass_matrix, dict):\n size = {k: v.shape for k, v in inverse_mass_matrix.items()}\n else:\n size = inverse_mass_matrix.shape[-1]\n mm_state = mm_init(size)\n\n window_idx = jnp.array(0, dtype=jnp.result_type(int))\n return HMCAdaptState(\n step_size,\n inverse_mass_matrix,\n mass_matrix_sqrt,\n mass_matrix_sqrt_inv,\n ss_state,\n mm_state,\n window_idx,\n rng_key,\n )\n\n def _update_at_window_end(z_info, rng_key_ss, state):\n (\n step_size,\n inverse_mass_matrix,\n mass_matrix_sqrt,\n mass_matrix_sqrt_inv,\n ss_state,\n mm_state,\n window_idx,\n rng_key,\n ) = state\n\n if adapt_mass_matrix:\n inverse_mass_matrix, mass_matrix_sqrt, mass_matrix_sqrt_inv = mm_final(\n mm_state, regularize=True\n )\n if isinstance(inverse_mass_matrix, dict):\n size = {k: v.shape for k, v in inverse_mass_matrix.items()}\n else:\n size = inverse_mass_matrix.shape[-1]\n mm_state = mm_init(size)\n\n if adapt_step_size:\n step_size = find_reasonable_step_size(\n step_size, inverse_mass_matrix, z_info, rng_key_ss\n )\n # NB: when step_size is large, say 1e38, jnp.log(10 * step_size) will be inf\n # and jnp.log(10) + jnp.log(step_size) will be finite\n ss_state = ss_init(jnp.log(10) + jnp.log(step_size))\n\n return HMCAdaptState(\n step_size,\n inverse_mass_matrix,\n mass_matrix_sqrt,\n mass_matrix_sqrt_inv,\n ss_state,\n mm_state,\n window_idx,\n rng_key,\n )\n\n def update_fn(t, accept_prob, z_info, state):\n \"\"\"\n :param int t: The current time step.\n :param float accept_prob: Acceptance probability of the current trajectory.\n :param IntegratorState z_info: The new integrator state.\n :param state: Current state of the adapt scheme.\n :return: new state of the adapt scheme.\n \"\"\"\n (\n step_size,\n inverse_mass_matrix,\n mass_matrix_sqrt,\n mass_matrix_sqrt_inv,\n ss_state,\n mm_state,\n window_idx,\n rng_key,\n ) = state\n if rng_key is not None:\n rng_key, rng_key_ss = random.split(rng_key)\n else:\n rng_key_ss = None\n\n # update step size state\n if adapt_step_size:\n ss_state = ss_update(target_accept_prob - accept_prob, ss_state)\n # note: at the end of warmup phase, use average of log step_size\n log_step_size, log_step_size_avg, *_ = ss_state\n step_size = jnp.where(\n t == (num_adapt_steps - 1),\n jnp.exp(log_step_size_avg),\n jnp.exp(log_step_size),\n )\n # account the the case log_step_size is an extreme number\n finfo = jnp.finfo(jnp.result_type(step_size))\n step_size = jnp.clip(step_size, a_min=finfo.tiny, a_max=finfo.max)\n\n # update mass matrix state\n is_middle_window = (0 < window_idx) & (window_idx < (num_windows - 1))\n if adapt_mass_matrix:\n z = z_info[0]\n mm_state = cond(\n is_middle_window,\n (z, mm_state),\n lambda args: mm_update(*args),\n mm_state,\n identity,\n )\n\n t_at_window_end = t == adaptation_schedule[window_idx, 1]\n window_idx = jnp.where(t_at_window_end, window_idx + 1, window_idx)\n state = HMCAdaptState(\n step_size,\n inverse_mass_matrix,\n mass_matrix_sqrt,\n mass_matrix_sqrt_inv,\n ss_state,\n mm_state,\n window_idx,\n rng_key,\n )\n state = cond(\n t_at_window_end & is_middle_window,\n (z_info, rng_key_ss, state),\n lambda args: _update_at_window_end(*args),\n state,\n identity,\n )\n return state\n\n return init_fn, update_fn\n\n\ndef _momentum_angle(inverse_mass_matrix, r_left, r_right, r_sum):\n if isinstance(inverse_mass_matrix, dict):\n left_angle, right_angle = jnp.zeros(()), jnp.zeros(())\n for site_names, inverse_mm in inverse_mass_matrix.items():\n r_left_b = tuple(r_left[k] for k in site_names)\n r_right_b = tuple(r_right[k] for k in site_names)\n r_sum_b = tuple(r_sum[k] for k in site_names)\n left_a, right_a = _momentum_angle(inverse_mm, r_left_b, r_right_b, r_sum_b)\n left_angle = left_angle + left_a\n right_angle = right_angle + right_a\n return left_angle, right_angle\n\n r_left, _ = ravel_pytree(r_left)\n r_right, _ = ravel_pytree(r_right)\n r_sum, _ = ravel_pytree(r_sum)\n\n if inverse_mass_matrix.ndim == 2:\n v_left = jnp.matmul(inverse_mass_matrix, r_left)\n v_right = jnp.matmul(inverse_mass_matrix, r_right)\n elif inverse_mass_matrix.ndim == 1:\n v_left = jnp.multiply(inverse_mass_matrix, r_left)\n v_right = jnp.multiply(inverse_mass_matrix, r_right)\n else:\n raise ValueError(\"inverse_mass_matrix should have 1 or 2 dimensions.\")\n\n # This implements dynamic termination criterion (ref [2], section A.4.2).\n r_sum = r_sum - (r_left + r_right) / 2\n return jnp.dot(v_left, r_sum), jnp.dot(v_right, r_sum)\n\n\ndef _is_turning(inverse_mass_matrix, r_left, r_right, r_sum):\n left_angle, right_angle = _momentum_angle(\n inverse_mass_matrix, r_left, r_right, r_sum\n )\n turning_at_left = left_angle <= 0\n turning_at_right = right_angle <= 0\n return turning_at_left | turning_at_right\n\n\ndef _uniform_transition_kernel(current_tree, new_tree):\n # This function computes transition prob for subtrees (ref [2], section A.3.1).\n # e^new_weight / (e^new_weight + e^current_weight)\n transition_prob = expit(new_tree.weight - current_tree.weight)\n return transition_prob\n\n\ndef _biased_transition_kernel(current_tree, new_tree):\n # This function computes transition prob for main trees (ref [2], section A.3.2).\n transition_prob = jnp.exp(new_tree.weight - current_tree.weight)\n # If new tree is turning or diverging, we won't move the proposal\n # to the new tree.\n transition_prob = jnp.where(\n new_tree.turning | new_tree.diverging, 0.0, jnp.clip(transition_prob, a_max=1.0)\n )\n return transition_prob\n\n\ndef _combine_tree(\n current_tree, new_tree, inverse_mass_matrix, going_right, rng_key, biased_transition\n):\n # Now we combine the current tree and the new tree. Note that outside\n # leaves of the combined tree are determined by the direction.\n z_left, r_left, z_left_grad, z_right, r_right, r_right_grad = cond(\n going_right,\n (current_tree, new_tree),\n lambda trees: (\n trees[0].z_left,\n trees[0].r_left,\n trees[0].z_left_grad,\n trees[1].z_right,\n trees[1].r_right,\n trees[1].z_right_grad,\n ),\n (new_tree, current_tree),\n lambda trees: (\n trees[0].z_left,\n trees[0].r_left,\n trees[0].z_left_grad,\n trees[1].z_right,\n trees[1].r_right,\n trees[1].z_right_grad,\n ),\n )\n r_sum = tree_multimap(jnp.add, current_tree.r_sum, new_tree.r_sum)\n\n if biased_transition:\n transition_prob = _biased_transition_kernel(current_tree, new_tree)\n turning = new_tree.turning | _is_turning(\n inverse_mass_matrix, r_left, r_right, r_sum\n )\n else:\n transition_prob = _uniform_transition_kernel(current_tree, new_tree)\n turning = current_tree.turning\n\n transition = random.bernoulli(rng_key, transition_prob)\n z_proposal, z_proposal_pe, z_proposal_grad, z_proposal_energy = cond(\n transition,\n new_tree,\n lambda tree: (\n tree.z_proposal,\n tree.z_proposal_pe,\n tree.z_proposal_grad,\n tree.z_proposal_energy,\n ),\n current_tree,\n lambda tree: (\n tree.z_proposal,\n tree.z_proposal_pe,\n tree.z_proposal_grad,\n tree.z_proposal_energy,\n ),\n )\n\n tree_depth = current_tree.depth + 1\n tree_weight = jnp.logaddexp(current_tree.weight, new_tree.weight)\n diverging = new_tree.diverging\n\n sum_accept_probs = current_tree.sum_accept_probs + new_tree.sum_accept_probs\n num_proposals = current_tree.num_proposals + new_tree.num_proposals\n\n return TreeInfo(\n z_left,\n r_left,\n z_left_grad,\n z_right,\n r_right,\n r_right_grad,\n z_proposal,\n z_proposal_pe,\n z_proposal_grad,\n z_proposal_energy,\n tree_depth,\n tree_weight,\n r_sum,\n turning,\n diverging,\n sum_accept_probs,\n num_proposals,\n )\n\n\ndef _build_basetree(\n vv_update,\n kinetic_fn,\n z,\n r,\n z_grad,\n inverse_mass_matrix,\n step_size,\n going_right,\n energy_current,\n max_delta_energy,\n):\n step_size = jnp.where(going_right, step_size, -step_size)\n z_new, r_new, potential_energy_new, z_new_grad = vv_update(\n step_size, inverse_mass_matrix, (z, r, energy_current, z_grad)\n )\n\n energy_new = potential_energy_new + kinetic_fn(inverse_mass_matrix, r_new)\n delta_energy = energy_new - energy_current\n # Handles the NaN case.\n delta_energy = jnp.where(jnp.isnan(delta_energy), jnp.inf, delta_energy)\n tree_weight = -delta_energy\n\n diverging = delta_energy > max_delta_energy\n accept_prob = jnp.clip(jnp.exp(-delta_energy), a_max=1.0)\n return TreeInfo(\n z_new,\n r_new,\n z_new_grad,\n z_new,\n r_new,\n z_new_grad,\n z_new,\n potential_energy_new,\n z_new_grad,\n energy_new,\n depth=0,\n weight=tree_weight,\n r_sum=r_new,\n turning=False,\n diverging=diverging,\n sum_accept_probs=accept_prob,\n num_proposals=1,\n )\n\n\ndef _get_leaf(tree, going_right):\n return cond(\n going_right,\n tree,\n lambda tree: (tree.z_right, tree.r_right, tree.z_right_grad),\n tree,\n lambda tree: (tree.z_left, tree.r_left, tree.z_left_grad),\n )\n\n\ndef _double_tree(\n current_tree,\n vv_update,\n kinetic_fn,\n inverse_mass_matrix,\n step_size,\n going_right,\n rng_key,\n energy_current,\n max_delta_energy,\n r_ckpts,\n r_sum_ckpts,\n):\n key, transition_key = random.split(rng_key)\n\n new_tree = _iterative_build_subtree(\n current_tree,\n vv_update,\n kinetic_fn,\n inverse_mass_matrix,\n step_size,\n going_right,\n key,\n energy_current,\n max_delta_energy,\n r_ckpts,\n r_sum_ckpts,\n )\n\n return _combine_tree(\n current_tree, new_tree, inverse_mass_matrix, going_right, transition_key, True\n )\n\n\ndef _leaf_idx_to_ckpt_idxs(n):\n # computes the number of non-zero bits except the last bit\n # e.g. 6 -> 2, 7 -> 2, 13 -> 2\n _, idx_max = while_loop(\n lambda nc: nc[0] > 0, lambda nc: (nc[0] >> 1, nc[1] + (nc[0] & 1)), (n >> 1, 0)\n )\n # computes the number of contiguous last non-zero bits\n # e.g. 6 -> 0, 7 -> 3, 13 -> 1\n _, num_subtrees = while_loop(\n lambda nc: (nc[0] & 1) != 0, lambda nc: (nc[0] >> 1, nc[1] + 1), (n, 0)\n )\n # TODO: explore the potential of setting idx_min=0 to allow more turning checks\n # It will be useful in case: e.g. assume a tree 0 -> 7 is a circle,\n # subtrees 0 -> 3, 4 -> 7 are half-circles, which two leaves might not\n # satisfy turning condition;\n # the full tree 0 -> 7 is a circle, which two leaves might also not satisfy\n # turning condition;\n # however, we can check the turning condition of the subtree 0 -> 5, which\n # likely satisfies turning condition because its trajectory 3/4 of a circle.\n # XXX: make sure that detailed balance is satisfied if we follow this direction\n idx_min = idx_max - num_subtrees + 1\n return idx_min, idx_max\n\n\ndef _is_iterative_turning(\n inverse_mass_matrix,\n r,\n r_sum,\n r_ckpts,\n r_sum_ckpts,\n idx_min,\n idx_max,\n unravel_fn=identity,\n):\n def _body_fn(state):\n i, _ = state\n subtree_r_sum = r_sum - r_sum_ckpts[i] + r_ckpts[i]\n subtree_r_sum = unravel_fn(subtree_r_sum)\n r_left = unravel_fn(r_ckpts[i])\n return i - 1, _is_turning(inverse_mass_matrix, r_left, r, subtree_r_sum)\n\n _, turning = while_loop(\n lambda it: (it[0] >= idx_min) & ~it[1], _body_fn, (idx_max, False)\n )\n return turning\n\n\ndef _iterative_build_subtree(\n prototype_tree,\n vv_update,\n kinetic_fn,\n inverse_mass_matrix,\n step_size,\n going_right,\n rng_key,\n energy_current,\n max_delta_energy,\n r_ckpts,\n r_sum_ckpts,\n):\n max_num_proposals = 2 ** prototype_tree.depth\n\n def _cond_fn(state):\n tree, turning, _, _, _ = state\n return (tree.num_proposals < max_num_proposals) & ~turning & ~tree.diverging\n\n def _body_fn(state):\n current_tree, _, r_ckpts, r_sum_ckpts, rng_key = state\n rng_key, transition_rng_key = random.split(rng_key)\n # If we are going to the right, start from the right leaf of the current tree.\n z, r, z_grad = _get_leaf(current_tree, going_right)\n new_leaf = _build_basetree(\n vv_update,\n kinetic_fn,\n z,\n r,\n z_grad,\n inverse_mass_matrix,\n step_size,\n going_right,\n energy_current,\n max_delta_energy,\n )\n new_tree = cond(\n current_tree.num_proposals == 0,\n new_leaf,\n identity,\n (\n current_tree,\n new_leaf,\n inverse_mass_matrix,\n going_right,\n transition_rng_key,\n ),\n lambda x: _combine_tree(*x, False),\n )\n\n leaf_idx = current_tree.num_proposals\n # NB: in the special case leaf_idx=0, ckpt_idx_min=1 and ckpt_idx_max=0,\n # the following logic is still valid for that case\n ckpt_idx_min, ckpt_idx_max = _leaf_idx_to_ckpt_idxs(leaf_idx)\n r, unravel_fn = ravel_pytree(new_leaf.r_right)\n r_sum, _ = ravel_pytree(new_tree.r_sum)\n # we update checkpoints when leaf_idx is even\n r_ckpts, r_sum_ckpts = cond(\n leaf_idx % 2 == 0,\n (r_ckpts, r_sum_ckpts),\n lambda x: (\n index_update(x[0], ckpt_idx_max, r),\n index_update(x[1], ckpt_idx_max, r_sum),\n ),\n (r_ckpts, r_sum_ckpts),\n identity,\n )\n\n turning = _is_iterative_turning(\n inverse_mass_matrix,\n new_leaf.r_right,\n r_sum,\n r_ckpts,\n r_sum_ckpts,\n ckpt_idx_min,\n ckpt_idx_max,\n unravel_fn,\n )\n return new_tree, turning, r_ckpts, r_sum_ckpts, rng_key\n\n basetree = prototype_tree._replace(num_proposals=0)\n\n tree, turning, _, _, _ = while_loop(\n _cond_fn, _body_fn, (basetree, False, r_ckpts, r_sum_ckpts, rng_key)\n )\n # update depth and turning condition\n return TreeInfo(\n tree.z_left,\n tree.r_left,\n tree.z_left_grad,\n tree.z_right,\n tree.r_right,\n tree.z_right_grad,\n tree.z_proposal,\n tree.z_proposal_pe,\n tree.z_proposal_grad,\n tree.z_proposal_energy,\n prototype_tree.depth,\n tree.weight,\n tree.r_sum,\n turning,\n tree.diverging,\n tree.sum_accept_probs,\n tree.num_proposals,\n )\n\n\ndef build_tree(\n verlet_update,\n kinetic_fn,\n verlet_state,\n inverse_mass_matrix,\n step_size,\n rng_key,\n max_delta_energy=1000.0,\n max_tree_depth=10,\n):\n \"\"\"\n Builds a binary tree from the `verlet_state`. This is used in NUTS sampler.\n\n **References:**\n\n 1. *The No-U-Turn Sampler: Adaptively Setting Path Lengths in Hamiltonian Monte Carlo*,\n Matthew D. Hoffman, Andrew Gelman\n 2. *A Conceptual Introduction to Hamiltonian Monte Carlo*,\n Michael Betancourt\n\n :param verlet_update: A callable to get a new integrator state given a current\n integrator state.\n :param kinetic_fn: A callable to compute kinetic energy.\n :param verlet_state: Initial integrator state.\n :param inverse_mass_matrix: Inverse of the mass matrix.\n :param float step_size: Step size for the current trajectory.\n :param jax.random.PRNGKey rng_key: random key to be used as the source of\n randomness.\n :param float max_delta_energy: A threshold to decide if the new state diverges\n (based on the energy difference) too much from the initial integrator state.\n :return: information of the tree.\n :rtype: :data:`TreeInfo`\n \"\"\"\n z, r, potential_energy, z_grad = verlet_state\n energy_current = potential_energy + kinetic_fn(inverse_mass_matrix, r)\n latent_size = jnp.size(ravel_pytree(r)[0])\n r_ckpts = jnp.zeros((max_tree_depth, latent_size))\n r_sum_ckpts = jnp.zeros((max_tree_depth, latent_size))\n\n tree = TreeInfo(\n z,\n r,\n z_grad,\n z,\n r,\n z_grad,\n z,\n potential_energy,\n z_grad,\n energy_current,\n depth=0,\n weight=jnp.zeros(()),\n r_sum=r,\n turning=jnp.array(False),\n diverging=jnp.array(False),\n sum_accept_probs=jnp.zeros(()),\n num_proposals=jnp.array(0, dtype=jnp.result_type(int)),\n )\n\n def _cond_fn(state):\n tree, _ = state\n return (tree.depth < max_tree_depth) & ~tree.turning & ~tree.diverging\n\n def _body_fn(state):\n tree, key = state\n key, direction_key, doubling_key = random.split(key, 3)\n going_right = random.bernoulli(direction_key)\n tree = _double_tree(\n tree,\n verlet_update,\n kinetic_fn,\n inverse_mass_matrix,\n step_size,\n going_right,\n doubling_key,\n energy_current,\n max_delta_energy,\n r_ckpts,\n r_sum_ckpts,\n )\n return tree, key\n\n state = (tree, rng_key)\n tree, _ = while_loop(_cond_fn, _body_fn, state)\n return tree\n\n\ndef euclidean_kinetic_energy(inverse_mass_matrix, r):\n if isinstance(inverse_mass_matrix, dict):\n ke = jnp.zeros(())\n for site_names, inverse_mm in inverse_mass_matrix.items():\n r_block = tuple(r[k] for k in site_names)\n ke = ke + euclidean_kinetic_energy(inverse_mm, r_block)\n return ke\n\n r, _ = ravel_pytree(r)\n\n if inverse_mass_matrix.ndim == 2:\n v = jnp.matmul(inverse_mass_matrix, r)\n elif inverse_mass_matrix.ndim == 1:\n v = jnp.multiply(inverse_mass_matrix, r)\n else:\n raise ValueError(\"inverse_mass_matrix should have 1 or 2 dimensions.\")\n\n return 0.5 * jnp.dot(v, r)\n\n\ndef _euclidean_kinetic_energy_grad(inverse_mass_matrix, r):\n if isinstance(inverse_mass_matrix, dict):\n r_grad = {}\n for site_names, inverse_mm in inverse_mass_matrix.items():\n r_block = OrderedDict([(k, r[k]) for k in site_names])\n r_grad.update(_euclidean_kinetic_energy_grad(inverse_mm, r_block))\n return r_grad\n\n r, unravel_fn = ravel_pytree(r)\n\n if inverse_mass_matrix.ndim == 2:\n v = jnp.matmul(inverse_mass_matrix, r)\n elif inverse_mass_matrix.ndim == 1:\n v = jnp.multiply(inverse_mass_matrix, r)\n else:\n raise ValueError(\"inverse_mass_matrix should have 1 or 2 dimensions.\")\n\n return unravel_fn(v)\n\n\neuclidean_kinetic_energy._kinetic_grad = _euclidean_kinetic_energy_grad\n\n\ndef consensus(subposteriors, num_draws=None, diagonal=False, rng_key=None):\n \"\"\"\n Merges subposteriors following consensus Monte Carlo algorithm.\n\n **References:**\n\n 1. *Bayes and big data: The consensus Monte Carlo algorithm*,\n Steven L. Scott, Alexander W. Blocker, Fernando V. Bonassi, Hugh A. Chipman,\n Edward I. George, Robert E. McCulloch\n\n :param list subposteriors: a list in which each element is a collection of samples.\n :param int num_draws: number of draws from the merged posterior.\n :param bool diagonal: whether to compute weights using variance or covariance, defaults to\n `False` (using covariance).\n :param jax.random.PRNGKey rng_key: source of the randomness, defaults to `jax.random.PRNGKey(0)`.\n :return: if `num_draws` is None, merges subposteriors without resampling; otherwise, returns\n a collection of `num_draws` samples with the same data structure as each subposterior.\n \"\"\"\n # stack subposteriors\n joined_subposteriors = tree_multimap(lambda *args: jnp.stack(args), *subposteriors)\n # shape of joined_subposteriors: n_subs x n_samples x sample_shape\n joined_subposteriors = vmap(vmap(lambda sample: ravel_pytree(sample)[0]))(\n joined_subposteriors\n )\n\n if num_draws is not None:\n rng_key = random.PRNGKey(0) if rng_key is None else rng_key\n # randomly gets num_draws from subposteriors\n n_subs = len(subposteriors)\n n_samples = tree_flatten(subposteriors[0])[0][0].shape[0]\n # shape of draw_idxs: n_subs x num_draws x sample_shape\n draw_idxs = random.randint(\n rng_key, shape=(n_subs, num_draws), minval=0, maxval=n_samples\n )\n joined_subposteriors = vmap(lambda x, idx: x[idx])(\n joined_subposteriors, draw_idxs\n )\n\n if diagonal:\n # compute weights for each subposterior (ref: Section 3.1 of [1])\n weights = vmap(lambda x: 1 / jnp.var(x, ddof=1, axis=0))(joined_subposteriors)\n normalized_weights = weights / jnp.sum(weights, axis=0)\n # get weighted samples\n samples_flat = jnp.einsum(\n \"ij,ikj->kj\", normalized_weights, joined_subposteriors\n )\n else:\n weights = vmap(lambda x: jnp.linalg.inv(jnp.cov(x.T)))(joined_subposteriors)\n normalized_weights = jnp.matmul(\n jnp.linalg.inv(jnp.sum(weights, axis=0)), weights\n )\n samples_flat = jnp.einsum(\n \"ijk,ilk->lj\", normalized_weights, joined_subposteriors\n )\n\n # unravel_fn acts on 1 sample of a subposterior\n _, unravel_fn = ravel_pytree(tree_map(lambda x: x[0], subposteriors[0]))\n return vmap(lambda x: unravel_fn(x))(samples_flat)\n\n\ndef parametric(subposteriors, diagonal=False):\n \"\"\"\n Merges subposteriors following (embarrassingly parallel) parametric Monte Carlo algorithm.\n\n **References:**\n\n 1. *Asymptotically Exact, Embarrassingly Parallel MCMC*,\n Willie Neiswanger, Chong Wang, Eric Xing\n\n :param list subposteriors: a list in which each element is a collection of samples.\n :param bool diagonal: whether to compute weights using variance or covariance, defaults to\n `False` (using covariance).\n :return: the estimated mean and variance/covariance parameters of the joined posterior\n \"\"\"\n joined_subposteriors = tree_multimap(lambda *args: jnp.stack(args), *subposteriors)\n joined_subposteriors = vmap(vmap(lambda sample: ravel_pytree(sample)[0]))(\n joined_subposteriors\n )\n\n submeans = jnp.mean(joined_subposteriors, axis=1)\n if diagonal:\n weights = vmap(lambda x: 1 / jnp.var(x, ddof=1, axis=0))(joined_subposteriors)\n var = 1 / jnp.sum(weights, axis=0)\n normalized_weights = var * weights\n\n # comparing to consensus implementation, we compute weighted mean here\n mean = jnp.einsum(\"ij,ij->j\", normalized_weights, submeans)\n return mean, var\n else:\n weights = vmap(lambda x: jnp.linalg.inv(jnp.cov(x.T)))(joined_subposteriors)\n cov = jnp.linalg.inv(jnp.sum(weights, axis=0))\n normalized_weights = jnp.matmul(cov, weights)\n\n # comparing to consensus implementation, we compute weighted mean here\n mean = jnp.einsum(\"ijk,ik->j\", normalized_weights, submeans)\n return mean, cov\n\n\ndef parametric_draws(subposteriors, num_draws, diagonal=False, rng_key=None):\n \"\"\"\n Merges subposteriors following (embarrassingly parallel) parametric Monte Carlo algorithm.\n\n **References:**\n\n 1. *Asymptotically Exact, Embarrassingly Parallel MCMC*,\n Willie Neiswanger, Chong Wang, Eric Xing\n\n :param list subposteriors: a list in which each element is a collection of samples.\n :param int num_draws: number of draws from the merged posterior.\n :param bool diagonal: whether to compute weights using variance or covariance, defaults to\n `False` (using covariance).\n :param jax.random.PRNGKey rng_key: source of the randomness, defaults to `jax.random.PRNGKey(0)`.\n :return: a collection of `num_draws` samples with the same data structure as each subposterior.\n \"\"\"\n rng_key = random.PRNGKey(0) if rng_key is None else rng_key\n if diagonal:\n mean, var = parametric(subposteriors, diagonal=True)\n samples_flat = dist.Normal(mean, jnp.sqrt(var)).sample(rng_key, (num_draws,))\n else:\n mean, cov = parametric(subposteriors, diagonal=False)\n samples_flat = dist.MultivariateNormal(mean, cov).sample(rng_key, (num_draws,))\n\n _, unravel_fn = ravel_pytree(tree_map(lambda x: x[0], subposteriors[0]))\n return vmap(lambda x: unravel_fn(x))(samples_flat)\n", "path": "numpyro/infer/hmc_util.py" }, { "content": "# Copyright Contributors to the Pyro project.\n# SPDX-License-Identifier: Apache-2.0\n\nfrom collections import OrderedDict, namedtuple\nimport math\nimport os\n\nfrom jax import device_put, lax, partial, random, vmap\nfrom jax.flatten_util import ravel_pytree\nimport jax.numpy as jnp\n\nfrom numpyro.infer.hmc_util import (\n IntegratorState,\n build_tree,\n euclidean_kinetic_energy,\n find_reasonable_step_size,\n velocity_verlet,\n warmup_adapter,\n)\nfrom numpyro.infer.mcmc import MCMCKernel\nfrom numpyro.infer.util import ParamInfo, init_to_uniform, initialize_model\nfrom numpyro.util import cond, fori_loop, identity\n\nHMCState = namedtuple(\n \"HMCState\",\n [\n \"i\",\n \"z\",\n \"z_grad\",\n \"potential_energy\",\n \"energy\",\n \"r\",\n \"trajectory_length\",\n \"num_steps\",\n \"accept_prob\",\n \"mean_accept_prob\",\n \"diverging\",\n \"adapt_state\",\n \"rng_key\",\n ],\n)\n\"\"\"\nA :func:`~collections.namedtuple` consisting of the following fields:\n\n - **i** - iteration. This is reset to 0 after warmup.\n - **z** - Python collection representing values (unconstrained samples from\n the posterior) at latent sites.\n - **z_grad** - Gradient of potential energy w.r.t. latent sample sites.\n - **potential_energy** - Potential energy computed at the given value of ``z``.\n - **energy** - Sum of potential energy and kinetic energy of the current state.\n - **r** - The current momentum variable. If this is None, a new momentum variable\n will be drawn at the beginning of each sampling step.\n - **trajectory_length** - The amount of time to run HMC dynamics in each sampling step.\n This field is not used in NUTS.\n - **num_steps** - Number of steps in the Hamiltonian trajectory (for diagnostics).\n In NUTS sampler, the tree depth of a trajectory can be computed from this field\n with `tree_depth = np.log2(num_steps).astype(int) + 1`.\n - **accept_prob** - Acceptance probability of the proposal. Note that ``z``\n does not correspond to the proposal if it is rejected.\n - **mean_accept_prob** - Mean acceptance probability until current iteration\n during warmup adaptation or sampling (for diagnostics).\n - **diverging** - A boolean value to indicate whether the current trajectory is diverging.\n - **adapt_state** - A ``HMCAdaptState`` namedtuple which contains adaptation information\n during warmup:\n\n + **step_size** - Step size to be used by the integrator in the next iteration.\n + **inverse_mass_matrix** - The inverse mass matrix to be used for the next\n iteration.\n + **mass_matrix_sqrt** - The square root of mass matrix to be used for the next\n iteration. In case of dense mass, this is the Cholesky factorization of the\n mass matrix.\n\n - **rng_key** - random number generator seed used for the iteration.\n\"\"\"\n\n\ndef _get_num_steps(step_size, trajectory_length):\n num_steps = jnp.ceil(trajectory_length / step_size)\n # NB: casting to jnp.int64 does not take effect (returns jnp.int32 instead)\n # if jax_enable_x64 is False\n return num_steps.astype(jnp.result_type(int))\n\n\ndef momentum_generator(prototype_r, mass_matrix_sqrt, rng_key):\n if isinstance(mass_matrix_sqrt, dict):\n rng_keys = random.split(rng_key, len(mass_matrix_sqrt))\n r = {}\n for (site_names, mm_sqrt), rng_key in zip(mass_matrix_sqrt.items(), rng_keys):\n r_block = OrderedDict([(k, prototype_r[k]) for k in site_names])\n r.update(momentum_generator(r_block, mm_sqrt, rng_key))\n return r\n\n _, unpack_fn = ravel_pytree(prototype_r)\n eps = random.normal(rng_key, jnp.shape(mass_matrix_sqrt)[:1])\n if mass_matrix_sqrt.ndim == 1:\n r = jnp.multiply(mass_matrix_sqrt, eps)\n return unpack_fn(r)\n elif mass_matrix_sqrt.ndim == 2:\n r = jnp.dot(mass_matrix_sqrt, eps)\n return unpack_fn(r)\n else:\n raise ValueError(\"Mass matrix has incorrect number of dims.\")\n\n\ndef hmc(potential_fn=None, potential_fn_gen=None, kinetic_fn=None, algo=\"NUTS\"):\n r\"\"\"\n Hamiltonian Monte Carlo inference, using either fixed number of\n steps or the No U-Turn Sampler (NUTS) with adaptive path length.\n\n **References:**\n\n 1. *MCMC Using Hamiltonian Dynamics*,\n Radford M. Neal\n 2. *The No-U-turn sampler: adaptively setting path lengths in Hamiltonian Monte Carlo*,\n Matthew D. Hoffman, and Andrew Gelman.\n 3. *A Conceptual Introduction to Hamiltonian Monte Carlo`*,\n Michael Betancourt\n\n :param potential_fn: Python callable that computes the potential energy\n given input parameters. The input parameters to `potential_fn` can be\n any python collection type, provided that `init_params` argument to\n `init_kernel` has the same type.\n :param potential_fn_gen: Python callable that when provided with model\n arguments / keyword arguments returns `potential_fn`. This\n may be provided to do inference on the same model with changing data.\n If the data shape remains the same, we can compile `sample_kernel`\n once, and use the same for multiple inference runs.\n :param kinetic_fn: Python callable that returns the kinetic energy given\n inverse mass matrix and momentum. If not provided, the default is\n euclidean kinetic energy.\n :param str algo: Whether to run ``HMC`` with fixed number of steps or ``NUTS``\n with adaptive path length. Default is ``NUTS``.\n :return: a tuple of callables (`init_kernel`, `sample_kernel`), the first\n one to initialize the sampler, and the second one to generate samples\n given an existing one.\n\n .. warning::\n Instead of using this interface directly, we would highly recommend you\n to use the higher level :class:`numpyro.infer.MCMC` API instead.\n\n **Example**\n\n .. doctest::\n\n >>> import jax\n >>> from jax import random\n >>> import jax.numpy as jnp\n >>> import numpyro\n >>> import numpyro.distributions as dist\n >>> from numpyro.infer.hmc import hmc\n >>> from numpyro.infer.util import initialize_model\n >>> from numpyro.util import fori_collect\n\n >>> true_coefs = jnp.array([1., 2., 3.])\n >>> data = random.normal(random.PRNGKey(2), (2000, 3))\n >>> labels = dist.Bernoulli(logits=(true_coefs * data).sum(-1)).sample(random.PRNGKey(3))\n >>>\n >>> def model(data, labels):\n ... coefs = numpyro.sample('coefs', dist.Normal(jnp.zeros(3), jnp.ones(3)))\n ... intercept = numpyro.sample('intercept', dist.Normal(0., 10.))\n ... return numpyro.sample('y', dist.Bernoulli(logits=(coefs * data + intercept).sum(-1)), obs=labels)\n >>>\n >>> model_info = initialize_model(random.PRNGKey(0), model, model_args=(data, labels,))\n >>> init_kernel, sample_kernel = hmc(model_info.potential_fn, algo='NUTS')\n >>> hmc_state = init_kernel(model_info.param_info,\n ... trajectory_length=10,\n ... num_warmup=300)\n >>> samples = fori_collect(0, 500, sample_kernel, hmc_state,\n ... transform=lambda state: model_info.postprocess_fn(state.z))\n >>> print(jnp.mean(samples['coefs'], axis=0)) # doctest: +SKIP\n [0.9153987 2.0754058 2.9621222]\n \"\"\"\n if kinetic_fn is None:\n kinetic_fn = euclidean_kinetic_energy\n vv_update = None\n max_treedepth = None\n wa_update = None\n wa_steps = None\n forward_mode_ad = False\n max_delta_energy = 1000.0\n if algo not in {\"HMC\", \"NUTS\"}:\n raise ValueError(\"`algo` must be one of `HMC` or `NUTS`.\")\n\n def init_kernel(\n init_params,\n num_warmup,\n step_size=1.0,\n inverse_mass_matrix=None,\n adapt_step_size=True,\n adapt_mass_matrix=True,\n dense_mass=False,\n target_accept_prob=0.8,\n trajectory_length=2 * math.pi,\n max_tree_depth=10,\n find_heuristic_step_size=False,\n forward_mode_differentiation=False,\n model_args=(),\n model_kwargs=None,\n rng_key=random.PRNGKey(0),\n ):\n \"\"\"\n Initializes the HMC sampler.\n\n :param init_params: Initial parameters to begin sampling. The type must\n be consistent with the input type to `potential_fn`.\n :param int num_warmup: Number of warmup steps; samples generated\n during warmup are discarded.\n :param float step_size: Determines the size of a single step taken by the\n verlet integrator while computing the trajectory using Hamiltonian\n dynamics. If not specified, it will be set to 1.\n :param inverse_mass_matrix: Initial value for inverse mass matrix.\n This may be adapted during warmup if adapt_mass_matrix = True.\n If no value is specified, then it is initialized to the identity matrix.\n For a potential_fn with general JAX pytree parameters, the order of entries\n of the mass matrix is the order of the flattened version of pytree parameters\n obtained with `jax.tree_flatten`, which is a bit ambiguous (see more at\n https://jax.readthedocs.io/en/latest/pytrees.html). If `model` is not None,\n here we can specify a structured block mass matrix as a dictionary, where\n keys are tuple of site names and values are the corresponding block of the\n mass matrix.\n For more information about structured mass matrix, see `dense_mass` argument.\n :type inverse_mass_matrix: numpy.ndarray or dict\n :param bool adapt_step_size: A flag to decide if we want to adapt step_size\n during warm-up phase using Dual Averaging scheme.\n :param bool adapt_mass_matrix: A flag to decide if we want to adapt mass\n matrix during warm-up phase using Welford scheme.\n :param dense_mass: This flag controls whether mass matrix is dense (i.e. full-rank) or\n diagonal (defaults to ``dense_mass=False``). To specify a structured mass matrix,\n users can provide a list of tuples of site names. Each tuple represents\n a block in the joint mass matrix. For example, assuming that the model\n has latent variables \"x\", \"y\", \"z\" (where each variable can be multi-dimensional),\n possible specifications and corresponding mass matrix structures are as follows:\n\n + dense_mass=[(\"x\", \"y\")]: use a dense mass matrix for the joint\n (x, y) and a diagonal mass matrix for z\n + dense_mass=[] (equivalent to dense_mass=False): use a diagonal mass\n matrix for the joint (x, y, z)\n + dense_mass=[(\"x\", \"y\", \"z\")] (equivalent to full_mass=True):\n use a dense mass matrix for the joint (x, y, z)\n + dense_mass=[(\"x\",), (\"y\",), (\"z\")]: use dense mass matrices for\n each of x, y, and z (i.e. block-diagonal with 3 blocks)\n\n :type dense_mass: bool or list\n :param float target_accept_prob: Target acceptance probability for step size\n adaptation using Dual Averaging. Increasing this value will lead to a smaller\n step size, hence the sampling will be slower but more robust. Default to 0.8.\n :param float trajectory_length: Length of a MCMC trajectory for HMC. Default\n value is :math:`2\\\\pi`.\n :param int max_tree_depth: Max depth of the binary tree created during the doubling\n scheme of NUTS sampler. Defaults to 10.\n :param bool find_heuristic_step_size: whether to a heuristic function to adjust the\n step size at the beginning of each adaptation window. Defaults to False.\n :param tuple model_args: Model arguments if `potential_fn_gen` is specified.\n :param dict model_kwargs: Model keyword arguments if `potential_fn_gen` is specified.\n :param jax.random.PRNGKey rng_key: random key to be used as the source of\n randomness.\n\n \"\"\"\n step_size = lax.convert_element_type(step_size, jnp.result_type(float))\n trajectory_length = lax.convert_element_type(\n trajectory_length, jnp.result_type(float)\n )\n nonlocal wa_update, max_treedepth, vv_update, wa_steps, forward_mode_ad\n forward_mode_ad = forward_mode_differentiation\n wa_steps = num_warmup\n max_treedepth = max_tree_depth\n if isinstance(init_params, ParamInfo):\n z, pe, z_grad = init_params\n else:\n z, pe, z_grad = init_params, None, None\n pe_fn = potential_fn\n if potential_fn_gen:\n if pe_fn is not None:\n raise ValueError(\n \"Only one of `potential_fn` or `potential_fn_gen` must be provided.\"\n )\n else:\n kwargs = {} if model_kwargs is None else model_kwargs\n pe_fn = potential_fn_gen(*model_args, **kwargs)\n\n find_reasonable_ss = None\n if find_heuristic_step_size:\n find_reasonable_ss = partial(\n find_reasonable_step_size, pe_fn, kinetic_fn, momentum_generator\n )\n\n wa_init, wa_update = warmup_adapter(\n num_warmup,\n adapt_step_size=adapt_step_size,\n adapt_mass_matrix=adapt_mass_matrix,\n dense_mass=dense_mass,\n target_accept_prob=target_accept_prob,\n find_reasonable_step_size=find_reasonable_ss,\n )\n\n rng_key_hmc, rng_key_wa, rng_key_momentum = random.split(rng_key, 3)\n z_info = IntegratorState(z=z, potential_energy=pe, z_grad=z_grad)\n wa_state = wa_init(\n z_info, rng_key_wa, step_size, inverse_mass_matrix=inverse_mass_matrix\n )\n r = momentum_generator(z, wa_state.mass_matrix_sqrt, rng_key_momentum)\n vv_init, vv_update = velocity_verlet(pe_fn, kinetic_fn, forward_mode_ad)\n vv_state = vv_init(z, r, potential_energy=pe, z_grad=z_grad)\n energy = vv_state.potential_energy + kinetic_fn(\n wa_state.inverse_mass_matrix, vv_state.r\n )\n zero_int = jnp.array(0, dtype=jnp.result_type(int))\n hmc_state = HMCState(\n zero_int,\n vv_state.z,\n vv_state.z_grad,\n vv_state.potential_energy,\n energy,\n None,\n trajectory_length,\n zero_int,\n jnp.zeros(()),\n jnp.zeros(()),\n jnp.array(False),\n wa_state,\n rng_key_hmc,\n )\n return device_put(hmc_state)\n\n def _hmc_next(\n step_size,\n inverse_mass_matrix,\n vv_state,\n model_args,\n model_kwargs,\n rng_key,\n trajectory_length,\n ):\n if potential_fn_gen:\n nonlocal vv_update, forward_mode_ad\n pe_fn = potential_fn_gen(*model_args, **model_kwargs)\n _, vv_update = velocity_verlet(pe_fn, kinetic_fn, forward_mode_ad)\n\n # no need to spend too many steps if the state z has 0 size (i.e. z is empty)\n if len(inverse_mass_matrix) == 0:\n num_steps = 1\n else:\n num_steps = _get_num_steps(step_size, trajectory_length)\n # makes sure trajectory length is constant, rather than step_size * num_steps\n step_size = trajectory_length / num_steps\n vv_state_new = fori_loop(\n 0,\n num_steps,\n lambda i, val: vv_update(step_size, inverse_mass_matrix, val),\n vv_state,\n )\n energy_old = vv_state.potential_energy + kinetic_fn(\n inverse_mass_matrix, vv_state.r\n )\n energy_new = vv_state_new.potential_energy + kinetic_fn(\n inverse_mass_matrix, vv_state_new.r\n )\n delta_energy = energy_new - energy_old\n delta_energy = jnp.where(jnp.isnan(delta_energy), jnp.inf, delta_energy)\n accept_prob = jnp.clip(jnp.exp(-delta_energy), a_max=1.0)\n diverging = delta_energy > max_delta_energy\n transition = random.bernoulli(rng_key, accept_prob)\n vv_state, energy = cond(\n transition,\n (vv_state_new, energy_new),\n identity,\n (vv_state, energy_old),\n identity,\n )\n return vv_state, energy, num_steps, accept_prob, diverging\n\n def _nuts_next(\n step_size,\n inverse_mass_matrix,\n vv_state,\n model_args,\n model_kwargs,\n rng_key,\n trajectory_length,\n ):\n if potential_fn_gen:\n nonlocal vv_update, forward_mode_ad\n pe_fn = potential_fn_gen(*model_args, **model_kwargs)\n _, vv_update = velocity_verlet(pe_fn, kinetic_fn, forward_mode_ad)\n\n binary_tree = build_tree(\n vv_update,\n kinetic_fn,\n vv_state,\n inverse_mass_matrix,\n step_size,\n rng_key,\n max_delta_energy=max_delta_energy,\n max_tree_depth=max_treedepth,\n )\n accept_prob = binary_tree.sum_accept_probs / binary_tree.num_proposals\n num_steps = binary_tree.num_proposals\n vv_state = IntegratorState(\n z=binary_tree.z_proposal,\n r=vv_state.r,\n potential_energy=binary_tree.z_proposal_pe,\n z_grad=binary_tree.z_proposal_grad,\n )\n return (\n vv_state,\n binary_tree.z_proposal_energy,\n num_steps,\n accept_prob,\n binary_tree.diverging,\n )\n\n _next = _nuts_next if algo == \"NUTS\" else _hmc_next\n\n def sample_kernel(hmc_state, model_args=(), model_kwargs=None):\n \"\"\"\n Given an existing :data:`~numpyro.infer.mcmc.HMCState`, run HMC with fixed (possibly adapted)\n step size and return a new :data:`~numpyro.infer.mcmc.HMCState`.\n\n :param hmc_state: Current sample (and associated state).\n :param tuple model_args: Model arguments if `potential_fn_gen` is specified.\n :param dict model_kwargs: Model keyword arguments if `potential_fn_gen` is specified.\n :return: new proposed :data:`~numpyro.infer.mcmc.HMCState` from simulating\n Hamiltonian dynamics given existing state.\n\n \"\"\"\n model_kwargs = {} if model_kwargs is None else model_kwargs\n rng_key, rng_key_momentum, rng_key_transition = random.split(\n hmc_state.rng_key, 3\n )\n r = (\n momentum_generator(\n hmc_state.z, hmc_state.adapt_state.mass_matrix_sqrt, rng_key_momentum\n )\n if hmc_state.r is None\n else hmc_state.r\n )\n vv_state = IntegratorState(\n hmc_state.z, r, hmc_state.potential_energy, hmc_state.z_grad\n )\n vv_state, energy, num_steps, accept_prob, diverging = _next(\n hmc_state.adapt_state.step_size,\n hmc_state.adapt_state.inverse_mass_matrix,\n vv_state,\n model_args,\n model_kwargs,\n rng_key_transition,\n hmc_state.trajectory_length,\n )\n # not update adapt_state after warmup phase\n adapt_state = cond(\n hmc_state.i < wa_steps,\n (hmc_state.i, accept_prob, vv_state, hmc_state.adapt_state),\n lambda args: wa_update(*args),\n hmc_state.adapt_state,\n identity,\n )\n\n itr = hmc_state.i + 1\n n = jnp.where(hmc_state.i < wa_steps, itr, itr - wa_steps)\n mean_accept_prob = (\n hmc_state.mean_accept_prob + (accept_prob - hmc_state.mean_accept_prob) / n\n )\n\n r = vv_state.r if hmc_state.r is not None else None\n return HMCState(\n itr,\n vv_state.z,\n vv_state.z_grad,\n vv_state.potential_energy,\n energy,\n r,\n hmc_state.trajectory_length,\n num_steps,\n accept_prob,\n mean_accept_prob,\n diverging,\n adapt_state,\n rng_key,\n )\n\n # Make `init_kernel` and `sample_kernel` visible from the global scope once\n # `hmc` is called for sphinx doc generation.\n if \"SPHINX_BUILD\" in os.environ:\n hmc.init_kernel = init_kernel\n hmc.sample_kernel = sample_kernel\n\n return init_kernel, sample_kernel\n\n\nclass HMC(MCMCKernel):\n \"\"\"\n Hamiltonian Monte Carlo inference, using fixed trajectory length, with\n provision for step size and mass matrix adaptation.\n\n **References:**\n\n 1. *MCMC Using Hamiltonian Dynamics*,\n Radford M. Neal\n\n :param model: Python callable containing Pyro :mod:`~numpyro.primitives`.\n If model is provided, `potential_fn` will be inferred using the model.\n :param potential_fn: Python callable that computes the potential energy\n given input parameters. The input parameters to `potential_fn` can be\n any python collection type, provided that `init_params` argument to\n :meth:`init` has the same type.\n :param kinetic_fn: Python callable that returns the kinetic energy given\n inverse mass matrix and momentum. If not provided, the default is\n euclidean kinetic energy.\n :param float step_size: Determines the size of a single step taken by the\n verlet integrator while computing the trajectory using Hamiltonian\n dynamics. If not specified, it will be set to 1.\n :param inverse_mass_matrix: Initial value for inverse mass matrix.\n This may be adapted during warmup if adapt_mass_matrix = True.\n If no value is specified, then it is initialized to the identity matrix.\n For a potential_fn with general JAX pytree parameters, the order of entries\n of the mass matrix is the order of the flattened version of pytree parameters\n obtained with `jax.tree_flatten`, which is a bit ambiguous (see more at\n https://jax.readthedocs.io/en/latest/pytrees.html). If `model` is not None,\n here we can specify a structured block mass matrix as a dictionary, where\n keys are tuple of site names and values are the corresponding block of the\n mass matrix.\n For more information about structured mass matrix, see `dense_mass` argument.\n :type inverse_mass_matrix: numpy.ndarray or dict\n :param bool adapt_step_size: A flag to decide if we want to adapt step_size\n during warm-up phase using Dual Averaging scheme.\n :param bool adapt_mass_matrix: A flag to decide if we want to adapt mass\n matrix during warm-up phase using Welford scheme.\n :param dense_mass: This flag controls whether mass matrix is dense (i.e. full-rank) or\n diagonal (defaults to ``dense_mass=False``). To specify a structured mass matrix,\n users can provide a list of tuples of site names. Each tuple represents\n a block in the joint mass matrix. For example, assuming that the model\n has latent variables \"x\", \"y\", \"z\" (where each variable can be multi-dimensional),\n possible specifications and corresponding mass matrix structures are as follows:\n\n + dense_mass=[(\"x\", \"y\")]: use a dense mass matrix for the joint\n (x, y) and a diagonal mass matrix for z\n + dense_mass=[] (equivalent to dense_mass=False): use a diagonal mass\n matrix for the joint (x, y, z)\n + dense_mass=[(\"x\", \"y\", \"z\")] (equivalent to full_mass=True):\n use a dense mass matrix for the joint (x, y, z)\n + dense_mass=[(\"x\",), (\"y\",), (\"z\")]: use dense mass matrices for\n each of x, y, and z (i.e. block-diagonal with 3 blocks)\n\n :type dense_mass: bool or list\n :param float target_accept_prob: Target acceptance probability for step size\n adaptation using Dual Averaging. Increasing this value will lead to a smaller\n step size, hence the sampling will be slower but more robust. Default to 0.8.\n :param float trajectory_length: Length of a MCMC trajectory for HMC. Default\n value is :math:`2\\\\pi`.\n :param callable init_strategy: a per-site initialization function.\n See :ref:`init_strategy` section for available functions.\n :param bool find_heuristic_step_size: whether to a heuristic function to adjust the\n step size at the beginning of each adaptation window. Defaults to False.\n :param bool forward_mode_differentiation: whether to use forward-mode differentiation\n or reverse-mode differentiation. By default, we use reverse mode but the forward\n mode can be useful in some cases to improve the performance. In addition, some\n control flow utility on JAX such as `jax.lax.while_loop` or `jax.lax.fori_loop`\n only supports forward-mode differentiation. See\n `JAX's The Autodiff Cookbook <https://jax.readthedocs.io/en/latest/notebooks/autodiff_cookbook.html>`_\n for more information.\n \"\"\"\n\n def __init__(\n self,\n model=None,\n potential_fn=None,\n kinetic_fn=None,\n step_size=1.0,\n inverse_mass_matrix=None,\n adapt_step_size=True,\n adapt_mass_matrix=True,\n dense_mass=False,\n target_accept_prob=0.8,\n trajectory_length=2 * math.pi,\n init_strategy=init_to_uniform,\n find_heuristic_step_size=False,\n forward_mode_differentiation=False,\n ):\n if not (model is None) ^ (potential_fn is None):\n raise ValueError(\"Only one of `model` or `potential_fn` must be specified.\")\n self._model = model\n self._potential_fn = potential_fn\n self._kinetic_fn = (\n kinetic_fn if kinetic_fn is not None else euclidean_kinetic_energy\n )\n self._step_size = float(step_size) if isinstance(step_size, int) else step_size\n self._inverse_mass_matrix = inverse_mass_matrix\n self._adapt_step_size = adapt_step_size\n self._adapt_mass_matrix = adapt_mass_matrix\n self._dense_mass = dense_mass\n self._target_accept_prob = target_accept_prob\n self._trajectory_length = (\n float(trajectory_length)\n if isinstance(trajectory_length, int)\n else trajectory_length\n )\n self._algo = \"HMC\"\n self._max_tree_depth = 10\n self._init_strategy = init_strategy\n self._find_heuristic_step_size = find_heuristic_step_size\n self._forward_mode_differentiation = forward_mode_differentiation\n # Set on first call to init\n self._init_fn = None\n self._potential_fn_gen = None\n self._postprocess_fn = None\n self._sample_fn = None\n\n def _init_state(self, rng_key, model_args, model_kwargs, init_params):\n if self._model is not None:\n init_params, potential_fn, postprocess_fn, model_trace = initialize_model(\n rng_key,\n self._model,\n dynamic_args=True,\n init_strategy=self._init_strategy,\n model_args=model_args,\n model_kwargs=model_kwargs,\n forward_mode_differentiation=self._forward_mode_differentiation,\n )\n if self._init_fn is None:\n self._init_fn, self._sample_fn = hmc(\n potential_fn_gen=potential_fn,\n kinetic_fn=self._kinetic_fn,\n algo=self._algo,\n )\n self._potential_fn_gen = potential_fn\n self._postprocess_fn = postprocess_fn\n elif self._init_fn is None:\n self._init_fn, self._sample_fn = hmc(\n potential_fn=self._potential_fn,\n kinetic_fn=self._kinetic_fn,\n algo=self._algo,\n )\n\n return init_params\n\n @property\n def model(self):\n return self._model\n\n @property\n def sample_field(self):\n return \"z\"\n\n @property\n def default_fields(self):\n return (\"z\", \"diverging\")\n\n def get_diagnostics_str(self, state):\n return \"{} steps of size {:.2e}. acc. prob={:.2f}\".format(\n state.num_steps, state.adapt_state.step_size, state.mean_accept_prob\n )\n\n def init(\n self, rng_key, num_warmup, init_params=None, model_args=(), model_kwargs={}\n ):\n # non-vectorized\n if rng_key.ndim == 1:\n rng_key, rng_key_init_model = random.split(rng_key)\n # vectorized\n else:\n rng_key, rng_key_init_model = jnp.swapaxes(\n vmap(random.split)(rng_key), 0, 1\n )\n init_params = self._init_state(\n rng_key_init_model, model_args, model_kwargs, init_params\n )\n if self._potential_fn and init_params is None:\n raise ValueError(\n \"Valid value of `init_params` must be provided with\" \" `potential_fn`.\"\n )\n\n # change dense_mass to a structural form\n dense_mass = self._dense_mass\n inverse_mass_matrix = self._inverse_mass_matrix\n if self._model is not None:\n z = init_params[0] if isinstance(init_params, ParamInfo) else init_params\n if isinstance(dense_mass, bool):\n # XXX: by default, the order variables are sorted by their names,\n # this is to be compatible with older numpyro versions\n # and to match autoguide scale parameter and jax flatten utils\n dense_mass = [tuple(sorted(z))] if dense_mass else []\n assert isinstance(dense_mass, list)\n\n hmc_init_fn = lambda init_params, rng_key: self._init_fn( # noqa: E731\n init_params,\n num_warmup=num_warmup,\n step_size=self._step_size,\n inverse_mass_matrix=inverse_mass_matrix,\n adapt_step_size=self._adapt_step_size,\n adapt_mass_matrix=self._adapt_mass_matrix,\n dense_mass=dense_mass,\n target_accept_prob=self._target_accept_prob,\n trajectory_length=self._trajectory_length,\n max_tree_depth=self._max_tree_depth,\n find_heuristic_step_size=self._find_heuristic_step_size,\n forward_mode_differentiation=self._forward_mode_differentiation,\n model_args=model_args,\n model_kwargs=model_kwargs,\n rng_key=rng_key,\n )\n if rng_key.ndim == 1:\n init_state = hmc_init_fn(init_params, rng_key)\n else:\n # XXX it is safe to run hmc_init_fn under vmap despite that hmc_init_fn changes some\n # nonlocal variables: momentum_generator, wa_update, trajectory_len, max_treedepth,\n # wa_steps because those variables do not depend on traced args: init_params, rng_key.\n init_state = vmap(hmc_init_fn)(init_params, rng_key)\n sample_fn = vmap(self._sample_fn, in_axes=(0, None, None))\n self._sample_fn = sample_fn\n return init_state\n\n def postprocess_fn(self, args, kwargs):\n if self._postprocess_fn is None:\n return identity\n return self._postprocess_fn(*args, **kwargs)\n\n def sample(self, state, model_args, model_kwargs):\n \"\"\"\n Run HMC from the given :data:`~numpyro.infer.hmc.HMCState` and return the resulting\n :data:`~numpyro.infer.hmc.HMCState`.\n\n :param HMCState state: Represents the current state.\n :param model_args: Arguments provided to the model.\n :param model_kwargs: Keyword arguments provided to the model.\n :return: Next `state` after running HMC.\n \"\"\"\n return self._sample_fn(state, model_args, model_kwargs)\n\n def __getstate__(self):\n state = self.__dict__.copy()\n state[\"_sample_fn\"] = None\n state[\"_init_fn\"] = None\n state[\"_postprocess_fn\"] = None\n state[\"_potential_fn_gen\"] = None\n return state\n\n\nclass NUTS(HMC):\n \"\"\"\n Hamiltonian Monte Carlo inference, using the No U-Turn Sampler (NUTS)\n with adaptive path length and mass matrix adaptation.\n\n **References:**\n\n 1. *MCMC Using Hamiltonian Dynamics*,\n Radford M. Neal\n 2. *The No-U-turn sampler: adaptively setting path lengths in Hamiltonian Monte Carlo*,\n Matthew D. Hoffman, and Andrew Gelman.\n 3. *A Conceptual Introduction to Hamiltonian Monte Carlo`*,\n Michael Betancourt\n\n :param model: Python callable containing Pyro :mod:`~numpyro.primitives`.\n If model is provided, `potential_fn` will be inferred using the model.\n :param potential_fn: Python callable that computes the potential energy\n given input parameters. The input parameters to `potential_fn` can be\n any python collection type, provided that `init_params` argument to\n `init_kernel` has the same type.\n :param kinetic_fn: Python callable that returns the kinetic energy given\n inverse mass matrix and momentum. If not provided, the default is\n euclidean kinetic energy.\n :param float step_size: Determines the size of a single step taken by the\n verlet integrator while computing the trajectory using Hamiltonian\n dynamics. If not specified, it will be set to 1.\n :param inverse_mass_matrix: Initial value for inverse mass matrix.\n This may be adapted during warmup if adapt_mass_matrix = True.\n If no value is specified, then it is initialized to the identity matrix.\n For a potential_fn with general JAX pytree parameters, the order of entries\n of the mass matrix is the order of the flattened version of pytree parameters\n obtained with `jax.tree_flatten`, which is a bit ambiguous (see more at\n https://jax.readthedocs.io/en/latest/pytrees.html). If `model` is not None,\n here we can specify a structured block mass matrix as a dictionary, where\n keys are tuple of site names and values are the corresponding block of the\n mass matrix.\n For more information about structured mass matrix, see `dense_mass` argument.\n :type inverse_mass_matrix: numpy.ndarray or dict\n :param bool adapt_step_size: A flag to decide if we want to adapt step_size\n during warm-up phase using Dual Averaging scheme.\n :param bool adapt_mass_matrix: A flag to decide if we want to adapt mass\n matrix during warm-up phase using Welford scheme.\n :param dense_mass: This flag controls whether mass matrix is dense (i.e. full-rank) or\n diagonal (defaults to ``dense_mass=False``). To specify a structured mass matrix,\n users can provide a list of tuples of site names. Each tuple represents\n a block in the joint mass matrix. For example, assuming that the model\n has latent variables \"x\", \"y\", \"z\" (where each variable can be multi-dimensional),\n possible specifications and corresponding mass matrix structures are as follows:\n\n + dense_mass=[(\"x\", \"y\")]: use a dense mass matrix for the joint\n (x, y) and a diagonal mass matrix for z\n + dense_mass=[] (equivalent to dense_mass=False): use a diagonal mass\n matrix for the joint (x, y, z)\n + dense_mass=[(\"x\", \"y\", \"z\")] (equivalent to full_mass=True):\n use a dense mass matrix for the joint (x, y, z)\n + dense_mass=[(\"x\",), (\"y\",), (\"z\")]: use dense mass matrices for\n each of x, y, and z (i.e. block-diagonal with 3 blocks)\n\n :type dense_mass: bool or list\n :param float target_accept_prob: Target acceptance probability for step size\n adaptation using Dual Averaging. Increasing this value will lead to a smaller\n step size, hence the sampling will be slower but more robust. Default to 0.8.\n :param float trajectory_length: Length of a MCMC trajectory for HMC. This arg has\n no effect in NUTS sampler.\n :param int max_tree_depth: Max depth of the binary tree created during the doubling\n scheme of NUTS sampler. Defaults to 10.\n :param callable init_strategy: a per-site initialization function.\n See :ref:`init_strategy` section for available functions.\n :param bool find_heuristic_step_size: whether to a heuristic function to adjust the\n step size at the beginning of each adaptation window. Defaults to False.\n :param bool forward_mode_differentiation: whether to use forward-mode differentiation\n or reverse-mode differentiation. By default, we use reverse mode but the forward\n mode can be useful in some cases to improve the performance. In addition, some\n control flow utility on JAX such as `jax.lax.while_loop` or `jax.lax.fori_loop`\n only supports forward-mode differentiation. See\n `JAX's The Autodiff Cookbook <https://jax.readthedocs.io/en/latest/notebooks/autodiff_cookbook.html>`_\n for more information.\n \"\"\"\n\n def __init__(\n self,\n model=None,\n potential_fn=None,\n kinetic_fn=None,\n step_size=1.0,\n inverse_mass_matrix=None,\n adapt_step_size=True,\n adapt_mass_matrix=True,\n dense_mass=False,\n target_accept_prob=0.8,\n trajectory_length=None,\n max_tree_depth=10,\n init_strategy=init_to_uniform,\n find_heuristic_step_size=False,\n forward_mode_differentiation=False,\n ):\n super(NUTS, self).__init__(\n potential_fn=potential_fn,\n model=model,\n kinetic_fn=kinetic_fn,\n step_size=step_size,\n inverse_mass_matrix=inverse_mass_matrix,\n adapt_step_size=adapt_step_size,\n adapt_mass_matrix=adapt_mass_matrix,\n dense_mass=dense_mass,\n target_accept_prob=target_accept_prob,\n trajectory_length=trajectory_length,\n init_strategy=init_strategy,\n find_heuristic_step_size=find_heuristic_step_size,\n forward_mode_differentiation=forward_mode_differentiation,\n )\n self._max_tree_depth = max_tree_depth\n self._algo = \"NUTS\"\n", "path": "numpyro/infer/hmc.py" } ]
[ { "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_update\nfrom jax.scipy.linalg import solve_triangular\nfrom jax.scipy.special import expit\nfrom jax.tree_util import tree_flatten, tree_map, tree_multimap\n\nimport numpyro.distributions as dist\nfrom numpyro.util import cond, identity, while_loop\n\nAdaptWindow = namedtuple(\"AdaptWindow\", [\"start\", \"end\"])\n# XXX: we need to store rng_key here in case we use find_reasonable_step_size functionality\nHMCAdaptState = namedtuple(\n \"HMCAdaptState\",\n [\n \"step_size\",\n \"inverse_mass_matrix\",\n \"mass_matrix_sqrt\",\n \"mass_matrix_sqrt_inv\",\n \"ss_state\",\n \"mm_state\",\n \"window_idx\",\n \"rng_key\",\n ],\n)\nIntegratorState = namedtuple(\n \"IntegratorState\", [\"z\", \"r\", \"potential_energy\", \"z_grad\"]\n)\nIntegratorState.__new__.__defaults__ = (None,) * len(IntegratorState._fields)\n\nTreeInfo = namedtuple(\n \"TreeInfo\",\n [\n \"z_left\",\n \"r_left\",\n \"z_left_grad\",\n \"z_right\",\n \"r_right\",\n \"z_right_grad\",\n \"z_proposal\",\n \"z_proposal_pe\",\n \"z_proposal_grad\",\n \"z_proposal_energy\",\n \"depth\",\n \"weight\",\n \"r_sum\",\n \"turning\",\n \"diverging\",\n \"sum_accept_probs\",\n \"num_proposals\",\n ],\n)\n\n\ndef dual_averaging(t0=10, kappa=0.75, gamma=0.05):\n \"\"\"\n Dual Averaging is a scheme to solve convex optimization problems. It\n belongs to a class of subgradient methods which uses subgradients (which\n lie in a dual space) to update states (in primal space) of a model. Under\n some conditions, the averages of generated parameters during the scheme are\n guaranteed to converge to an optimal value. However, a counter-intuitive\n aspect of traditional subgradient methods is \"new subgradients enter the\n model with decreasing weights\" (see reference [1]). Dual Averaging scheme\n resolves that issue by updating parameters using weights equally for\n subgradients, hence we have the name \"dual averaging\".\n\n This class implements a dual averaging scheme which is adapted for Markov\n chain Monte Carlo (MCMC) algorithms. To be more precise, we will replace\n subgradients by some statistics calculated at the end of MCMC trajectories.\n Following [2], we introduce some free parameters such as ``t0`` and\n ``kappa``, which is helpful and still guarantees the convergence of the\n scheme.\n\n **References:**\n\n 1. *Primal-dual subgradient methods for convex problems*,\n Yurii Nesterov\n 2. *The No-U-turn sampler: adaptively setting path lengths in Hamiltonian Monte Carlo*,\n Matthew D. Hoffman, Andrew Gelman\n\n :param int t0: A free parameter introduced in reference [2] that stabilizes\n the initial steps of the scheme. Defaults to 10.\n :param float kappa: A free parameter introduced in reference [2] that\n controls the weights of steps of the scheme. For a small ``kappa``, the\n scheme will quickly forget states from early steps. This should be a\n number in :math:`(0.5, 1]`. Defaults to 0.75.\n :param float gamma: A free parameter introduced in reference [1] which\n controls the speed of the convergence of the scheme. Defaults to 0.05.\n :return: a (`init_fn`, `update_fn`) pair.\n \"\"\"\n\n def init_fn(prox_center=0.0):\n \"\"\"\n :param float prox_center: A parameter introduced in reference [1] which\n pulls the primal sequence towards it. Defaults to 0.\n :return: initial state for the scheme.\n \"\"\"\n x_t = jnp.zeros(())\n x_avg = jnp.zeros(()) # average of primal sequence\n g_avg = jnp.zeros(()) # average of dual sequence\n t = jnp.array(0, dtype=jnp.result_type(int))\n return x_t, x_avg, g_avg, t, prox_center\n\n def update_fn(g, state):\n \"\"\"\n :param float g: The current subgradient or statistics calculated during\n an MCMC trajectory.\n :param state: Current state of the scheme.\n :return: new state for the scheme.\n \"\"\"\n x_t, x_avg, g_avg, t, prox_center = state\n t = t + 1\n # g_avg = (g_1 + ... + g_t) / t\n g_avg = (1 - 1 / (t + t0)) * g_avg + g / (t + t0)\n # According to formula (3.4) of [1], we have\n # x_t = argmin{ g_avg . x + loc_t . |x - x0|^2 },\n # hence x_t = x0 - g_avg / (2 * loc_t),\n # where loc_t := beta_t / t, beta_t := (gamma/2) * sqrt(t).\n x_t = prox_center - (t ** 0.5) / gamma * g_avg\n # weight for the new x_t\n weight_t = t ** (-kappa)\n x_avg = (1 - weight_t) * x_avg + weight_t * x_t\n return x_t, x_avg, g_avg, t, prox_center\n\n return init_fn, update_fn\n\n\ndef welford_covariance(diagonal=True):\n \"\"\"\n Implements Welford's online method for estimating (co)variance. Useful for\n adapting diagonal and dense mass structures for HMC. It is required that\n each sample is a 1-dimensional array.\n\n **References:**\n\n 1. *The Art of Computer Programming*,\n Donald E. Knuth\n\n :param bool diagonal: If True, we estimate the variance of samples.\n Otherwise, we estimate the covariance of the samples. Defaults to True.\n :return: a (`init_fn`, `update_fn`, `final_fn`) triple.\n \"\"\"\n\n def init_fn(size):\n \"\"\"\n :param int size: size of each sample. For a structured mass matrix,\n this is a dict mapping from tuples of site names to the shape\n of the mass matrix.\n :return: initial state for the scheme.\n \"\"\"\n if isinstance(size, dict):\n state = {}\n for site_names, size_block in size.items():\n state[site_names] = init_fn(size_block)\n return state\n\n if isinstance(size, int):\n shape = (size,) if diagonal else (size, size)\n else:\n shape = size\n\n mean = jnp.zeros(shape[-1])\n m2 = jnp.zeros(shape)\n n = 0\n return mean, m2, n\n\n def update_fn(sample, state):\n \"\"\"\n :param sample: A new sample.\n :param state: Current state of the scheme.\n :return: new state for the scheme.\n \"\"\"\n if isinstance(state, dict):\n assert isinstance(sample, dict)\n new_state = {}\n for site_names, state_block in state.items():\n sample_block = tuple(sample[k] for k in site_names)\n new_state[site_names] = update_fn(sample_block, state_block)\n return new_state\n\n sample, _ = ravel_pytree(sample)\n mean, m2, n = state\n n = n + 1\n delta_pre = sample - mean\n mean = mean + delta_pre / n\n delta_post = sample - mean\n if jnp.ndim(m2) == 1:\n m2 = m2 + delta_pre * delta_post\n else:\n m2 = m2 + jnp.outer(delta_post, delta_pre)\n return mean, m2, n\n\n def final_fn(state, regularize=False):\n \"\"\"\n :param state: Current state of the scheme.\n :param bool regularize: Whether to adjust diagonal for numerical stability.\n :return: a triple of estimated covariance, the square root of precision, and\n the inverse of that square root.\n \"\"\"\n if isinstance(state, dict):\n cov, cov_inv_sqrt, tril_inv = {}, {}, {}\n for site_names, state_block in state.items():\n cov_block, cov_inv_sqrt_block, tril_inv_block = final_fn(\n state_block, regularize=regularize\n )\n cov[site_names] = cov_block\n cov_inv_sqrt[site_names] = cov_inv_sqrt_block\n tril_inv[site_names] = tril_inv_block\n return cov, cov_inv_sqrt, tril_inv\n\n mean, m2, n = state\n # XXX it is not necessary to check for the case n=1\n cov = m2 / (n - 1)\n if regularize:\n # Regularization from Stan\n scaled_cov = (n / (n + 5)) * cov\n shrinkage = 1e-3 * (5 / (n + 5))\n if jnp.ndim(scaled_cov) == 1:\n cov = scaled_cov + shrinkage\n else:\n cov = scaled_cov + shrinkage * jnp.identity(mean.shape[0])\n if jnp.ndim(cov) == 2:\n # copy the implementation of distributions.util.cholesky_of_inverse here\n tril_inv = jnp.swapaxes(\n jnp.linalg.cholesky(cov[..., ::-1, ::-1])[..., ::-1, ::-1], -2, -1\n )\n identity = jnp.identity(cov.shape[-1])\n cov_inv_sqrt = solve_triangular(tril_inv, identity, lower=True)\n else:\n tril_inv = jnp.sqrt(cov)\n cov_inv_sqrt = jnp.reciprocal(tril_inv)\n return cov, cov_inv_sqrt, tril_inv\n\n return init_fn, update_fn, final_fn\n\n\ndef _value_and_grad(f, x, forward_mode_differentiation=False):\n if forward_mode_differentiation:\n return f(x), jacfwd(f)(x)\n else:\n return value_and_grad(f)(x)\n\n\ndef _kinetic_grad(kinetic_fn, inverse_mass_matrix, r):\n if hasattr(kinetic_fn, \"_kinetic_grad\"):\n return kinetic_fn._kinetic_grad(inverse_mass_matrix, r)\n else:\n return grad(kinetic_fn, argnums=1)(inverse_mass_matrix, r)\n\n\ndef velocity_verlet(potential_fn, kinetic_fn, forward_mode_differentiation=False):\n r\"\"\"\n Second order symplectic integrator that uses the velocity verlet algorithm\n for position `z` and momentum `r`.\n\n :param potential_fn: Python callable that computes the potential energy\n given input parameters. The input parameters to `potential_fn` can be\n any python collection type.\n :param kinetic_fn: Python callable that returns the kinetic energy given\n inverse mass matrix and momentum.\n :return: a pair of (`init_fn`, `update_fn`).\n \"\"\"\n\n def init_fn(z, r, potential_energy=None, z_grad=None):\n \"\"\"\n :param z: Position of the particle.\n :param r: Momentum of the particle.\n :param potential_energy: Potential energy at `z`.\n :param z_grad: gradient of potential energy at `z`.\n :return: initial state for the integrator.\n \"\"\"\n if potential_energy is None or z_grad is None:\n potential_energy, z_grad = _value_and_grad(\n potential_fn, z, forward_mode_differentiation\n )\n return IntegratorState(z, r, potential_energy, z_grad)\n\n def update_fn(step_size, inverse_mass_matrix, state):\n \"\"\"\n :param float step_size: Size of a single step.\n :param inverse_mass_matrix: Inverse of mass matrix, which is used to\n calculate kinetic energy.\n :param state: Current state of the integrator.\n :return: new state for the integrator.\n \"\"\"\n z, r, _, z_grad = state\n r = tree_multimap(\n lambda r, z_grad: r - 0.5 * step_size * z_grad, r, z_grad\n ) # r(n+1/2)\n r_grad = _kinetic_grad(kinetic_fn, inverse_mass_matrix, r)\n z = tree_multimap(lambda z, r_grad: z + step_size * r_grad, z, r_grad) # z(n+1)\n potential_energy, z_grad = _value_and_grad(\n potential_fn, z, forward_mode_differentiation\n )\n r = tree_multimap(\n lambda r, z_grad: r - 0.5 * step_size * z_grad, r, z_grad\n ) # r(n+1)\n return IntegratorState(z, r, potential_energy, z_grad)\n\n return init_fn, update_fn\n\n\ndef find_reasonable_step_size(\n potential_fn,\n kinetic_fn,\n momentum_generator,\n init_step_size,\n inverse_mass_matrix,\n z_info,\n rng_key,\n):\n \"\"\"\n Finds a reasonable step size by tuning `init_step_size`. This function is used\n to avoid working with a too large or too small step size in HMC.\n\n **References:**\n\n 1. *The No-U-Turn Sampler: Adaptively Setting Path Lengths in Hamiltonian Monte Carlo*,\n Matthew D. Hoffman, Andrew Gelman\n\n :param potential_fn: A callable to compute potential energy.\n :param kinetic_fn: A callable to compute kinetic energy.\n :param momentum_generator: A generator to get a random momentum variable.\n :param float init_step_size: Initial step size to be tuned.\n :param inverse_mass_matrix: Inverse of mass matrix.\n :param IntegratorState z_info: The current integrator state.\n :param jax.random.PRNGKey rng_key: Random key to be used as the source of randomness.\n :return: a reasonable value for step size.\n :rtype: float\n \"\"\"\n # We are going to find a step_size which make accept_prob (Metropolis correction)\n # near the target_accept_prob. If accept_prob:=exp(-delta_energy) is small,\n # then we have to decrease step_size; otherwise, increase step_size.\n target_accept_prob = jnp.log(0.8)\n\n _, vv_update = velocity_verlet(potential_fn, kinetic_fn)\n z, _, potential_energy, z_grad = z_info\n if potential_energy is None or z_grad is None:\n potential_energy, z_grad = value_and_grad(potential_fn)(z)\n finfo = jnp.finfo(jnp.result_type(init_step_size))\n\n def _body_fn(state):\n step_size, _, direction, rng_key = state\n rng_key, rng_key_momentum = random.split(rng_key)\n # scale step_size: increase 2x or decrease 2x depends on direction;\n # direction=1 means keep increasing step_size, otherwise decreasing step_size.\n # Note that the direction is -1 if delta_energy is `NaN`, which may be the\n # case for a diverging trajectory (e.g. in the case of evaluating log prob\n # of a value simulated using a large step size for a constrained sample site).\n step_size = (2.0 ** direction) * step_size\n r = momentum_generator(z, inverse_mass_matrix, rng_key_momentum)\n _, r_new, potential_energy_new, _ = vv_update(\n step_size, inverse_mass_matrix, (z, r, potential_energy, z_grad)\n )\n energy_current = kinetic_fn(inverse_mass_matrix, r) + potential_energy\n energy_new = kinetic_fn(inverse_mass_matrix, r_new) + potential_energy_new\n delta_energy = energy_new - energy_current\n direction_new = jnp.where(target_accept_prob < -delta_energy, 1, -1)\n return step_size, direction, direction_new, rng_key\n\n def _cond_fn(state):\n step_size, last_direction, direction, _ = state\n # condition to run only if step_size is not too small or we are not decreasing step_size\n not_small_step_size_cond = (step_size > finfo.tiny) | (direction >= 0)\n # condition to run only if step_size is not too large or we are not increasing step_size\n not_large_step_size_cond = (step_size < finfo.max) | (direction <= 0)\n not_extreme_cond = not_small_step_size_cond & not_large_step_size_cond\n return not_extreme_cond & (\n (last_direction == 0) | (direction == last_direction)\n )\n\n step_size, _, _, _ = while_loop(_cond_fn, _body_fn, (init_step_size, 0, 0, rng_key))\n return step_size\n\n\ndef build_adaptation_schedule(num_steps):\n \"\"\"\n Builds a window adaptation schedule to be used during warmup phase of HMC.\n\n :param int num_steps: Number of warmup steps.\n :return: a list of contiguous windows, each has attributes `start` and `end`,\n where `start` is the starting index and `end` is the ending index of the window.\n\n **References:**\n\n 1. *Stan Reference Manual version 2.18*,\n Stan Development Team\n \"\"\"\n adaptation_schedule = []\n # from Stan, for small num_steps\n if num_steps < 20:\n adaptation_schedule.append(AdaptWindow(0, num_steps - 1))\n return adaptation_schedule\n\n # We separate num_steps into windows:\n # start_buffer + window 1 + window 2 + window 3 + ... + end_buffer\n # where the length of each window will be doubled for the next window.\n # We won't adapt mass matrix during start and end buffers; and mass\n # matrix will be updated at the end of each window. This is helpful\n # for dealing with the intense computation of sampling momentum from the\n # inverse of mass matrix.\n start_buffer_size = 75 # from Stan\n end_buffer_size = 50 # from Stan\n init_window_size = 25 # from Stan\n if (start_buffer_size + end_buffer_size + init_window_size) > num_steps:\n start_buffer_size = int(0.15 * num_steps)\n end_buffer_size = int(0.1 * num_steps)\n init_window_size = num_steps - start_buffer_size - end_buffer_size\n\n adaptation_schedule.append(AdaptWindow(start=0, end=start_buffer_size - 1))\n end_window_start = num_steps - end_buffer_size\n\n next_window_size = init_window_size\n next_window_start = start_buffer_size\n while next_window_start < end_window_start:\n cur_window_start, cur_window_size = next_window_start, next_window_size\n # Ensure that slow adaptation windows are monotonically increasing\n if 3 * cur_window_size <= end_window_start - cur_window_start:\n next_window_size = 2 * cur_window_size\n else:\n cur_window_size = end_window_start - cur_window_start\n next_window_start = cur_window_start + cur_window_size\n adaptation_schedule.append(AdaptWindow(cur_window_start, next_window_start - 1))\n adaptation_schedule.append(AdaptWindow(end_window_start, num_steps - 1))\n return adaptation_schedule\n\n\ndef _initialize_mass_matrix(z, inverse_mass_matrix, dense_mass):\n if isinstance(dense_mass, list):\n if inverse_mass_matrix is None:\n inverse_mass_matrix = {}\n # if user specifies an ndarray mass matrix, then we convert it to a dict\n elif not isinstance(inverse_mass_matrix, dict):\n inverse_mass_matrix = {tuple(sorted(z)): inverse_mass_matrix}\n mass_matrix_sqrt = {}\n mass_matrix_sqrt_inv = {}\n for site_names in dense_mass:\n inverse_mm = inverse_mass_matrix.get(site_names)\n z_block = tuple(z[k] for k in site_names)\n inverse_mm, mm_sqrt, mm_sqrt_inv = _initialize_mass_matrix(\n z_block, inverse_mm, True\n )\n inverse_mass_matrix[site_names] = inverse_mm\n mass_matrix_sqrt[site_names] = mm_sqrt\n mass_matrix_sqrt_inv[site_names] = mm_sqrt_inv\n # NB: this branch only happens when users want to use block diagonal\n # inverse_mass_matrix, for example, {(\"a\",): jnp.ones(3), (\"b\",): jnp.ones(3)}.\n for site_names, inverse_mm in inverse_mass_matrix.items():\n if site_names in dense_mass:\n continue\n z_block = tuple(z[k] for k in site_names)\n inverse_mm, mm_sqrt, mm_sqrt_inv = _initialize_mass_matrix(\n z_block, inverse_mm, False\n )\n inverse_mass_matrix[site_names] = inverse_mm\n mass_matrix_sqrt[site_names] = mm_sqrt\n mass_matrix_sqrt_inv[site_names] = mm_sqrt_inv\n remaining_sites = tuple(sorted(set(z) - set().union(*inverse_mass_matrix)))\n if len(remaining_sites) > 0:\n z_block = tuple(z[k] for k in remaining_sites)\n inverse_mm, mm_sqrt, mm_sqrt_inv = _initialize_mass_matrix(\n z_block, None, False\n )\n inverse_mass_matrix[remaining_sites] = inverse_mm\n mass_matrix_sqrt[remaining_sites] = mm_sqrt\n mass_matrix_sqrt_inv[remaining_sites] = mm_sqrt_inv\n expected_site_names = sorted(z)\n actual_site_names = sorted(\n [k for site_names in inverse_mass_matrix for k in site_names]\n )\n assert actual_site_names == expected_site_names, (\n \"There seems to be a conflict of sites names specified in the initial\"\n \" `inverse_mass_matrix` and in `dense_mass` argument.\"\n )\n return inverse_mass_matrix, mass_matrix_sqrt, mass_matrix_sqrt_inv\n\n mass_matrix_size = jnp.size(ravel_pytree(z)[0])\n if inverse_mass_matrix is None:\n if dense_mass:\n inverse_mass_matrix = jnp.identity(mass_matrix_size)\n else:\n inverse_mass_matrix = jnp.ones(mass_matrix_size)\n mass_matrix_sqrt = mass_matrix_sqrt_inv = inverse_mass_matrix\n else:\n if dense_mass:\n if jnp.ndim(inverse_mass_matrix) == 1:\n inverse_mass_matrix = jnp.diag(inverse_mass_matrix)\n mass_matrix_sqrt_inv = jnp.swapaxes(\n jnp.linalg.cholesky(inverse_mass_matrix[..., ::-1, ::-1])[\n ..., ::-1, ::-1\n ],\n -2,\n -1,\n )\n identity = jnp.identity(inverse_mass_matrix.shape[-1])\n mass_matrix_sqrt = solve_triangular(\n mass_matrix_sqrt_inv, identity, lower=True\n )\n else:\n if jnp.ndim(inverse_mass_matrix) == 2:\n inverse_mass_matrix = jnp.diag(inverse_mass_matrix)\n mass_matrix_sqrt_inv = jnp.sqrt(inverse_mass_matrix)\n mass_matrix_sqrt = jnp.reciprocal(mass_matrix_sqrt_inv)\n return inverse_mass_matrix, mass_matrix_sqrt, mass_matrix_sqrt_inv\n\n\ndef warmup_adapter(\n num_adapt_steps,\n find_reasonable_step_size=None,\n adapt_step_size=True,\n adapt_mass_matrix=True,\n dense_mass=False,\n target_accept_prob=0.8,\n):\n \"\"\"\n A scheme to adapt tunable parameters, namely step size and mass matrix, during\n the warmup phase of HMC.\n\n :param int num_adapt_steps: Number of warmup steps.\n :param find_reasonable_step_size: A callable to find a reasonable step size\n at the beginning of each adaptation window.\n :param bool adapt_step_size: A flag to decide if we want to adapt step_size\n during warm-up phase using Dual Averaging scheme (defaults to ``True``).\n :param bool adapt_mass_matrix: A flag to decide if we want to adapt mass\n matrix during warm-up phase using Welford scheme (defaults to ``True``).\n :param bool dense_mass: A flag to decide if mass matrix is dense or\n diagonal (defaults to ``False``).\n :param float target_accept_prob: Target acceptance probability for step size\n adaptation using Dual Averaging. Increasing this value will lead to a smaller\n step size, hence the sampling will be slower but more robust. Default to 0.8.\n :return: a pair of (`init_fn`, `update_fn`).\n \"\"\"\n if find_reasonable_step_size is None:\n find_reasonable_step_size = identity\n ss_init, ss_update = dual_averaging()\n mm_init, mm_update, mm_final = welford_covariance(diagonal=not dense_mass)\n adaptation_schedule = jnp.array(build_adaptation_schedule(num_adapt_steps))\n num_windows = len(adaptation_schedule)\n\n def init_fn(\n z_info, rng_key, step_size=1.0, inverse_mass_matrix=None, mass_matrix_size=None\n ):\n \"\"\"\n :param IntegratorState z_info: The initial integrator state.\n :param jax.random.PRNGKey rng_key: Random key to be used as the source of randomness.\n :param float step_size: Initial step size.\n :param inverse_mass_matrix: Inverse of the initial mass matrix. If ``None``,\n inverse of mass matrix will be an identity matrix with size is decided\n by the argument `mass_matrix_size`.\n :param int mass_matrix_size: Size of the mass matrix.\n :return: initial state of the adapt scheme.\n \"\"\"\n rng_key, rng_key_ss = random.split(rng_key)\n (\n inverse_mass_matrix,\n mass_matrix_sqrt,\n mass_matrix_sqrt_inv,\n ) = _initialize_mass_matrix(z_info[0], inverse_mass_matrix, dense_mass)\n\n if adapt_step_size:\n step_size = find_reasonable_step_size(\n step_size, inverse_mass_matrix, z_info, rng_key_ss\n )\n ss_state = ss_init(jnp.log(10 * step_size))\n\n if isinstance(inverse_mass_matrix, dict):\n size = {k: v.shape for k, v in inverse_mass_matrix.items()}\n else:\n size = inverse_mass_matrix.shape[-1]\n mm_state = mm_init(size)\n\n window_idx = jnp.array(0, dtype=jnp.result_type(int))\n return HMCAdaptState(\n step_size,\n inverse_mass_matrix,\n mass_matrix_sqrt,\n mass_matrix_sqrt_inv,\n ss_state,\n mm_state,\n window_idx,\n rng_key,\n )\n\n def _update_at_window_end(z_info, rng_key_ss, state):\n (\n step_size,\n inverse_mass_matrix,\n mass_matrix_sqrt,\n mass_matrix_sqrt_inv,\n ss_state,\n mm_state,\n window_idx,\n rng_key,\n ) = state\n\n if adapt_mass_matrix:\n inverse_mass_matrix, mass_matrix_sqrt, mass_matrix_sqrt_inv = mm_final(\n mm_state, regularize=True\n )\n if isinstance(inverse_mass_matrix, dict):\n size = {k: v.shape for k, v in inverse_mass_matrix.items()}\n else:\n size = inverse_mass_matrix.shape[-1]\n mm_state = mm_init(size)\n\n if adapt_step_size:\n step_size = find_reasonable_step_size(\n step_size, inverse_mass_matrix, z_info, rng_key_ss\n )\n # NB: when step_size is large, say 1e38, jnp.log(10 * step_size) will be inf\n # and jnp.log(10) + jnp.log(step_size) will be finite\n ss_state = ss_init(jnp.log(10) + jnp.log(step_size))\n\n return HMCAdaptState(\n step_size,\n inverse_mass_matrix,\n mass_matrix_sqrt,\n mass_matrix_sqrt_inv,\n ss_state,\n mm_state,\n window_idx,\n rng_key,\n )\n\n def update_fn(t, accept_prob, z_info, state):\n \"\"\"\n :param int t: The current time step.\n :param float accept_prob: Acceptance probability of the current trajectory.\n :param IntegratorState z_info: The new integrator state.\n :param state: Current state of the adapt scheme.\n :return: new state of the adapt scheme.\n \"\"\"\n (\n step_size,\n inverse_mass_matrix,\n mass_matrix_sqrt,\n mass_matrix_sqrt_inv,\n ss_state,\n mm_state,\n window_idx,\n rng_key,\n ) = state\n if rng_key is not None:\n rng_key, rng_key_ss = random.split(rng_key)\n else:\n rng_key_ss = None\n\n # update step size state\n if adapt_step_size:\n ss_state = ss_update(target_accept_prob - accept_prob, ss_state)\n # note: at the end of warmup phase, use average of log step_size\n log_step_size, log_step_size_avg, *_ = ss_state\n step_size = jnp.where(\n t == (num_adapt_steps - 1),\n jnp.exp(log_step_size_avg),\n jnp.exp(log_step_size),\n )\n # account the the case log_step_size is an extreme number\n finfo = jnp.finfo(jnp.result_type(step_size))\n step_size = jnp.clip(step_size, a_min=finfo.tiny, a_max=finfo.max)\n\n # update mass matrix state\n is_middle_window = (0 < window_idx) & (window_idx < (num_windows - 1))\n if adapt_mass_matrix:\n z = z_info[0]\n mm_state = cond(\n is_middle_window,\n (z, mm_state),\n lambda args: mm_update(*args),\n mm_state,\n identity,\n )\n\n t_at_window_end = t == adaptation_schedule[window_idx, 1]\n window_idx = jnp.where(t_at_window_end, window_idx + 1, window_idx)\n state = HMCAdaptState(\n step_size,\n inverse_mass_matrix,\n mass_matrix_sqrt,\n mass_matrix_sqrt_inv,\n ss_state,\n mm_state,\n window_idx,\n rng_key,\n )\n state = cond(\n t_at_window_end & is_middle_window,\n (z_info, rng_key_ss, state),\n lambda args: _update_at_window_end(*args),\n state,\n identity,\n )\n return state\n\n return init_fn, update_fn\n\n\ndef _momentum_angle(inverse_mass_matrix, r_left, r_right, r_sum):\n if isinstance(inverse_mass_matrix, dict):\n left_angle, right_angle = jnp.zeros(()), jnp.zeros(())\n for site_names, inverse_mm in inverse_mass_matrix.items():\n r_left_b = tuple(r_left[k] for k in site_names)\n r_right_b = tuple(r_right[k] for k in site_names)\n r_sum_b = tuple(r_sum[k] for k in site_names)\n left_a, right_a = _momentum_angle(inverse_mm, r_left_b, r_right_b, r_sum_b)\n left_angle = left_angle + left_a\n right_angle = right_angle + right_a\n return left_angle, right_angle\n\n r_left, _ = ravel_pytree(r_left)\n r_right, _ = ravel_pytree(r_right)\n r_sum, _ = ravel_pytree(r_sum)\n\n if inverse_mass_matrix.ndim == 2:\n v_left = jnp.matmul(inverse_mass_matrix, r_left)\n v_right = jnp.matmul(inverse_mass_matrix, r_right)\n elif inverse_mass_matrix.ndim == 1:\n v_left = jnp.multiply(inverse_mass_matrix, r_left)\n v_right = jnp.multiply(inverse_mass_matrix, r_right)\n else:\n raise ValueError(\"inverse_mass_matrix should have 1 or 2 dimensions.\")\n\n # This implements dynamic termination criterion (ref [2], section A.4.2).\n r_sum = r_sum - (r_left + r_right) / 2\n return jnp.dot(v_left, r_sum), jnp.dot(v_right, r_sum)\n\n\ndef _is_turning(inverse_mass_matrix, r_left, r_right, r_sum):\n left_angle, right_angle = _momentum_angle(\n inverse_mass_matrix, r_left, r_right, r_sum\n )\n turning_at_left = left_angle <= 0\n turning_at_right = right_angle <= 0\n return turning_at_left | turning_at_right\n\n\ndef _uniform_transition_kernel(current_tree, new_tree):\n # This function computes transition prob for subtrees (ref [2], section A.3.1).\n # e^new_weight / (e^new_weight + e^current_weight)\n transition_prob = expit(new_tree.weight - current_tree.weight)\n return transition_prob\n\n\ndef _biased_transition_kernel(current_tree, new_tree):\n # This function computes transition prob for main trees (ref [2], section A.3.2).\n transition_prob = jnp.exp(new_tree.weight - current_tree.weight)\n # If new tree is turning or diverging, we won't move the proposal\n # to the new tree.\n transition_prob = jnp.where(\n new_tree.turning | new_tree.diverging, 0.0, jnp.clip(transition_prob, a_max=1.0)\n )\n return transition_prob\n\n\ndef _combine_tree(\n current_tree, new_tree, inverse_mass_matrix, going_right, rng_key, biased_transition\n):\n # Now we combine the current tree and the new tree. Note that outside\n # leaves of the combined tree are determined by the direction.\n z_left, r_left, z_left_grad, z_right, r_right, r_right_grad = cond(\n going_right,\n (current_tree, new_tree),\n lambda trees: (\n trees[0].z_left,\n trees[0].r_left,\n trees[0].z_left_grad,\n trees[1].z_right,\n trees[1].r_right,\n trees[1].z_right_grad,\n ),\n (new_tree, current_tree),\n lambda trees: (\n trees[0].z_left,\n trees[0].r_left,\n trees[0].z_left_grad,\n trees[1].z_right,\n trees[1].r_right,\n trees[1].z_right_grad,\n ),\n )\n r_sum = tree_multimap(jnp.add, current_tree.r_sum, new_tree.r_sum)\n\n if biased_transition:\n transition_prob = _biased_transition_kernel(current_tree, new_tree)\n turning = new_tree.turning | _is_turning(\n inverse_mass_matrix, r_left, r_right, r_sum\n )\n else:\n transition_prob = _uniform_transition_kernel(current_tree, new_tree)\n turning = current_tree.turning\n\n transition = random.bernoulli(rng_key, transition_prob)\n z_proposal, z_proposal_pe, z_proposal_grad, z_proposal_energy = cond(\n transition,\n new_tree,\n lambda tree: (\n tree.z_proposal,\n tree.z_proposal_pe,\n tree.z_proposal_grad,\n tree.z_proposal_energy,\n ),\n current_tree,\n lambda tree: (\n tree.z_proposal,\n tree.z_proposal_pe,\n tree.z_proposal_grad,\n tree.z_proposal_energy,\n ),\n )\n\n tree_depth = current_tree.depth + 1\n tree_weight = jnp.logaddexp(current_tree.weight, new_tree.weight)\n diverging = new_tree.diverging\n\n sum_accept_probs = current_tree.sum_accept_probs + new_tree.sum_accept_probs\n num_proposals = current_tree.num_proposals + new_tree.num_proposals\n\n return TreeInfo(\n z_left,\n r_left,\n z_left_grad,\n z_right,\n r_right,\n r_right_grad,\n z_proposal,\n z_proposal_pe,\n z_proposal_grad,\n z_proposal_energy,\n tree_depth,\n tree_weight,\n r_sum,\n turning,\n diverging,\n sum_accept_probs,\n num_proposals,\n )\n\n\ndef _build_basetree(\n vv_update,\n kinetic_fn,\n z,\n r,\n z_grad,\n inverse_mass_matrix,\n step_size,\n going_right,\n energy_current,\n max_delta_energy,\n):\n step_size = jnp.where(going_right, step_size, -step_size)\n z_new, r_new, potential_energy_new, z_new_grad = vv_update(\n step_size, inverse_mass_matrix, (z, r, energy_current, z_grad)\n )\n\n energy_new = potential_energy_new + kinetic_fn(inverse_mass_matrix, r_new)\n delta_energy = energy_new - energy_current\n # Handles the NaN case.\n delta_energy = jnp.where(jnp.isnan(delta_energy), jnp.inf, delta_energy)\n tree_weight = -delta_energy\n\n diverging = delta_energy > max_delta_energy\n accept_prob = jnp.clip(jnp.exp(-delta_energy), a_max=1.0)\n return TreeInfo(\n z_new,\n r_new,\n z_new_grad,\n z_new,\n r_new,\n z_new_grad,\n z_new,\n potential_energy_new,\n z_new_grad,\n energy_new,\n depth=0,\n weight=tree_weight,\n r_sum=r_new,\n turning=False,\n diverging=diverging,\n sum_accept_probs=accept_prob,\n num_proposals=1,\n )\n\n\ndef _get_leaf(tree, going_right):\n return cond(\n going_right,\n tree,\n lambda tree: (tree.z_right, tree.r_right, tree.z_right_grad),\n tree,\n lambda tree: (tree.z_left, tree.r_left, tree.z_left_grad),\n )\n\n\ndef _double_tree(\n current_tree,\n vv_update,\n kinetic_fn,\n inverse_mass_matrix,\n step_size,\n going_right,\n rng_key,\n energy_current,\n max_delta_energy,\n r_ckpts,\n r_sum_ckpts,\n):\n key, transition_key = random.split(rng_key)\n\n new_tree = _iterative_build_subtree(\n current_tree,\n vv_update,\n kinetic_fn,\n inverse_mass_matrix,\n step_size,\n going_right,\n key,\n energy_current,\n max_delta_energy,\n r_ckpts,\n r_sum_ckpts,\n )\n\n return _combine_tree(\n current_tree, new_tree, inverse_mass_matrix, going_right, transition_key, True\n )\n\n\ndef _leaf_idx_to_ckpt_idxs(n):\n # computes the number of non-zero bits except the last bit\n # e.g. 6 -> 2, 7 -> 2, 13 -> 2\n _, idx_max = while_loop(\n lambda nc: nc[0] > 0, lambda nc: (nc[0] >> 1, nc[1] + (nc[0] & 1)), (n >> 1, 0)\n )\n # computes the number of contiguous last non-zero bits\n # e.g. 6 -> 0, 7 -> 3, 13 -> 1\n _, num_subtrees = while_loop(\n lambda nc: (nc[0] & 1) != 0, lambda nc: (nc[0] >> 1, nc[1] + 1), (n, 0)\n )\n # TODO: explore the potential of setting idx_min=0 to allow more turning checks\n # It will be useful in case: e.g. assume a tree 0 -> 7 is a circle,\n # subtrees 0 -> 3, 4 -> 7 are half-circles, which two leaves might not\n # satisfy turning condition;\n # the full tree 0 -> 7 is a circle, which two leaves might also not satisfy\n # turning condition;\n # however, we can check the turning condition of the subtree 0 -> 5, which\n # likely satisfies turning condition because its trajectory 3/4 of a circle.\n # XXX: make sure that detailed balance is satisfied if we follow this direction\n idx_min = idx_max - num_subtrees + 1\n return idx_min, idx_max\n\n\ndef _is_iterative_turning(\n inverse_mass_matrix,\n r,\n r_sum,\n r_ckpts,\n r_sum_ckpts,\n idx_min,\n idx_max,\n unravel_fn=identity,\n):\n def _body_fn(state):\n i, _ = state\n subtree_r_sum = r_sum - r_sum_ckpts[i] + r_ckpts[i]\n subtree_r_sum = unravel_fn(subtree_r_sum)\n r_left = unravel_fn(r_ckpts[i])\n return i - 1, _is_turning(inverse_mass_matrix, r_left, r, subtree_r_sum)\n\n _, turning = while_loop(\n lambda it: (it[0] >= idx_min) & ~it[1], _body_fn, (idx_max, False)\n )\n return turning\n\n\ndef _iterative_build_subtree(\n prototype_tree,\n vv_update,\n kinetic_fn,\n inverse_mass_matrix,\n step_size,\n going_right,\n rng_key,\n energy_current,\n max_delta_energy,\n r_ckpts,\n r_sum_ckpts,\n):\n max_num_proposals = 2 ** prototype_tree.depth\n\n def _cond_fn(state):\n tree, turning, _, _, _ = state\n return (tree.num_proposals < max_num_proposals) & ~turning & ~tree.diverging\n\n def _body_fn(state):\n current_tree, _, r_ckpts, r_sum_ckpts, rng_key = state\n rng_key, transition_rng_key = random.split(rng_key)\n # If we are going to the right, start from the right leaf of the current tree.\n z, r, z_grad = _get_leaf(current_tree, going_right)\n new_leaf = _build_basetree(\n vv_update,\n kinetic_fn,\n z,\n r,\n z_grad,\n inverse_mass_matrix,\n step_size,\n going_right,\n energy_current,\n max_delta_energy,\n )\n new_tree = cond(\n current_tree.num_proposals == 0,\n new_leaf,\n identity,\n (\n current_tree,\n new_leaf,\n inverse_mass_matrix,\n going_right,\n transition_rng_key,\n ),\n lambda x: _combine_tree(*x, False),\n )\n\n leaf_idx = current_tree.num_proposals\n # NB: in the special case leaf_idx=0, ckpt_idx_min=1 and ckpt_idx_max=0,\n # the following logic is still valid for that case\n ckpt_idx_min, ckpt_idx_max = _leaf_idx_to_ckpt_idxs(leaf_idx)\n r, unravel_fn = ravel_pytree(new_leaf.r_right)\n r_sum, _ = ravel_pytree(new_tree.r_sum)\n # we update checkpoints when leaf_idx is even\n r_ckpts, r_sum_ckpts = cond(\n leaf_idx % 2 == 0,\n (r_ckpts, r_sum_ckpts),\n lambda x: (\n index_update(x[0], ckpt_idx_max, r),\n index_update(x[1], ckpt_idx_max, r_sum),\n ),\n (r_ckpts, r_sum_ckpts),\n identity,\n )\n\n turning = _is_iterative_turning(\n inverse_mass_matrix,\n new_leaf.r_right,\n r_sum,\n r_ckpts,\n r_sum_ckpts,\n ckpt_idx_min,\n ckpt_idx_max,\n unravel_fn,\n )\n return new_tree, turning, r_ckpts, r_sum_ckpts, rng_key\n\n basetree = prototype_tree._replace(num_proposals=0)\n\n tree, turning, _, _, _ = while_loop(\n _cond_fn, _body_fn, (basetree, False, r_ckpts, r_sum_ckpts, rng_key)\n )\n # update depth and turning condition\n return TreeInfo(\n tree.z_left,\n tree.r_left,\n tree.z_left_grad,\n tree.z_right,\n tree.r_right,\n tree.z_right_grad,\n tree.z_proposal,\n tree.z_proposal_pe,\n tree.z_proposal_grad,\n tree.z_proposal_energy,\n prototype_tree.depth,\n tree.weight,\n tree.r_sum,\n turning,\n tree.diverging,\n tree.sum_accept_probs,\n tree.num_proposals,\n )\n\n\ndef build_tree(\n verlet_update,\n kinetic_fn,\n verlet_state,\n inverse_mass_matrix,\n step_size,\n rng_key,\n max_delta_energy=1000.0,\n max_tree_depth=10,\n):\n \"\"\"\n Builds a binary tree from the `verlet_state`. This is used in NUTS sampler.\n\n **References:**\n\n 1. *The No-U-Turn Sampler: Adaptively Setting Path Lengths in Hamiltonian Monte Carlo*,\n Matthew D. Hoffman, Andrew Gelman\n 2. *A Conceptual Introduction to Hamiltonian Monte Carlo*,\n Michael Betancourt\n\n :param verlet_update: A callable to get a new integrator state given a current\n integrator state.\n :param kinetic_fn: A callable to compute kinetic energy.\n :param verlet_state: Initial integrator state.\n :param inverse_mass_matrix: Inverse of the mass matrix.\n :param float step_size: Step size for the current trajectory.\n :param jax.random.PRNGKey rng_key: random key to be used as the source of\n randomness.\n :param float max_delta_energy: A threshold to decide if the new state diverges\n (based on the energy difference) too much from the initial integrator state.\n :param int max_tree_depth: Max depth of the binary tree created during the doubling\n scheme of NUTS sampler. Defaults to 10. This argument also accepts a tuple of\n integers `(d1, d2)`, where `d1` is the max tree depth at the current MCMC\n step and `d2` is the global max tree depth for all MCMC steps.\n :return: information of the tree.\n :rtype: :data:`TreeInfo`\n \"\"\"\n if isinstance(max_tree_depth, tuple):\n max_tree_depth_current, max_tree_depth = max_tree_depth\n else:\n max_tree_depth_current = max_tree_depth\n z, r, potential_energy, z_grad = verlet_state\n energy_current = potential_energy + kinetic_fn(inverse_mass_matrix, r)\n latent_size = jnp.size(ravel_pytree(r)[0])\n r_ckpts = jnp.zeros((max_tree_depth, latent_size))\n r_sum_ckpts = jnp.zeros((max_tree_depth, latent_size))\n\n tree = TreeInfo(\n z,\n r,\n z_grad,\n z,\n r,\n z_grad,\n z,\n potential_energy,\n z_grad,\n energy_current,\n depth=0,\n weight=jnp.zeros(()),\n r_sum=r,\n turning=jnp.array(False),\n diverging=jnp.array(False),\n sum_accept_probs=jnp.zeros(()),\n num_proposals=jnp.array(0, dtype=jnp.result_type(int)),\n )\n\n def _cond_fn(state):\n tree, _ = state\n return (tree.depth < max_tree_depth_current) & ~tree.turning & ~tree.diverging\n\n def _body_fn(state):\n tree, key = state\n key, direction_key, doubling_key = random.split(key, 3)\n going_right = random.bernoulli(direction_key)\n tree = _double_tree(\n tree,\n verlet_update,\n kinetic_fn,\n inverse_mass_matrix,\n step_size,\n going_right,\n doubling_key,\n energy_current,\n max_delta_energy,\n r_ckpts,\n r_sum_ckpts,\n )\n return tree, key\n\n state = (tree, rng_key)\n tree, _ = while_loop(_cond_fn, _body_fn, state)\n return tree\n\n\ndef euclidean_kinetic_energy(inverse_mass_matrix, r):\n if isinstance(inverse_mass_matrix, dict):\n ke = jnp.zeros(())\n for site_names, inverse_mm in inverse_mass_matrix.items():\n r_block = tuple(r[k] for k in site_names)\n ke = ke + euclidean_kinetic_energy(inverse_mm, r_block)\n return ke\n\n r, _ = ravel_pytree(r)\n\n if inverse_mass_matrix.ndim == 2:\n v = jnp.matmul(inverse_mass_matrix, r)\n elif inverse_mass_matrix.ndim == 1:\n v = jnp.multiply(inverse_mass_matrix, r)\n else:\n raise ValueError(\"inverse_mass_matrix should have 1 or 2 dimensions.\")\n\n return 0.5 * jnp.dot(v, r)\n\n\ndef _euclidean_kinetic_energy_grad(inverse_mass_matrix, r):\n if isinstance(inverse_mass_matrix, dict):\n r_grad = {}\n for site_names, inverse_mm in inverse_mass_matrix.items():\n r_block = OrderedDict([(k, r[k]) for k in site_names])\n r_grad.update(_euclidean_kinetic_energy_grad(inverse_mm, r_block))\n return r_grad\n\n r, unravel_fn = ravel_pytree(r)\n\n if inverse_mass_matrix.ndim == 2:\n v = jnp.matmul(inverse_mass_matrix, r)\n elif inverse_mass_matrix.ndim == 1:\n v = jnp.multiply(inverse_mass_matrix, r)\n else:\n raise ValueError(\"inverse_mass_matrix should have 1 or 2 dimensions.\")\n\n return unravel_fn(v)\n\n\neuclidean_kinetic_energy._kinetic_grad = _euclidean_kinetic_energy_grad\n\n\ndef consensus(subposteriors, num_draws=None, diagonal=False, rng_key=None):\n \"\"\"\n Merges subposteriors following consensus Monte Carlo algorithm.\n\n **References:**\n\n 1. *Bayes and big data: The consensus Monte Carlo algorithm*,\n Steven L. Scott, Alexander W. Blocker, Fernando V. Bonassi, Hugh A. Chipman,\n Edward I. George, Robert E. McCulloch\n\n :param list subposteriors: a list in which each element is a collection of samples.\n :param int num_draws: number of draws from the merged posterior.\n :param bool diagonal: whether to compute weights using variance or covariance, defaults to\n `False` (using covariance).\n :param jax.random.PRNGKey rng_key: source of the randomness, defaults to `jax.random.PRNGKey(0)`.\n :return: if `num_draws` is None, merges subposteriors without resampling; otherwise, returns\n a collection of `num_draws` samples with the same data structure as each subposterior.\n \"\"\"\n # stack subposteriors\n joined_subposteriors = tree_multimap(lambda *args: jnp.stack(args), *subposteriors)\n # shape of joined_subposteriors: n_subs x n_samples x sample_shape\n joined_subposteriors = vmap(vmap(lambda sample: ravel_pytree(sample)[0]))(\n joined_subposteriors\n )\n\n if num_draws is not None:\n rng_key = random.PRNGKey(0) if rng_key is None else rng_key\n # randomly gets num_draws from subposteriors\n n_subs = len(subposteriors)\n n_samples = tree_flatten(subposteriors[0])[0][0].shape[0]\n # shape of draw_idxs: n_subs x num_draws x sample_shape\n draw_idxs = random.randint(\n rng_key, shape=(n_subs, num_draws), minval=0, maxval=n_samples\n )\n joined_subposteriors = vmap(lambda x, idx: x[idx])(\n joined_subposteriors, draw_idxs\n )\n\n if diagonal:\n # compute weights for each subposterior (ref: Section 3.1 of [1])\n weights = vmap(lambda x: 1 / jnp.var(x, ddof=1, axis=0))(joined_subposteriors)\n normalized_weights = weights / jnp.sum(weights, axis=0)\n # get weighted samples\n samples_flat = jnp.einsum(\n \"ij,ikj->kj\", normalized_weights, joined_subposteriors\n )\n else:\n weights = vmap(lambda x: jnp.linalg.inv(jnp.cov(x.T)))(joined_subposteriors)\n normalized_weights = jnp.matmul(\n jnp.linalg.inv(jnp.sum(weights, axis=0)), weights\n )\n samples_flat = jnp.einsum(\n \"ijk,ilk->lj\", normalized_weights, joined_subposteriors\n )\n\n # unravel_fn acts on 1 sample of a subposterior\n _, unravel_fn = ravel_pytree(tree_map(lambda x: x[0], subposteriors[0]))\n return vmap(lambda x: unravel_fn(x))(samples_flat)\n\n\ndef parametric(subposteriors, diagonal=False):\n \"\"\"\n Merges subposteriors following (embarrassingly parallel) parametric Monte Carlo algorithm.\n\n **References:**\n\n 1. *Asymptotically Exact, Embarrassingly Parallel MCMC*,\n Willie Neiswanger, Chong Wang, Eric Xing\n\n :param list subposteriors: a list in which each element is a collection of samples.\n :param bool diagonal: whether to compute weights using variance or covariance, defaults to\n `False` (using covariance).\n :return: the estimated mean and variance/covariance parameters of the joined posterior\n \"\"\"\n joined_subposteriors = tree_multimap(lambda *args: jnp.stack(args), *subposteriors)\n joined_subposteriors = vmap(vmap(lambda sample: ravel_pytree(sample)[0]))(\n joined_subposteriors\n )\n\n submeans = jnp.mean(joined_subposteriors, axis=1)\n if diagonal:\n weights = vmap(lambda x: 1 / jnp.var(x, ddof=1, axis=0))(joined_subposteriors)\n var = 1 / jnp.sum(weights, axis=0)\n normalized_weights = var * weights\n\n # comparing to consensus implementation, we compute weighted mean here\n mean = jnp.einsum(\"ij,ij->j\", normalized_weights, submeans)\n return mean, var\n else:\n weights = vmap(lambda x: jnp.linalg.inv(jnp.cov(x.T)))(joined_subposteriors)\n cov = jnp.linalg.inv(jnp.sum(weights, axis=0))\n normalized_weights = jnp.matmul(cov, weights)\n\n # comparing to consensus implementation, we compute weighted mean here\n mean = jnp.einsum(\"ijk,ik->j\", normalized_weights, submeans)\n return mean, cov\n\n\ndef parametric_draws(subposteriors, num_draws, diagonal=False, rng_key=None):\n \"\"\"\n Merges subposteriors following (embarrassingly parallel) parametric Monte Carlo algorithm.\n\n **References:**\n\n 1. *Asymptotically Exact, Embarrassingly Parallel MCMC*,\n Willie Neiswanger, Chong Wang, Eric Xing\n\n :param list subposteriors: a list in which each element is a collection of samples.\n :param int num_draws: number of draws from the merged posterior.\n :param bool diagonal: whether to compute weights using variance or covariance, defaults to\n `False` (using covariance).\n :param jax.random.PRNGKey rng_key: source of the randomness, defaults to `jax.random.PRNGKey(0)`.\n :return: a collection of `num_draws` samples with the same data structure as each subposterior.\n \"\"\"\n rng_key = random.PRNGKey(0) if rng_key is None else rng_key\n if diagonal:\n mean, var = parametric(subposteriors, diagonal=True)\n samples_flat = dist.Normal(mean, jnp.sqrt(var)).sample(rng_key, (num_draws,))\n else:\n mean, cov = parametric(subposteriors, diagonal=False)\n samples_flat = dist.MultivariateNormal(mean, cov).sample(rng_key, (num_draws,))\n\n _, unravel_fn = ravel_pytree(tree_map(lambda x: x[0], subposteriors[0]))\n return vmap(lambda x: unravel_fn(x))(samples_flat)\n", "path": "numpyro/infer/hmc_util.py" }, { "content": "# Copyright Contributors to the Pyro project.\n# SPDX-License-Identifier: Apache-2.0\n\nfrom collections import OrderedDict, namedtuple\nimport math\nimport os\n\nfrom jax import device_put, lax, partial, random, vmap\nfrom jax.flatten_util import ravel_pytree\nimport jax.numpy as jnp\n\nfrom numpyro.infer.hmc_util import (\n IntegratorState,\n build_tree,\n euclidean_kinetic_energy,\n find_reasonable_step_size,\n velocity_verlet,\n warmup_adapter,\n)\nfrom numpyro.infer.mcmc import MCMCKernel\nfrom numpyro.infer.util import ParamInfo, init_to_uniform, initialize_model\nfrom numpyro.util import cond, fori_loop, identity\n\nHMCState = namedtuple(\n \"HMCState\",\n [\n \"i\",\n \"z\",\n \"z_grad\",\n \"potential_energy\",\n \"energy\",\n \"r\",\n \"trajectory_length\",\n \"num_steps\",\n \"accept_prob\",\n \"mean_accept_prob\",\n \"diverging\",\n \"adapt_state\",\n \"rng_key\",\n ],\n)\n\"\"\"\nA :func:`~collections.namedtuple` consisting of the following fields:\n\n - **i** - iteration. This is reset to 0 after warmup.\n - **z** - Python collection representing values (unconstrained samples from\n the posterior) at latent sites.\n - **z_grad** - Gradient of potential energy w.r.t. latent sample sites.\n - **potential_energy** - Potential energy computed at the given value of ``z``.\n - **energy** - Sum of potential energy and kinetic energy of the current state.\n - **r** - The current momentum variable. If this is None, a new momentum variable\n will be drawn at the beginning of each sampling step.\n - **trajectory_length** - The amount of time to run HMC dynamics in each sampling step.\n This field is not used in NUTS.\n - **num_steps** - Number of steps in the Hamiltonian trajectory (for diagnostics).\n In NUTS sampler, the tree depth of a trajectory can be computed from this field\n with `tree_depth = np.log2(num_steps).astype(int) + 1`.\n - **accept_prob** - Acceptance probability of the proposal. Note that ``z``\n does not correspond to the proposal if it is rejected.\n - **mean_accept_prob** - Mean acceptance probability until current iteration\n during warmup adaptation or sampling (for diagnostics).\n - **diverging** - A boolean value to indicate whether the current trajectory is diverging.\n - **adapt_state** - A ``HMCAdaptState`` namedtuple which contains adaptation information\n during warmup:\n\n + **step_size** - Step size to be used by the integrator in the next iteration.\n + **inverse_mass_matrix** - The inverse mass matrix to be used for the next\n iteration.\n + **mass_matrix_sqrt** - The square root of mass matrix to be used for the next\n iteration. In case of dense mass, this is the Cholesky factorization of the\n mass matrix.\n\n - **rng_key** - random number generator seed used for the iteration.\n\"\"\"\n\n\ndef _get_num_steps(step_size, trajectory_length):\n num_steps = jnp.ceil(trajectory_length / step_size)\n # NB: casting to jnp.int64 does not take effect (returns jnp.int32 instead)\n # if jax_enable_x64 is False\n return num_steps.astype(jnp.result_type(int))\n\n\ndef momentum_generator(prototype_r, mass_matrix_sqrt, rng_key):\n if isinstance(mass_matrix_sqrt, dict):\n rng_keys = random.split(rng_key, len(mass_matrix_sqrt))\n r = {}\n for (site_names, mm_sqrt), rng_key in zip(mass_matrix_sqrt.items(), rng_keys):\n r_block = OrderedDict([(k, prototype_r[k]) for k in site_names])\n r.update(momentum_generator(r_block, mm_sqrt, rng_key))\n return r\n\n _, unpack_fn = ravel_pytree(prototype_r)\n eps = random.normal(rng_key, jnp.shape(mass_matrix_sqrt)[:1])\n if mass_matrix_sqrt.ndim == 1:\n r = jnp.multiply(mass_matrix_sqrt, eps)\n return unpack_fn(r)\n elif mass_matrix_sqrt.ndim == 2:\n r = jnp.dot(mass_matrix_sqrt, eps)\n return unpack_fn(r)\n else:\n raise ValueError(\"Mass matrix has incorrect number of dims.\")\n\n\ndef hmc(potential_fn=None, potential_fn_gen=None, kinetic_fn=None, algo=\"NUTS\"):\n r\"\"\"\n Hamiltonian Monte Carlo inference, using either fixed number of\n steps or the No U-Turn Sampler (NUTS) with adaptive path length.\n\n **References:**\n\n 1. *MCMC Using Hamiltonian Dynamics*,\n Radford M. Neal\n 2. *The No-U-turn sampler: adaptively setting path lengths in Hamiltonian Monte Carlo*,\n Matthew D. Hoffman, and Andrew Gelman.\n 3. *A Conceptual Introduction to Hamiltonian Monte Carlo`*,\n Michael Betancourt\n\n :param potential_fn: Python callable that computes the potential energy\n given input parameters. The input parameters to `potential_fn` can be\n any python collection type, provided that `init_params` argument to\n `init_kernel` has the same type.\n :param potential_fn_gen: Python callable that when provided with model\n arguments / keyword arguments returns `potential_fn`. This\n may be provided to do inference on the same model with changing data.\n If the data shape remains the same, we can compile `sample_kernel`\n once, and use the same for multiple inference runs.\n :param kinetic_fn: Python callable that returns the kinetic energy given\n inverse mass matrix and momentum. If not provided, the default is\n euclidean kinetic energy.\n :param str algo: Whether to run ``HMC`` with fixed number of steps or ``NUTS``\n with adaptive path length. Default is ``NUTS``.\n :return: a tuple of callables (`init_kernel`, `sample_kernel`), the first\n one to initialize the sampler, and the second one to generate samples\n given an existing one.\n\n .. warning::\n Instead of using this interface directly, we would highly recommend you\n to use the higher level :class:`numpyro.infer.MCMC` API instead.\n\n **Example**\n\n .. doctest::\n\n >>> import jax\n >>> from jax import random\n >>> import jax.numpy as jnp\n >>> import numpyro\n >>> import numpyro.distributions as dist\n >>> from numpyro.infer.hmc import hmc\n >>> from numpyro.infer.util import initialize_model\n >>> from numpyro.util import fori_collect\n\n >>> true_coefs = jnp.array([1., 2., 3.])\n >>> data = random.normal(random.PRNGKey(2), (2000, 3))\n >>> labels = dist.Bernoulli(logits=(true_coefs * data).sum(-1)).sample(random.PRNGKey(3))\n >>>\n >>> def model(data, labels):\n ... coefs = numpyro.sample('coefs', dist.Normal(jnp.zeros(3), jnp.ones(3)))\n ... intercept = numpyro.sample('intercept', dist.Normal(0., 10.))\n ... return numpyro.sample('y', dist.Bernoulli(logits=(coefs * data + intercept).sum(-1)), obs=labels)\n >>>\n >>> model_info = initialize_model(random.PRNGKey(0), model, model_args=(data, labels,))\n >>> init_kernel, sample_kernel = hmc(model_info.potential_fn, algo='NUTS')\n >>> hmc_state = init_kernel(model_info.param_info,\n ... trajectory_length=10,\n ... num_warmup=300)\n >>> samples = fori_collect(0, 500, sample_kernel, hmc_state,\n ... transform=lambda state: model_info.postprocess_fn(state.z))\n >>> print(jnp.mean(samples['coefs'], axis=0)) # doctest: +SKIP\n [0.9153987 2.0754058 2.9621222]\n \"\"\"\n if kinetic_fn is None:\n kinetic_fn = euclidean_kinetic_energy\n vv_update = None\n max_treedepth = None\n wa_update = None\n wa_steps = None\n forward_mode_ad = False\n max_delta_energy = 1000.0\n if algo not in {\"HMC\", \"NUTS\"}:\n raise ValueError(\"`algo` must be one of `HMC` or `NUTS`.\")\n\n def init_kernel(\n init_params,\n num_warmup,\n step_size=1.0,\n inverse_mass_matrix=None,\n adapt_step_size=True,\n adapt_mass_matrix=True,\n dense_mass=False,\n target_accept_prob=0.8,\n trajectory_length=2 * math.pi,\n max_tree_depth=10,\n find_heuristic_step_size=False,\n forward_mode_differentiation=False,\n model_args=(),\n model_kwargs=None,\n rng_key=random.PRNGKey(0),\n ):\n \"\"\"\n Initializes the HMC sampler.\n\n :param init_params: Initial parameters to begin sampling. The type must\n be consistent with the input type to `potential_fn`.\n :param int num_warmup: Number of warmup steps; samples generated\n during warmup are discarded.\n :param float step_size: Determines the size of a single step taken by the\n verlet integrator while computing the trajectory using Hamiltonian\n dynamics. If not specified, it will be set to 1.\n :param inverse_mass_matrix: Initial value for inverse mass matrix.\n This may be adapted during warmup if adapt_mass_matrix = True.\n If no value is specified, then it is initialized to the identity matrix.\n For a potential_fn with general JAX pytree parameters, the order of entries\n of the mass matrix is the order of the flattened version of pytree parameters\n obtained with `jax.tree_flatten`, which is a bit ambiguous (see more at\n https://jax.readthedocs.io/en/latest/pytrees.html). If `model` is not None,\n here we can specify a structured block mass matrix as a dictionary, where\n keys are tuple of site names and values are the corresponding block of the\n mass matrix.\n For more information about structured mass matrix, see `dense_mass` argument.\n :type inverse_mass_matrix: numpy.ndarray or dict\n :param bool adapt_step_size: A flag to decide if we want to adapt step_size\n during warm-up phase using Dual Averaging scheme.\n :param bool adapt_mass_matrix: A flag to decide if we want to adapt mass\n matrix during warm-up phase using Welford scheme.\n :param dense_mass: This flag controls whether mass matrix is dense (i.e. full-rank) or\n diagonal (defaults to ``dense_mass=False``). To specify a structured mass matrix,\n users can provide a list of tuples of site names. Each tuple represents\n a block in the joint mass matrix. For example, assuming that the model\n has latent variables \"x\", \"y\", \"z\" (where each variable can be multi-dimensional),\n possible specifications and corresponding mass matrix structures are as follows:\n\n + dense_mass=[(\"x\", \"y\")]: use a dense mass matrix for the joint\n (x, y) and a diagonal mass matrix for z\n + dense_mass=[] (equivalent to dense_mass=False): use a diagonal mass\n matrix for the joint (x, y, z)\n + dense_mass=[(\"x\", \"y\", \"z\")] (equivalent to full_mass=True):\n use a dense mass matrix for the joint (x, y, z)\n + dense_mass=[(\"x\",), (\"y\",), (\"z\")]: use dense mass matrices for\n each of x, y, and z (i.e. block-diagonal with 3 blocks)\n\n :type dense_mass: bool or list\n :param float target_accept_prob: Target acceptance probability for step size\n adaptation using Dual Averaging. Increasing this value will lead to a smaller\n step size, hence the sampling will be slower but more robust. Default to 0.8.\n :param float trajectory_length: Length of a MCMC trajectory for HMC. Default\n value is :math:`2\\\\pi`.\n :param int max_tree_depth: Max depth of the binary tree created during the doubling\n scheme of NUTS sampler. Defaults to 10. This argument also accepts a tuple of\n integers `(d1, d2)`, where `d1` is the max tree depth during warmup phase and\n `d2` is the max tree depth during post warmup phase.\n :param bool find_heuristic_step_size: whether to a heuristic function to adjust the\n step size at the beginning of each adaptation window. Defaults to False.\n :param tuple model_args: Model arguments if `potential_fn_gen` is specified.\n :param dict model_kwargs: Model keyword arguments if `potential_fn_gen` is specified.\n :param jax.random.PRNGKey rng_key: random key to be used as the source of\n randomness.\n\n \"\"\"\n step_size = lax.convert_element_type(step_size, jnp.result_type(float))\n trajectory_length = lax.convert_element_type(\n trajectory_length, jnp.result_type(float)\n )\n nonlocal wa_update, max_treedepth, vv_update, wa_steps, forward_mode_ad\n forward_mode_ad = forward_mode_differentiation\n wa_steps = num_warmup\n max_treedepth = (\n max_tree_depth\n if isinstance(max_tree_depth, tuple)\n else (max_tree_depth, max_tree_depth)\n )\n if isinstance(init_params, ParamInfo):\n z, pe, z_grad = init_params\n else:\n z, pe, z_grad = init_params, None, None\n pe_fn = potential_fn\n if potential_fn_gen:\n if pe_fn is not None:\n raise ValueError(\n \"Only one of `potential_fn` or `potential_fn_gen` must be provided.\"\n )\n else:\n kwargs = {} if model_kwargs is None else model_kwargs\n pe_fn = potential_fn_gen(*model_args, **kwargs)\n\n find_reasonable_ss = None\n if find_heuristic_step_size:\n find_reasonable_ss = partial(\n find_reasonable_step_size, pe_fn, kinetic_fn, momentum_generator\n )\n\n wa_init, wa_update = warmup_adapter(\n num_warmup,\n adapt_step_size=adapt_step_size,\n adapt_mass_matrix=adapt_mass_matrix,\n dense_mass=dense_mass,\n target_accept_prob=target_accept_prob,\n find_reasonable_step_size=find_reasonable_ss,\n )\n\n rng_key_hmc, rng_key_wa, rng_key_momentum = random.split(rng_key, 3)\n z_info = IntegratorState(z=z, potential_energy=pe, z_grad=z_grad)\n wa_state = wa_init(\n z_info, rng_key_wa, step_size, inverse_mass_matrix=inverse_mass_matrix\n )\n r = momentum_generator(z, wa_state.mass_matrix_sqrt, rng_key_momentum)\n vv_init, vv_update = velocity_verlet(pe_fn, kinetic_fn, forward_mode_ad)\n vv_state = vv_init(z, r, potential_energy=pe, z_grad=z_grad)\n energy = vv_state.potential_energy + kinetic_fn(\n wa_state.inverse_mass_matrix, vv_state.r\n )\n zero_int = jnp.array(0, dtype=jnp.result_type(int))\n hmc_state = HMCState(\n zero_int,\n vv_state.z,\n vv_state.z_grad,\n vv_state.potential_energy,\n energy,\n None,\n trajectory_length,\n zero_int,\n jnp.zeros(()),\n jnp.zeros(()),\n jnp.array(False),\n wa_state,\n rng_key_hmc,\n )\n return device_put(hmc_state)\n\n def _hmc_next(\n step_size,\n inverse_mass_matrix,\n vv_state,\n model_args,\n model_kwargs,\n rng_key,\n trajectory_length,\n ):\n if potential_fn_gen:\n nonlocal vv_update, forward_mode_ad\n pe_fn = potential_fn_gen(*model_args, **model_kwargs)\n _, vv_update = velocity_verlet(pe_fn, kinetic_fn, forward_mode_ad)\n\n # no need to spend too many steps if the state z has 0 size (i.e. z is empty)\n if len(inverse_mass_matrix) == 0:\n num_steps = 1\n else:\n num_steps = _get_num_steps(step_size, trajectory_length)\n # makes sure trajectory length is constant, rather than step_size * num_steps\n step_size = trajectory_length / num_steps\n vv_state_new = fori_loop(\n 0,\n num_steps,\n lambda i, val: vv_update(step_size, inverse_mass_matrix, val),\n vv_state,\n )\n energy_old = vv_state.potential_energy + kinetic_fn(\n inverse_mass_matrix, vv_state.r\n )\n energy_new = vv_state_new.potential_energy + kinetic_fn(\n inverse_mass_matrix, vv_state_new.r\n )\n delta_energy = energy_new - energy_old\n delta_energy = jnp.where(jnp.isnan(delta_energy), jnp.inf, delta_energy)\n accept_prob = jnp.clip(jnp.exp(-delta_energy), a_max=1.0)\n diverging = delta_energy > max_delta_energy\n transition = random.bernoulli(rng_key, accept_prob)\n vv_state, energy = cond(\n transition,\n (vv_state_new, energy_new),\n identity,\n (vv_state, energy_old),\n identity,\n )\n return vv_state, energy, num_steps, accept_prob, diverging\n\n def _nuts_next(\n step_size,\n inverse_mass_matrix,\n vv_state,\n model_args,\n model_kwargs,\n rng_key,\n max_treedepth_current,\n ):\n if potential_fn_gen:\n nonlocal vv_update, forward_mode_ad\n pe_fn = potential_fn_gen(*model_args, **model_kwargs)\n _, vv_update = velocity_verlet(pe_fn, kinetic_fn, forward_mode_ad)\n\n binary_tree = build_tree(\n vv_update,\n kinetic_fn,\n vv_state,\n inverse_mass_matrix,\n step_size,\n rng_key,\n max_delta_energy=max_delta_energy,\n max_tree_depth=(max_treedepth_current, max(max_treedepth)),\n )\n accept_prob = binary_tree.sum_accept_probs / binary_tree.num_proposals\n num_steps = binary_tree.num_proposals\n vv_state = IntegratorState(\n z=binary_tree.z_proposal,\n r=vv_state.r,\n potential_energy=binary_tree.z_proposal_pe,\n z_grad=binary_tree.z_proposal_grad,\n )\n return (\n vv_state,\n binary_tree.z_proposal_energy,\n num_steps,\n accept_prob,\n binary_tree.diverging,\n )\n\n _next = _nuts_next if algo == \"NUTS\" else _hmc_next\n\n def sample_kernel(hmc_state, model_args=(), model_kwargs=None):\n \"\"\"\n Given an existing :data:`~numpyro.infer.mcmc.HMCState`, run HMC with fixed (possibly adapted)\n step size and return a new :data:`~numpyro.infer.mcmc.HMCState`.\n\n :param hmc_state: Current sample (and associated state).\n :param tuple model_args: Model arguments if `potential_fn_gen` is specified.\n :param dict model_kwargs: Model keyword arguments if `potential_fn_gen` is specified.\n :return: new proposed :data:`~numpyro.infer.mcmc.HMCState` from simulating\n Hamiltonian dynamics given existing state.\n\n \"\"\"\n model_kwargs = {} if model_kwargs is None else model_kwargs\n rng_key, rng_key_momentum, rng_key_transition = random.split(\n hmc_state.rng_key, 3\n )\n r = (\n momentum_generator(\n hmc_state.z, hmc_state.adapt_state.mass_matrix_sqrt, rng_key_momentum\n )\n if hmc_state.r is None\n else hmc_state.r\n )\n vv_state = IntegratorState(\n hmc_state.z, r, hmc_state.potential_energy, hmc_state.z_grad\n )\n if algo == \"HMC\":\n hmc_length_args = (hmc_state.trajectory_length,)\n else:\n hmc_length_args = (\n jnp.where(hmc_state.i < wa_steps, max_treedepth[0], max_treedepth[1]),\n )\n vv_state, energy, num_steps, accept_prob, diverging = _next(\n hmc_state.adapt_state.step_size,\n hmc_state.adapt_state.inverse_mass_matrix,\n vv_state,\n model_args,\n model_kwargs,\n rng_key_transition,\n *hmc_length_args,\n )\n # not update adapt_state after warmup phase\n adapt_state = cond(\n hmc_state.i < wa_steps,\n (hmc_state.i, accept_prob, vv_state, hmc_state.adapt_state),\n lambda args: wa_update(*args),\n hmc_state.adapt_state,\n identity,\n )\n\n itr = hmc_state.i + 1\n n = jnp.where(hmc_state.i < wa_steps, itr, itr - wa_steps)\n mean_accept_prob = (\n hmc_state.mean_accept_prob + (accept_prob - hmc_state.mean_accept_prob) / n\n )\n\n r = vv_state.r if hmc_state.r is not None else None\n return HMCState(\n itr,\n vv_state.z,\n vv_state.z_grad,\n vv_state.potential_energy,\n energy,\n r,\n hmc_state.trajectory_length,\n num_steps,\n accept_prob,\n mean_accept_prob,\n diverging,\n adapt_state,\n rng_key,\n )\n\n # Make `init_kernel` and `sample_kernel` visible from the global scope once\n # `hmc` is called for sphinx doc generation.\n if \"SPHINX_BUILD\" in os.environ:\n hmc.init_kernel = init_kernel\n hmc.sample_kernel = sample_kernel\n\n return init_kernel, sample_kernel\n\n\nclass HMC(MCMCKernel):\n \"\"\"\n Hamiltonian Monte Carlo inference, using fixed trajectory length, with\n provision for step size and mass matrix adaptation.\n\n **References:**\n\n 1. *MCMC Using Hamiltonian Dynamics*,\n Radford M. Neal\n\n :param model: Python callable containing Pyro :mod:`~numpyro.primitives`.\n If model is provided, `potential_fn` will be inferred using the model.\n :param potential_fn: Python callable that computes the potential energy\n given input parameters. The input parameters to `potential_fn` can be\n any python collection type, provided that `init_params` argument to\n :meth:`init` has the same type.\n :param kinetic_fn: Python callable that returns the kinetic energy given\n inverse mass matrix and momentum. If not provided, the default is\n euclidean kinetic energy.\n :param float step_size: Determines the size of a single step taken by the\n verlet integrator while computing the trajectory using Hamiltonian\n dynamics. If not specified, it will be set to 1.\n :param inverse_mass_matrix: Initial value for inverse mass matrix.\n This may be adapted during warmup if adapt_mass_matrix = True.\n If no value is specified, then it is initialized to the identity matrix.\n For a potential_fn with general JAX pytree parameters, the order of entries\n of the mass matrix is the order of the flattened version of pytree parameters\n obtained with `jax.tree_flatten`, which is a bit ambiguous (see more at\n https://jax.readthedocs.io/en/latest/pytrees.html). If `model` is not None,\n here we can specify a structured block mass matrix as a dictionary, where\n keys are tuple of site names and values are the corresponding block of the\n mass matrix.\n For more information about structured mass matrix, see `dense_mass` argument.\n :type inverse_mass_matrix: numpy.ndarray or dict\n :param bool adapt_step_size: A flag to decide if we want to adapt step_size\n during warm-up phase using Dual Averaging scheme.\n :param bool adapt_mass_matrix: A flag to decide if we want to adapt mass\n matrix during warm-up phase using Welford scheme.\n :param dense_mass: This flag controls whether mass matrix is dense (i.e. full-rank) or\n diagonal (defaults to ``dense_mass=False``). To specify a structured mass matrix,\n users can provide a list of tuples of site names. Each tuple represents\n a block in the joint mass matrix. For example, assuming that the model\n has latent variables \"x\", \"y\", \"z\" (where each variable can be multi-dimensional),\n possible specifications and corresponding mass matrix structures are as follows:\n\n + dense_mass=[(\"x\", \"y\")]: use a dense mass matrix for the joint\n (x, y) and a diagonal mass matrix for z\n + dense_mass=[] (equivalent to dense_mass=False): use a diagonal mass\n matrix for the joint (x, y, z)\n + dense_mass=[(\"x\", \"y\", \"z\")] (equivalent to full_mass=True):\n use a dense mass matrix for the joint (x, y, z)\n + dense_mass=[(\"x\",), (\"y\",), (\"z\")]: use dense mass matrices for\n each of x, y, and z (i.e. block-diagonal with 3 blocks)\n\n :type dense_mass: bool or list\n :param float target_accept_prob: Target acceptance probability for step size\n adaptation using Dual Averaging. Increasing this value will lead to a smaller\n step size, hence the sampling will be slower but more robust. Default to 0.8.\n :param float trajectory_length: Length of a MCMC trajectory for HMC. Default\n value is :math:`2\\\\pi`.\n :param callable init_strategy: a per-site initialization function.\n See :ref:`init_strategy` section for available functions.\n :param bool find_heuristic_step_size: whether to a heuristic function to adjust the\n step size at the beginning of each adaptation window. Defaults to False.\n :param bool forward_mode_differentiation: whether to use forward-mode differentiation\n or reverse-mode differentiation. By default, we use reverse mode but the forward\n mode can be useful in some cases to improve the performance. In addition, some\n control flow utility on JAX such as `jax.lax.while_loop` or `jax.lax.fori_loop`\n only supports forward-mode differentiation. See\n `JAX's The Autodiff Cookbook <https://jax.readthedocs.io/en/latest/notebooks/autodiff_cookbook.html>`_\n for more information.\n \"\"\"\n\n def __init__(\n self,\n model=None,\n potential_fn=None,\n kinetic_fn=None,\n step_size=1.0,\n inverse_mass_matrix=None,\n adapt_step_size=True,\n adapt_mass_matrix=True,\n dense_mass=False,\n target_accept_prob=0.8,\n trajectory_length=2 * math.pi,\n init_strategy=init_to_uniform,\n find_heuristic_step_size=False,\n forward_mode_differentiation=False,\n ):\n if not (model is None) ^ (potential_fn is None):\n raise ValueError(\"Only one of `model` or `potential_fn` must be specified.\")\n self._model = model\n self._potential_fn = potential_fn\n self._kinetic_fn = (\n kinetic_fn if kinetic_fn is not None else euclidean_kinetic_energy\n )\n self._step_size = float(step_size) if isinstance(step_size, int) else step_size\n self._inverse_mass_matrix = inverse_mass_matrix\n self._adapt_step_size = adapt_step_size\n self._adapt_mass_matrix = adapt_mass_matrix\n self._dense_mass = dense_mass\n self._target_accept_prob = target_accept_prob\n self._trajectory_length = (\n float(trajectory_length)\n if isinstance(trajectory_length, int)\n else trajectory_length\n )\n self._algo = \"HMC\"\n self._max_tree_depth = 10\n self._init_strategy = init_strategy\n self._find_heuristic_step_size = find_heuristic_step_size\n self._forward_mode_differentiation = forward_mode_differentiation\n # Set on first call to init\n self._init_fn = None\n self._potential_fn_gen = None\n self._postprocess_fn = None\n self._sample_fn = None\n\n def _init_state(self, rng_key, model_args, model_kwargs, init_params):\n if self._model is not None:\n init_params, potential_fn, postprocess_fn, model_trace = initialize_model(\n rng_key,\n self._model,\n dynamic_args=True,\n init_strategy=self._init_strategy,\n model_args=model_args,\n model_kwargs=model_kwargs,\n forward_mode_differentiation=self._forward_mode_differentiation,\n )\n if self._init_fn is None:\n self._init_fn, self._sample_fn = hmc(\n potential_fn_gen=potential_fn,\n kinetic_fn=self._kinetic_fn,\n algo=self._algo,\n )\n self._potential_fn_gen = potential_fn\n self._postprocess_fn = postprocess_fn\n elif self._init_fn is None:\n self._init_fn, self._sample_fn = hmc(\n potential_fn=self._potential_fn,\n kinetic_fn=self._kinetic_fn,\n algo=self._algo,\n )\n\n return init_params\n\n @property\n def model(self):\n return self._model\n\n @property\n def sample_field(self):\n return \"z\"\n\n @property\n def default_fields(self):\n return (\"z\", \"diverging\")\n\n def get_diagnostics_str(self, state):\n return \"{} steps of size {:.2e}. acc. prob={:.2f}\".format(\n state.num_steps, state.adapt_state.step_size, state.mean_accept_prob\n )\n\n def init(\n self, rng_key, num_warmup, init_params=None, model_args=(), model_kwargs={}\n ):\n # non-vectorized\n if rng_key.ndim == 1:\n rng_key, rng_key_init_model = random.split(rng_key)\n # vectorized\n else:\n rng_key, rng_key_init_model = jnp.swapaxes(\n vmap(random.split)(rng_key), 0, 1\n )\n init_params = self._init_state(\n rng_key_init_model, model_args, model_kwargs, init_params\n )\n if self._potential_fn and init_params is None:\n raise ValueError(\n \"Valid value of `init_params` must be provided with\" \" `potential_fn`.\"\n )\n\n # change dense_mass to a structural form\n dense_mass = self._dense_mass\n inverse_mass_matrix = self._inverse_mass_matrix\n if self._model is not None:\n z = init_params[0] if isinstance(init_params, ParamInfo) else init_params\n if isinstance(dense_mass, bool):\n # XXX: by default, the order variables are sorted by their names,\n # this is to be compatible with older numpyro versions\n # and to match autoguide scale parameter and jax flatten utils\n dense_mass = [tuple(sorted(z))] if dense_mass else []\n assert isinstance(dense_mass, list)\n\n hmc_init_fn = lambda init_params, rng_key: self._init_fn( # noqa: E731\n init_params,\n num_warmup=num_warmup,\n step_size=self._step_size,\n inverse_mass_matrix=inverse_mass_matrix,\n adapt_step_size=self._adapt_step_size,\n adapt_mass_matrix=self._adapt_mass_matrix,\n dense_mass=dense_mass,\n target_accept_prob=self._target_accept_prob,\n trajectory_length=self._trajectory_length,\n max_tree_depth=self._max_tree_depth,\n find_heuristic_step_size=self._find_heuristic_step_size,\n forward_mode_differentiation=self._forward_mode_differentiation,\n model_args=model_args,\n model_kwargs=model_kwargs,\n rng_key=rng_key,\n )\n if rng_key.ndim == 1:\n init_state = hmc_init_fn(init_params, rng_key)\n else:\n # XXX it is safe to run hmc_init_fn under vmap despite that hmc_init_fn changes some\n # nonlocal variables: momentum_generator, wa_update, trajectory_len, max_treedepth,\n # wa_steps because those variables do not depend on traced args: init_params, rng_key.\n init_state = vmap(hmc_init_fn)(init_params, rng_key)\n sample_fn = vmap(self._sample_fn, in_axes=(0, None, None))\n self._sample_fn = sample_fn\n return init_state\n\n def postprocess_fn(self, args, kwargs):\n if self._postprocess_fn is None:\n return identity\n return self._postprocess_fn(*args, **kwargs)\n\n def sample(self, state, model_args, model_kwargs):\n \"\"\"\n Run HMC from the given :data:`~numpyro.infer.hmc.HMCState` and return the resulting\n :data:`~numpyro.infer.hmc.HMCState`.\n\n :param HMCState state: Represents the current state.\n :param model_args: Arguments provided to the model.\n :param model_kwargs: Keyword arguments provided to the model.\n :return: Next `state` after running HMC.\n \"\"\"\n return self._sample_fn(state, model_args, model_kwargs)\n\n def __getstate__(self):\n state = self.__dict__.copy()\n state[\"_sample_fn\"] = None\n state[\"_init_fn\"] = None\n state[\"_postprocess_fn\"] = None\n state[\"_potential_fn_gen\"] = None\n return state\n\n\nclass NUTS(HMC):\n \"\"\"\n Hamiltonian Monte Carlo inference, using the No U-Turn Sampler (NUTS)\n with adaptive path length and mass matrix adaptation.\n\n **References:**\n\n 1. *MCMC Using Hamiltonian Dynamics*,\n Radford M. Neal\n 2. *The No-U-turn sampler: adaptively setting path lengths in Hamiltonian Monte Carlo*,\n Matthew D. Hoffman, and Andrew Gelman.\n 3. *A Conceptual Introduction to Hamiltonian Monte Carlo`*,\n Michael Betancourt\n\n :param model: Python callable containing Pyro :mod:`~numpyro.primitives`.\n If model is provided, `potential_fn` will be inferred using the model.\n :param potential_fn: Python callable that computes the potential energy\n given input parameters. The input parameters to `potential_fn` can be\n any python collection type, provided that `init_params` argument to\n `init_kernel` has the same type.\n :param kinetic_fn: Python callable that returns the kinetic energy given\n inverse mass matrix and momentum. If not provided, the default is\n euclidean kinetic energy.\n :param float step_size: Determines the size of a single step taken by the\n verlet integrator while computing the trajectory using Hamiltonian\n dynamics. If not specified, it will be set to 1.\n :param inverse_mass_matrix: Initial value for inverse mass matrix.\n This may be adapted during warmup if adapt_mass_matrix = True.\n If no value is specified, then it is initialized to the identity matrix.\n For a potential_fn with general JAX pytree parameters, the order of entries\n of the mass matrix is the order of the flattened version of pytree parameters\n obtained with `jax.tree_flatten`, which is a bit ambiguous (see more at\n https://jax.readthedocs.io/en/latest/pytrees.html). If `model` is not None,\n here we can specify a structured block mass matrix as a dictionary, where\n keys are tuple of site names and values are the corresponding block of the\n mass matrix.\n For more information about structured mass matrix, see `dense_mass` argument.\n :type inverse_mass_matrix: numpy.ndarray or dict\n :param bool adapt_step_size: A flag to decide if we want to adapt step_size\n during warm-up phase using Dual Averaging scheme.\n :param bool adapt_mass_matrix: A flag to decide if we want to adapt mass\n matrix during warm-up phase using Welford scheme.\n :param dense_mass: This flag controls whether mass matrix is dense (i.e. full-rank) or\n diagonal (defaults to ``dense_mass=False``). To specify a structured mass matrix,\n users can provide a list of tuples of site names. Each tuple represents\n a block in the joint mass matrix. For example, assuming that the model\n has latent variables \"x\", \"y\", \"z\" (where each variable can be multi-dimensional),\n possible specifications and corresponding mass matrix structures are as follows:\n\n + dense_mass=[(\"x\", \"y\")]: use a dense mass matrix for the joint\n (x, y) and a diagonal mass matrix for z\n + dense_mass=[] (equivalent to dense_mass=False): use a diagonal mass\n matrix for the joint (x, y, z)\n + dense_mass=[(\"x\", \"y\", \"z\")] (equivalent to full_mass=True):\n use a dense mass matrix for the joint (x, y, z)\n + dense_mass=[(\"x\",), (\"y\",), (\"z\")]: use dense mass matrices for\n each of x, y, and z (i.e. block-diagonal with 3 blocks)\n\n :type dense_mass: bool or list\n :param float target_accept_prob: Target acceptance probability for step size\n adaptation using Dual Averaging. Increasing this value will lead to a smaller\n step size, hence the sampling will be slower but more robust. Default to 0.8.\n :param float trajectory_length: Length of a MCMC trajectory for HMC. This arg has\n no effect in NUTS sampler.\n :param int max_tree_depth: Max depth of the binary tree created during the doubling\n scheme of NUTS sampler. Defaults to 10. This argument also accepts a tuple of\n integers `(d1, d2)`, where `d1` is the max tree depth during warmup phase and\n `d2` is the max tree depth during post warmup phase.\n :param callable init_strategy: a per-site initialization function.\n See :ref:`init_strategy` section for available functions.\n :param bool find_heuristic_step_size: whether to a heuristic function to adjust the\n step size at the beginning of each adaptation window. Defaults to False.\n :param bool forward_mode_differentiation: whether to use forward-mode differentiation\n or reverse-mode differentiation. By default, we use reverse mode but the forward\n mode can be useful in some cases to improve the performance. In addition, some\n control flow utility on JAX such as `jax.lax.while_loop` or `jax.lax.fori_loop`\n only supports forward-mode differentiation. See\n `JAX's The Autodiff Cookbook <https://jax.readthedocs.io/en/latest/notebooks/autodiff_cookbook.html>`_\n for more information.\n \"\"\"\n\n def __init__(\n self,\n model=None,\n potential_fn=None,\n kinetic_fn=None,\n step_size=1.0,\n inverse_mass_matrix=None,\n adapt_step_size=True,\n adapt_mass_matrix=True,\n dense_mass=False,\n target_accept_prob=0.8,\n trajectory_length=None,\n max_tree_depth=10,\n init_strategy=init_to_uniform,\n find_heuristic_step_size=False,\n forward_mode_differentiation=False,\n ):\n super(NUTS, self).__init__(\n potential_fn=potential_fn,\n model=model,\n kinetic_fn=kinetic_fn,\n step_size=step_size,\n inverse_mass_matrix=inverse_mass_matrix,\n adapt_step_size=adapt_step_size,\n adapt_mass_matrix=adapt_mass_matrix,\n dense_mass=dense_mass,\n target_accept_prob=target_accept_prob,\n trajectory_length=trajectory_length,\n init_strategy=init_strategy,\n find_heuristic_step_size=find_heuristic_step_size,\n forward_mode_differentiation=forward_mode_differentiation,\n )\n self._max_tree_depth = max_tree_depth\n self._algo = \"NUTS\"\n", "path": "numpyro/infer/hmc.py" } ]
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(): [email protected]("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.numpy as jnp\n\nfrom numpyro.infer.hmc_util import (\n IntegratorState,\n build_tree,\n euclidean_kinetic_energy,\n find_reasonable_step_size,\n velocity_verlet,\n warmup_adapter,\n)\nfrom numpyro.infer.mcmc import MCMCKernel\nfrom numpyro.infer.util import ParamInfo, init_to_uniform, initialize_model\nfrom numpyro.util import cond, fori_loop, identity\n\nHMCState = namedtuple(\n \"HMCState\",\n [\n \"i\",\n \"z\",\n \"z_grad\",\n \"potential_energy\",\n \"energy\",\n \"r\",\n \"trajectory_length\",\n \"num_steps\",\n \"accept_prob\",\n \"mean_accept_prob\",\n \"diverging\",\n \"adapt_state\",\n \"rng_key\",\n ],\n)\n\"\"\"\nA :func:`~collections.namedtuple` consisting of the following fields:\n\n - **i** - iteration. This is reset to 0 after warmup.\n - **z** - Python collection representing values (unconstrained samples from\n the posterior) at latent sites.\n - **z_grad** - Gradient of potential energy w.r.t. latent sample sites.\n - **potential_energy** - Potential energy computed at the given value of ``z``.\n - **energy** - Sum of potential energy and kinetic energy of the current state.\n - **r** - The current momentum variable. If this is None, a new momentum variable\n will be drawn at the beginning of each sampling step.\n - **trajectory_length** - The amount of time to run HMC dynamics in each sampling step.\n This field is not used in NUTS.\n - **num_steps** - Number of steps in the Hamiltonian trajectory (for diagnostics).\n In NUTS sampler, the tree depth of a trajectory can be computed from this field\n with `tree_depth = np.log2(num_steps).astype(int) + 1`.\n - **accept_prob** - Acceptance probability of the proposal. Note that ``z``\n does not correspond to the proposal if it is rejected.\n - **mean_accept_prob** - Mean acceptance probability until current iteration\n during warmup adaptation or sampling (for diagnostics).\n - **diverging** - A boolean value to indicate whether the current trajectory is diverging.\n - **adapt_state** - A ``HMCAdaptState`` namedtuple which contains adaptation information\n during warmup:\n\n + **step_size** - Step size to be used by the integrator in the next iteration.\n + **inverse_mass_matrix** - The inverse mass matrix to be used for the next\n iteration.\n + **mass_matrix_sqrt** - The square root of mass matrix to be used for the next\n iteration. In case of dense mass, this is the Cholesky factorization of the\n mass matrix.\n\n - **rng_key** - random number generator seed used for the iteration.\n\"\"\"\n\n\ndef _get_num_steps(step_size, trajectory_length):\n num_steps = jnp.ceil(trajectory_length / step_size)\n # NB: casting to jnp.int64 does not take effect (returns jnp.int32 instead)\n # if jax_enable_x64 is False\n return num_steps.astype(jnp.result_type(int))\n\n\ndef momentum_generator(prototype_r, mass_matrix_sqrt, rng_key):\n if isinstance(mass_matrix_sqrt, dict):\n rng_keys = random.split(rng_key, len(mass_matrix_sqrt))\n r = {}\n for (site_names, mm_sqrt), rng_key in zip(mass_matrix_sqrt.items(), rng_keys):\n r_block = OrderedDict([(k, prototype_r[k]) for k in site_names])\n r.update(momentum_generator(r_block, mm_sqrt, rng_key))\n return r\n\n _, unpack_fn = ravel_pytree(prototype_r)\n eps = random.normal(rng_key, jnp.shape(mass_matrix_sqrt)[:1])\n if mass_matrix_sqrt.ndim == 1:\n r = jnp.multiply(mass_matrix_sqrt, eps)\n return unpack_fn(r)\n elif mass_matrix_sqrt.ndim == 2:\n r = jnp.dot(mass_matrix_sqrt, eps)\n return unpack_fn(r)\n else:\n raise ValueError(\"Mass matrix has incorrect number of dims.\")\n\n\ndef hmc(potential_fn=None, potential_fn_gen=None, kinetic_fn=None, algo=\"NUTS\"):\n r\"\"\"\n Hamiltonian Monte Carlo inference, using either fixed number of\n steps or the No U-Turn Sampler (NUTS) with adaptive path length.\n\n **References:**\n\n 1. *MCMC Using Hamiltonian Dynamics*,\n Radford M. Neal\n 2. *The No-U-turn sampler: adaptively setting path lengths in Hamiltonian Monte Carlo*,\n Matthew D. Hoffman, and Andrew Gelman.\n 3. *A Conceptual Introduction to Hamiltonian Monte Carlo`*,\n Michael Betancourt\n\n :param potential_fn: Python callable that computes the potential energy\n given input parameters. The input parameters to `potential_fn` can be\n any python collection type, provided that `init_params` argument to\n `init_kernel` has the same type.\n :param potential_fn_gen: Python callable that when provided with model\n arguments / keyword arguments returns `potential_fn`. This\n may be provided to do inference on the same model with changing data.\n If the data shape remains the same, we can compile `sample_kernel`\n once, and use the same for multiple inference runs.\n :param kinetic_fn: Python callable that returns the kinetic energy given\n inverse mass matrix and momentum. If not provided, the default is\n euclidean kinetic energy.\n :param str algo: Whether to run ``HMC`` with fixed number of steps or ``NUTS``\n with adaptive path length. Default is ``NUTS``.\n :return: a tuple of callables (`init_kernel`, `sample_kernel`), the first\n one to initialize the sampler, and the second one to generate samples\n given an existing one.\n\n .. warning::\n Instead of using this interface directly, we would highly recommend you\n to use the higher level :class:`~numpyro.infer.mcmc.MCMC` API instead.\n\n **Example**\n\n .. doctest::\n\n >>> import jax\n >>> from jax import random\n >>> import jax.numpy as jnp\n >>> import numpyro\n >>> import numpyro.distributions as dist\n >>> from numpyro.infer.hmc import hmc\n >>> from numpyro.infer.util import initialize_model\n >>> from numpyro.util import fori_collect\n\n >>> true_coefs = jnp.array([1., 2., 3.])\n >>> data = random.normal(random.PRNGKey(2), (2000, 3))\n >>> labels = dist.Bernoulli(logits=(true_coefs * data).sum(-1)).sample(random.PRNGKey(3))\n >>>\n >>> def model(data, labels):\n ... coefs = numpyro.sample('coefs', dist.Normal(jnp.zeros(3), jnp.ones(3)))\n ... intercept = numpyro.sample('intercept', dist.Normal(0., 10.))\n ... return numpyro.sample('y', dist.Bernoulli(logits=(coefs * data + intercept).sum(-1)), obs=labels)\n >>>\n >>> model_info = initialize_model(random.PRNGKey(0), model, model_args=(data, labels,))\n >>> init_kernel, sample_kernel = hmc(model_info.potential_fn, algo='NUTS')\n >>> hmc_state = init_kernel(model_info.param_info,\n ... trajectory_length=10,\n ... num_warmup=300)\n >>> samples = fori_collect(0, 500, sample_kernel, hmc_state,\n ... transform=lambda state: model_info.postprocess_fn(state.z))\n >>> print(jnp.mean(samples['coefs'], axis=0)) # doctest: +SKIP\n [0.9153987 2.0754058 2.9621222]\n \"\"\"\n if kinetic_fn is None:\n kinetic_fn = euclidean_kinetic_energy\n vv_update = None\n max_treedepth = None\n wa_update = None\n wa_steps = None\n forward_mode_ad = False\n max_delta_energy = 1000.0\n fixed_num_steps = None\n if algo not in {\"HMC\", \"NUTS\"}:\n raise ValueError(\"`algo` must be one of `HMC` or `NUTS`.\")\n\n def init_kernel(\n init_params,\n num_warmup,\n step_size=1.0,\n inverse_mass_matrix=None,\n adapt_step_size=True,\n adapt_mass_matrix=True,\n dense_mass=False,\n target_accept_prob=0.8,\n *,\n num_steps=None,\n trajectory_length=2 * math.pi,\n max_tree_depth=10,\n find_heuristic_step_size=False,\n forward_mode_differentiation=False,\n regularize_mass_matrix=True,\n model_args=(),\n model_kwargs=None,\n rng_key=None,\n ):\n \"\"\"\n Initializes the HMC sampler.\n\n :param init_params: Initial parameters to begin sampling. The type must\n be consistent with the input type to `potential_fn`.\n :param int num_warmup: Number of warmup steps; samples generated\n during warmup are discarded.\n :param float step_size: Determines the size of a single step taken by the\n verlet integrator while computing the trajectory using Hamiltonian\n dynamics. If not specified, it will be set to 1.\n :param inverse_mass_matrix: Initial value for inverse mass matrix.\n This may be adapted during warmup if adapt_mass_matrix = True.\n If no value is specified, then it is initialized to the identity matrix.\n For a potential_fn with general JAX pytree parameters, the order of entries\n of the mass matrix is the order of the flattened version of pytree parameters\n obtained with `jax.tree_flatten`, which is a bit ambiguous (see more at\n https://jax.readthedocs.io/en/latest/pytrees.html). If `model` is not None,\n here we can specify a structured block mass matrix as a dictionary, where\n keys are tuple of site names and values are the corresponding block of the\n mass matrix.\n For more information about structured mass matrix, see `dense_mass` argument.\n :type inverse_mass_matrix: numpy.ndarray or dict\n :param bool adapt_step_size: A flag to decide if we want to adapt step_size\n during warm-up phase using Dual Averaging scheme.\n :param bool adapt_mass_matrix: A flag to decide if we want to adapt mass\n matrix during warm-up phase using Welford scheme.\n :param dense_mass: This flag controls whether mass matrix is dense (i.e. full-rank) or\n diagonal (defaults to ``dense_mass=False``). To specify a structured mass matrix,\n users can provide a list of tuples of site names. Each tuple represents\n a block in the joint mass matrix. For example, assuming that the model\n has latent variables \"x\", \"y\", \"z\" (where each variable can be multi-dimensional),\n possible specifications and corresponding mass matrix structures are as follows:\n\n + dense_mass=[(\"x\", \"y\")]: use a dense mass matrix for the joint\n (x, y) and a diagonal mass matrix for z\n + dense_mass=[] (equivalent to dense_mass=False): use a diagonal mass\n matrix for the joint (x, y, z)\n + dense_mass=[(\"x\", \"y\", \"z\")] (equivalent to full_mass=True):\n use a dense mass matrix for the joint (x, y, z)\n + dense_mass=[(\"x\",), (\"y\",), (\"z\")]: use dense mass matrices for\n each of x, y, and z (i.e. block-diagonal with 3 blocks)\n\n :type dense_mass: bool or list\n :param float target_accept_prob: Target acceptance probability for step size\n adaptation using Dual Averaging. Increasing this value will lead to a smaller\n step size, hence the sampling will be slower but more robust. Defaults to 0.8.\n :param int num_steps: if different than None, fix the number of steps allowed for each iteration.\n :param float trajectory_length: Length of a MCMC trajectory for HMC. Default\n value is :math:`2\\\\pi`.\n :param int max_tree_depth: Max depth of the binary tree created during the doubling\n scheme of NUTS sampler. Defaults to 10. This argument also accepts a tuple of\n integers `(d1, d2)`, where `d1` is the max tree depth during warmup phase and\n `d2` is the max tree depth during post warmup phase.\n :param bool find_heuristic_step_size: whether to a heuristic function to adjust the\n step size at the beginning of each adaptation window. Defaults to False.\n :param bool regularize_mass_matrix: whether or not to regularize the estimated mass\n matrix for numerical stability during warmup phase. Defaults to True. This flag\n does not take effect if ``adapt_mass_matrix == False``.\n :param tuple model_args: Model arguments if `potential_fn_gen` is specified.\n :param dict model_kwargs: Model keyword arguments if `potential_fn_gen` is specified.\n :param jax.random.PRNGKey rng_key: random key to be used as the source of\n randomness.\n\n \"\"\"\n rng_key = random.PRNGKey(0) if rng_key is None else rng_key\n step_size = lax.convert_element_type(step_size, jnp.result_type(float))\n if trajectory_length is not None:\n trajectory_length = lax.convert_element_type(\n trajectory_length, jnp.result_type(float)\n )\n nonlocal wa_update, max_treedepth, vv_update, wa_steps, forward_mode_ad, fixed_num_steps\n forward_mode_ad = forward_mode_differentiation\n wa_steps = num_warmup\n max_treedepth = (\n max_tree_depth\n if isinstance(max_tree_depth, tuple)\n else (max_tree_depth, max_tree_depth)\n )\n fixed_num_steps = num_steps\n if isinstance(init_params, ParamInfo):\n z, pe, z_grad = init_params\n else:\n z, pe, z_grad = init_params, None, None\n pe_fn = potential_fn\n if potential_fn_gen:\n if pe_fn is not None:\n raise ValueError(\n \"Only one of `potential_fn` or `potential_fn_gen` must be provided.\"\n )\n else:\n kwargs = {} if model_kwargs is None else model_kwargs\n pe_fn = potential_fn_gen(*model_args, **kwargs)\n\n find_reasonable_ss = None\n if find_heuristic_step_size:\n find_reasonable_ss = partial(\n find_reasonable_step_size, pe_fn, kinetic_fn, momentum_generator\n )\n\n wa_init, wa_update = warmup_adapter(\n num_warmup,\n adapt_step_size=adapt_step_size,\n adapt_mass_matrix=adapt_mass_matrix,\n dense_mass=dense_mass,\n target_accept_prob=target_accept_prob,\n find_reasonable_step_size=find_reasonable_ss,\n regularize_mass_matrix=regularize_mass_matrix,\n )\n\n rng_key_hmc, rng_key_wa, rng_key_momentum = random.split(rng_key, 3)\n z_info = IntegratorState(z=z, potential_energy=pe, z_grad=z_grad)\n wa_state = wa_init(\n z_info, rng_key_wa, step_size, inverse_mass_matrix=inverse_mass_matrix\n )\n r = momentum_generator(z, wa_state.mass_matrix_sqrt, rng_key_momentum)\n vv_init, vv_update = velocity_verlet(pe_fn, kinetic_fn, forward_mode_ad)\n vv_state = vv_init(z, r, potential_energy=pe, z_grad=z_grad)\n energy = vv_state.potential_energy + kinetic_fn(\n wa_state.inverse_mass_matrix, vv_state.r\n )\n zero_int = jnp.array(0, dtype=jnp.result_type(int))\n hmc_state = HMCState(\n zero_int,\n vv_state.z,\n vv_state.z_grad,\n vv_state.potential_energy,\n energy,\n None,\n trajectory_length,\n zero_int,\n jnp.zeros(()),\n jnp.zeros(()),\n jnp.array(False),\n wa_state,\n rng_key_hmc,\n )\n return device_put(hmc_state)\n\n def _hmc_next(\n step_size,\n inverse_mass_matrix,\n vv_state,\n model_args,\n model_kwargs,\n rng_key,\n trajectory_length,\n ):\n if potential_fn_gen:\n nonlocal vv_update, forward_mode_ad\n pe_fn = potential_fn_gen(*model_args, **model_kwargs)\n _, vv_update = velocity_verlet(pe_fn, kinetic_fn, forward_mode_ad)\n\n if fixed_num_steps is not None:\n num_steps = fixed_num_steps\n # no need to spend too many steps if the state z has 0 size (i.e. z is empty)\n elif len(inverse_mass_matrix) == 0:\n num_steps = 1\n else:\n num_steps = _get_num_steps(step_size, trajectory_length)\n # makes sure trajectory length is constant, rather than step_size * num_steps\n step_size = trajectory_length / num_steps\n vv_state_new = fori_loop(\n 0,\n num_steps,\n lambda i, val: vv_update(step_size, inverse_mass_matrix, val),\n vv_state,\n )\n energy_old = vv_state.potential_energy + kinetic_fn(\n inverse_mass_matrix, vv_state.r\n )\n energy_new = vv_state_new.potential_energy + kinetic_fn(\n inverse_mass_matrix, vv_state_new.r\n )\n delta_energy = energy_new - energy_old\n delta_energy = jnp.where(jnp.isnan(delta_energy), jnp.inf, delta_energy)\n accept_prob = jnp.clip(jnp.exp(-delta_energy), a_max=1.0)\n diverging = delta_energy > max_delta_energy\n transition = random.bernoulli(rng_key, accept_prob)\n vv_state, energy = cond(\n transition,\n (vv_state_new, energy_new),\n identity,\n (vv_state, energy_old),\n identity,\n )\n return vv_state, energy, num_steps, accept_prob, diverging\n\n def _nuts_next(\n step_size,\n inverse_mass_matrix,\n vv_state,\n model_args,\n model_kwargs,\n rng_key,\n max_treedepth_current,\n ):\n if potential_fn_gen:\n nonlocal vv_update, forward_mode_ad\n pe_fn = potential_fn_gen(*model_args, **model_kwargs)\n _, vv_update = velocity_verlet(pe_fn, kinetic_fn, forward_mode_ad)\n\n binary_tree = build_tree(\n vv_update,\n kinetic_fn,\n vv_state,\n inverse_mass_matrix,\n step_size,\n rng_key,\n max_delta_energy=max_delta_energy,\n max_tree_depth=(max_treedepth_current, max(max_treedepth)),\n )\n accept_prob = binary_tree.sum_accept_probs / binary_tree.num_proposals\n num_steps = binary_tree.num_proposals\n vv_state = IntegratorState(\n z=binary_tree.z_proposal,\n r=vv_state.r,\n potential_energy=binary_tree.z_proposal_pe,\n z_grad=binary_tree.z_proposal_grad,\n )\n return (\n vv_state,\n binary_tree.z_proposal_energy,\n num_steps,\n accept_prob,\n binary_tree.diverging,\n )\n\n _next = _nuts_next if algo == \"NUTS\" else _hmc_next\n\n def sample_kernel(hmc_state, model_args=(), model_kwargs=None):\n \"\"\"\n Given an existing :data:`~numpyro.infer.mcmc.HMCState`, run HMC with fixed (possibly adapted)\n step size and return a new :data:`~numpyro.infer.mcmc.HMCState`.\n\n :param hmc_state: Current sample (and associated state).\n :param tuple model_args: Model arguments if `potential_fn_gen` is specified.\n :param dict model_kwargs: Model keyword arguments if `potential_fn_gen` is specified.\n :return: new proposed :data:`~numpyro.infer.mcmc.HMCState` from simulating\n Hamiltonian dynamics given existing state.\n\n \"\"\"\n model_kwargs = {} if model_kwargs is None else model_kwargs\n rng_key, rng_key_momentum, rng_key_transition = random.split(\n hmc_state.rng_key, 3\n )\n r = (\n momentum_generator(\n hmc_state.z, hmc_state.adapt_state.mass_matrix_sqrt, rng_key_momentum\n )\n if hmc_state.r is None\n else hmc_state.r\n )\n vv_state = IntegratorState(\n hmc_state.z, r, hmc_state.potential_energy, hmc_state.z_grad\n )\n if algo == \"HMC\":\n hmc_length_args = (hmc_state.trajectory_length,)\n else:\n hmc_length_args = (\n jnp.where(hmc_state.i < wa_steps, max_treedepth[0], max_treedepth[1]),\n )\n vv_state, energy, num_steps, accept_prob, diverging = _next(\n hmc_state.adapt_state.step_size,\n hmc_state.adapt_state.inverse_mass_matrix,\n vv_state,\n model_args,\n model_kwargs,\n rng_key_transition,\n *hmc_length_args,\n )\n # not update adapt_state after warmup phase\n adapt_state = cond(\n hmc_state.i < wa_steps,\n (hmc_state.i, accept_prob, vv_state, hmc_state.adapt_state),\n lambda args: wa_update(*args),\n hmc_state.adapt_state,\n identity,\n )\n\n itr = hmc_state.i + 1\n n = jnp.where(hmc_state.i < wa_steps, itr, itr - wa_steps)\n mean_accept_prob = (\n hmc_state.mean_accept_prob + (accept_prob - hmc_state.mean_accept_prob) / n\n )\n\n r = vv_state.r if hmc_state.r is not None else None\n return HMCState(\n itr,\n vv_state.z,\n vv_state.z_grad,\n vv_state.potential_energy,\n energy,\n r,\n hmc_state.trajectory_length,\n num_steps,\n accept_prob,\n mean_accept_prob,\n diverging,\n adapt_state,\n rng_key,\n )\n\n # Make `init_kernel` and `sample_kernel` visible from the global scope once\n # `hmc` is called for sphinx doc generation.\n if \"SPHINX_BUILD\" in os.environ:\n hmc.init_kernel = init_kernel\n hmc.sample_kernel = sample_kernel\n\n return init_kernel, sample_kernel\n\n\nclass HMC(MCMCKernel):\n \"\"\"\n Hamiltonian Monte Carlo inference, using fixed trajectory length, with\n provision for step size and mass matrix adaptation.\n\n .. note:: Until the kernel is used in an MCMC run, `postprocess_fn` will return the\n identity function.\n\n .. note:: The default init strategy ``init_to_uniform`` might not be a good strategy\n for some models. You might want to try other init strategies like ``init_to_median``.\n\n **References:**\n\n 1. *MCMC Using Hamiltonian Dynamics*,\n Radford M. Neal\n\n :param model: Python callable containing Pyro :mod:`~numpyro.primitives`.\n If model is provided, `potential_fn` will be inferred using the model.\n :param potential_fn: Python callable that computes the potential energy\n given input parameters. The input parameters to `potential_fn` can be\n any python collection type, provided that `init_params` argument to\n :meth:`init` has the same type.\n :param kinetic_fn: Python callable that returns the kinetic energy given\n inverse mass matrix and momentum. If not provided, the default is\n euclidean kinetic energy.\n :param float step_size: Determines the size of a single step taken by the\n verlet integrator while computing the trajectory using Hamiltonian\n dynamics. If not specified, it will be set to 1.\n :param inverse_mass_matrix: Initial value for inverse mass matrix.\n This may be adapted during warmup if adapt_mass_matrix = True.\n If no value is specified, then it is initialized to the identity matrix.\n For a potential_fn with general JAX pytree parameters, the order of entries\n of the mass matrix is the order of the flattened version of pytree parameters\n obtained with `jax.tree_flatten`, which is a bit ambiguous (see more at\n https://jax.readthedocs.io/en/latest/pytrees.html). If `model` is not None,\n here we can specify a structured block mass matrix as a dictionary, where\n keys are tuple of site names and values are the corresponding block of the\n mass matrix.\n For more information about structured mass matrix, see `dense_mass` argument.\n :type inverse_mass_matrix: numpy.ndarray or dict\n :param bool adapt_step_size: A flag to decide if we want to adapt step_size\n during warm-up phase using Dual Averaging scheme.\n :param bool adapt_mass_matrix: A flag to decide if we want to adapt mass\n matrix during warm-up phase using Welford scheme.\n :param dense_mass: This flag controls whether mass matrix is dense (i.e. full-rank) or\n diagonal (defaults to ``dense_mass=False``). To specify a structured mass matrix,\n users can provide a list of tuples of site names. Each tuple represents\n a block in the joint mass matrix. For example, assuming that the model\n has latent variables \"x\", \"y\", \"z\" (where each variable can be multi-dimensional),\n possible specifications and corresponding mass matrix structures are as follows:\n\n + dense_mass=[(\"x\", \"y\")]: use a dense mass matrix for the joint\n (x, y) and a diagonal mass matrix for z\n + dense_mass=[] (equivalent to dense_mass=False): use a diagonal mass\n matrix for the joint (x, y, z)\n + dense_mass=[(\"x\", \"y\", \"z\")] (equivalent to full_mass=True):\n use a dense mass matrix for the joint (x, y, z)\n + dense_mass=[(\"x\",), (\"y\",), (\"z\")]: use dense mass matrices for\n each of x, y, and z (i.e. block-diagonal with 3 blocks)\n\n :type dense_mass: bool or list\n :param float target_accept_prob: Target acceptance probability for step size\n adaptation using Dual Averaging. Increasing this value will lead to a smaller\n step size, hence the sampling will be slower but more robust. Defaults to 0.8.\n :param int num_steps: if different than None, fix the number of steps allowed for each iteration.\n :param float trajectory_length: Length of a MCMC trajectory for HMC. Default\n value is :math:`2\\\\pi`.\n :param callable init_strategy: a per-site initialization function.\n See :ref:`init_strategy` section for available functions.\n :param bool find_heuristic_step_size: whether or not to use a heuristic function\n to adjust the step size at the beginning of each adaptation window. Defaults\n to False.\n :param bool forward_mode_differentiation: whether to use forward-mode differentiation\n or reverse-mode differentiation. By default, we use reverse mode but the forward\n mode can be useful in some cases to improve the performance. In addition, some\n control flow utility on JAX such as `jax.lax.while_loop` or `jax.lax.fori_loop`\n only supports forward-mode differentiation. See\n `JAX's The Autodiff Cookbook <https://jax.readthedocs.io/en/latest/notebooks/autodiff_cookbook.html>`_\n for more information.\n :param bool regularize_mass_matrix: whether or not to regularize the estimated mass\n matrix for numerical stability during warmup phase. Defaults to True. This flag\n does not take effect if ``adapt_mass_matrix == False``.\n \"\"\"\n\n def __init__(\n self,\n model=None,\n potential_fn=None,\n kinetic_fn=None,\n step_size=1.0,\n inverse_mass_matrix=None,\n adapt_step_size=True,\n adapt_mass_matrix=True,\n dense_mass=False,\n target_accept_prob=0.8,\n num_steps=None,\n trajectory_length=2 * math.pi,\n init_strategy=init_to_uniform,\n find_heuristic_step_size=False,\n forward_mode_differentiation=False,\n regularize_mass_matrix=True,\n ):\n if not (model is None) ^ (potential_fn is None):\n raise ValueError(\"Only one of `model` or `potential_fn` must be specified.\")\n self._model = model\n self._potential_fn = potential_fn\n self._kinetic_fn = (\n kinetic_fn if kinetic_fn is not None else euclidean_kinetic_energy\n )\n self._num_steps = num_steps\n self._step_size = float(step_size) if isinstance(step_size, int) else step_size\n self._inverse_mass_matrix = inverse_mass_matrix\n self._adapt_step_size = adapt_step_size\n self._adapt_mass_matrix = adapt_mass_matrix\n self._dense_mass = dense_mass\n self._target_accept_prob = target_accept_prob\n self._trajectory_length = (\n float(trajectory_length)\n if isinstance(trajectory_length, int)\n else trajectory_length\n )\n self._algo = \"HMC\"\n self._max_tree_depth = 10\n self._init_strategy = init_strategy\n self._find_heuristic_step_size = find_heuristic_step_size\n self._forward_mode_differentiation = forward_mode_differentiation\n self._regularize_mass_matrix = regularize_mass_matrix\n # Set on first call to init\n self._init_fn = None\n self._potential_fn_gen = None\n self._postprocess_fn = None\n self._sample_fn = None\n\n def _init_state(self, rng_key, model_args, model_kwargs, init_params):\n if self._model is not None:\n init_params, potential_fn, postprocess_fn, model_trace = initialize_model(\n rng_key,\n self._model,\n dynamic_args=True,\n init_strategy=self._init_strategy,\n model_args=model_args,\n model_kwargs=model_kwargs,\n forward_mode_differentiation=self._forward_mode_differentiation,\n )\n if self._init_fn is None:\n self._init_fn, self._sample_fn = hmc(\n potential_fn_gen=potential_fn,\n kinetic_fn=self._kinetic_fn,\n algo=self._algo,\n )\n self._potential_fn_gen = potential_fn\n self._postprocess_fn = postprocess_fn\n elif self._init_fn is None:\n self._init_fn, self._sample_fn = hmc(\n potential_fn=self._potential_fn,\n kinetic_fn=self._kinetic_fn,\n algo=self._algo,\n )\n\n return init_params\n\n @property\n def model(self):\n return self._model\n\n @property\n def sample_field(self):\n return \"z\"\n\n @property\n def default_fields(self):\n return (\"z\", \"diverging\")\n\n def get_diagnostics_str(self, state):\n return \"{} steps of size {:.2e}. acc. prob={:.2f}\".format(\n state.num_steps, state.adapt_state.step_size, state.mean_accept_prob\n )\n\n def init(\n self, rng_key, num_warmup, init_params=None, model_args=(), model_kwargs={}\n ):\n # non-vectorized\n if rng_key.ndim == 1:\n rng_key, rng_key_init_model = random.split(rng_key)\n # vectorized\n else:\n rng_key, rng_key_init_model = jnp.swapaxes(\n vmap(random.split)(rng_key), 0, 1\n )\n init_params = self._init_state(\n rng_key_init_model, model_args, model_kwargs, init_params\n )\n if self._potential_fn and init_params is None:\n raise ValueError(\n \"Valid value of `init_params` must be provided with\" \" `potential_fn`.\"\n )\n\n # change dense_mass to a structural form\n dense_mass = self._dense_mass\n inverse_mass_matrix = self._inverse_mass_matrix\n if self._model is not None:\n z = init_params[0] if isinstance(init_params, ParamInfo) else init_params\n if isinstance(dense_mass, bool):\n # XXX: by default, the order variables are sorted by their names,\n # this is to be compatible with older numpyro versions\n # and to match autoguide scale parameter and jax flatten utils\n dense_mass = [tuple(sorted(z))] if dense_mass else []\n assert isinstance(dense_mass, list)\n\n hmc_init_fn = lambda init_params, rng_key: self._init_fn( # noqa: E731\n init_params,\n num_warmup=num_warmup,\n step_size=self._step_size,\n num_steps=self._num_steps,\n inverse_mass_matrix=inverse_mass_matrix,\n adapt_step_size=self._adapt_step_size,\n adapt_mass_matrix=self._adapt_mass_matrix,\n dense_mass=dense_mass,\n target_accept_prob=self._target_accept_prob,\n trajectory_length=self._trajectory_length,\n max_tree_depth=self._max_tree_depth,\n find_heuristic_step_size=self._find_heuristic_step_size,\n forward_mode_differentiation=self._forward_mode_differentiation,\n regularize_mass_matrix=self._regularize_mass_matrix,\n model_args=model_args,\n model_kwargs=model_kwargs,\n rng_key=rng_key,\n )\n if rng_key.ndim == 1:\n init_state = hmc_init_fn(init_params, rng_key)\n else:\n # XXX it is safe to run hmc_init_fn under vmap despite that hmc_init_fn changes some\n # nonlocal variables: momentum_generator, wa_update, trajectory_len, max_treedepth,\n # wa_steps because those variables do not depend on traced args: init_params, rng_key.\n init_state = vmap(hmc_init_fn)(init_params, rng_key)\n sample_fn = vmap(self._sample_fn, in_axes=(0, None, None))\n self._sample_fn = sample_fn\n return init_state\n\n def postprocess_fn(self, args, kwargs):\n if self._postprocess_fn is None:\n return identity\n return self._postprocess_fn(*args, **kwargs)\n\n def sample(self, state, model_args, model_kwargs):\n \"\"\"\n Run HMC from the given :data:`~numpyro.infer.hmc.HMCState` and return the resulting\n :data:`~numpyro.infer.hmc.HMCState`.\n\n :param HMCState state: Represents the current state.\n :param model_args: Arguments provided to the model.\n :param model_kwargs: Keyword arguments provided to the model.\n :return: Next `state` after running HMC.\n \"\"\"\n return self._sample_fn(state, model_args, model_kwargs)\n\n def __getstate__(self):\n state = self.__dict__.copy()\n state[\"_sample_fn\"] = None\n state[\"_init_fn\"] = None\n return state\n\n\nclass NUTS(HMC):\n \"\"\"\n Hamiltonian Monte Carlo inference, using the No U-Turn Sampler (NUTS)\n with adaptive path length and mass matrix adaptation.\n\n .. note:: Until the kernel is used in an MCMC run, `postprocess_fn` will return the\n identity function.\n\n .. note:: The default init strategy ``init_to_uniform`` might not be a good strategy\n for some models. You might want to try other init strategies like ``init_to_median``.\n\n **References:**\n\n 1. *MCMC Using Hamiltonian Dynamics*,\n Radford M. Neal\n 2. *The No-U-turn sampler: adaptively setting path lengths in Hamiltonian Monte Carlo*,\n Matthew D. Hoffman, and Andrew Gelman.\n 3. *A Conceptual Introduction to Hamiltonian Monte Carlo`*,\n Michael Betancourt\n\n :param model: Python callable containing Pyro :mod:`~numpyro.primitives`.\n If model is provided, `potential_fn` will be inferred using the model.\n :param potential_fn: Python callable that computes the potential energy\n given input parameters. The input parameters to `potential_fn` can be\n any python collection type, provided that `init_params` argument to\n `init_kernel` has the same type.\n :param kinetic_fn: Python callable that returns the kinetic energy given\n inverse mass matrix and momentum. If not provided, the default is\n euclidean kinetic energy.\n :param float step_size: Determines the size of a single step taken by the\n verlet integrator while computing the trajectory using Hamiltonian\n dynamics. If not specified, it will be set to 1.\n :param inverse_mass_matrix: Initial value for inverse mass matrix.\n This may be adapted during warmup if adapt_mass_matrix = True.\n If no value is specified, then it is initialized to the identity matrix.\n For a potential_fn with general JAX pytree parameters, the order of entries\n of the mass matrix is the order of the flattened version of pytree parameters\n obtained with `jax.tree_flatten`, which is a bit ambiguous (see more at\n https://jax.readthedocs.io/en/latest/pytrees.html). If `model` is not None,\n here we can specify a structured block mass matrix as a dictionary, where\n keys are tuple of site names and values are the corresponding block of the\n mass matrix.\n For more information about structured mass matrix, see `dense_mass` argument.\n :type inverse_mass_matrix: numpy.ndarray or dict\n :param bool adapt_step_size: A flag to decide if we want to adapt step_size\n during warm-up phase using Dual Averaging scheme.\n :param bool adapt_mass_matrix: A flag to decide if we want to adapt mass\n matrix during warm-up phase using Welford scheme.\n :param dense_mass: This flag controls whether mass matrix is dense (i.e. full-rank) or\n diagonal (defaults to ``dense_mass=False``). To specify a structured mass matrix,\n users can provide a list of tuples of site names. Each tuple represents\n a block in the joint mass matrix. For example, assuming that the model\n has latent variables \"x\", \"y\", \"z\" (where each variable can be multi-dimensional),\n possible specifications and corresponding mass matrix structures are as follows:\n\n + dense_mass=[(\"x\", \"y\")]: use a dense mass matrix for the joint\n (x, y) and a diagonal mass matrix for z\n + dense_mass=[] (equivalent to dense_mass=False): use a diagonal mass\n matrix for the joint (x, y, z)\n + dense_mass=[(\"x\", \"y\", \"z\")] (equivalent to full_mass=True):\n use a dense mass matrix for the joint (x, y, z)\n + dense_mass=[(\"x\",), (\"y\",), (\"z\")]: use dense mass matrices for\n each of x, y, and z (i.e. block-diagonal with 3 blocks)\n\n :type dense_mass: bool or list\n :param float target_accept_prob: Target acceptance probability for step size\n adaptation using Dual Averaging. Increasing this value will lead to a smaller\n step size, hence the sampling will be slower but more robust. Defaults to 0.8.\n :param float trajectory_length: Length of a MCMC trajectory for HMC. This arg has\n no effect in NUTS sampler.\n :param int max_tree_depth: Max depth of the binary tree created during the doubling\n scheme of NUTS sampler. Defaults to 10. This argument also accepts a tuple of\n integers `(d1, d2)`, where `d1` is the max tree depth during warmup phase and\n `d2` is the max tree depth during post warmup phase.\n :param callable init_strategy: a per-site initialization function.\n See :ref:`init_strategy` section for available functions.\n :param bool find_heuristic_step_size: whether or not to use a heuristic function\n to adjust the step size at the beginning of each adaptation window. Defaults\n to False.\n :param bool forward_mode_differentiation: whether to use forward-mode differentiation\n or reverse-mode differentiation. By default, we use reverse mode but the forward\n mode can be useful in some cases to improve the performance. In addition, some\n control flow utility on JAX such as `jax.lax.while_loop` or `jax.lax.fori_loop`\n only supports forward-mode differentiation. See\n `JAX's The Autodiff Cookbook <https://jax.readthedocs.io/en/latest/notebooks/autodiff_cookbook.html>`_\n for more information.\n \"\"\"\n\n def __init__(\n self,\n model=None,\n potential_fn=None,\n kinetic_fn=None,\n step_size=1.0,\n inverse_mass_matrix=None,\n adapt_step_size=True,\n adapt_mass_matrix=True,\n dense_mass=False,\n target_accept_prob=0.8,\n trajectory_length=None,\n max_tree_depth=10,\n init_strategy=init_to_uniform,\n find_heuristic_step_size=False,\n forward_mode_differentiation=False,\n regularize_mass_matrix=True,\n ):\n super(NUTS, self).__init__(\n potential_fn=potential_fn,\n model=model,\n kinetic_fn=kinetic_fn,\n step_size=step_size,\n inverse_mass_matrix=inverse_mass_matrix,\n adapt_step_size=adapt_step_size,\n adapt_mass_matrix=adapt_mass_matrix,\n dense_mass=dense_mass,\n target_accept_prob=target_accept_prob,\n trajectory_length=trajectory_length,\n init_strategy=init_strategy,\n find_heuristic_step_size=find_heuristic_step_size,\n forward_mode_differentiation=forward_mode_differentiation,\n regularize_mass_matrix=regularize_mass_matrix,\n )\n self._max_tree_depth = max_tree_depth\n self._algo = \"NUTS\"\n", "path": "numpyro/infer/hmc.py" }, { "content": "# Copyright Contributors to the Pyro project.\n# SPDX-License-Identifier: Apache-2.0\n\nfrom abc import ABC, abstractmethod\nfrom functools import partial\nfrom operator import attrgetter\nimport os\nimport warnings\n\nimport numpy as np\n\nfrom jax import jit, lax, local_device_count, pmap, random, vmap\nimport jax.numpy as jnp\nfrom jax.tree_util import tree_flatten, tree_map\n\nfrom numpyro.diagnostics import print_summary\nfrom numpyro.util import cached_by, find_stack_level, fori_collect, identity\n\n__all__ = [\n \"MCMCKernel\",\n \"MCMC\",\n]\n\n\nclass MCMCKernel(ABC):\n \"\"\"\n Defines the interface for the Markov transition kernel that is\n used for :class:`~numpyro.infer.mcmc.MCMC` inference.\n\n **Example:**\n\n .. doctest::\n\n >>> from collections import namedtuple\n >>> from jax import random\n >>> import jax.numpy as jnp\n >>> import numpyro\n >>> import numpyro.distributions as dist\n >>> from numpyro.infer import MCMC\n\n >>> MHState = namedtuple(\"MHState\", [\"u\", \"rng_key\"])\n\n >>> class MetropolisHastings(numpyro.infer.mcmc.MCMCKernel):\n ... sample_field = \"u\"\n ...\n ... def __init__(self, potential_fn, step_size=0.1):\n ... self.potential_fn = potential_fn\n ... self.step_size = step_size\n ...\n ... def init(self, rng_key, num_warmup, init_params, model_args, model_kwargs):\n ... return MHState(init_params, rng_key)\n ...\n ... def sample(self, state, model_args, model_kwargs):\n ... u, rng_key = state\n ... rng_key, key_proposal, key_accept = random.split(rng_key, 3)\n ... u_proposal = dist.Normal(u, self.step_size).sample(key_proposal)\n ... accept_prob = jnp.exp(self.potential_fn(u) - self.potential_fn(u_proposal))\n ... u_new = jnp.where(dist.Uniform().sample(key_accept) < accept_prob, u_proposal, u)\n ... return MHState(u_new, rng_key)\n\n >>> def f(x):\n ... return ((x - 2) ** 2).sum()\n\n >>> kernel = MetropolisHastings(f)\n >>> mcmc = MCMC(kernel, num_warmup=1000, num_samples=1000)\n >>> mcmc.run(random.PRNGKey(0), init_params=jnp.array([1., 2.]))\n >>> posterior_samples = mcmc.get_samples()\n >>> mcmc.print_summary() # doctest: +SKIP\n \"\"\"\n\n def postprocess_fn(self, model_args, model_kwargs):\n \"\"\"\n Get a function that transforms unconstrained values at sample sites to values\n constrained to the site's support, in addition to returning deterministic\n sites in the model.\n\n :param model_args: Arguments to the model.\n :param model_kwargs: Keyword arguments to the model.\n \"\"\"\n return identity\n\n @abstractmethod\n def init(self, rng_key, num_warmup, init_params, model_args, model_kwargs):\n \"\"\"\n Initialize the `MCMCKernel` and return an initial state to begin sampling\n from.\n\n :param random.PRNGKey rng_key: Random number generator key to initialize\n the kernel.\n :param int num_warmup: Number of warmup steps. This can be useful\n when doing adaptation during warmup.\n :param tuple init_params: Initial parameters to begin sampling. The type must\n be consistent with the input type to `potential_fn`.\n :param model_args: Arguments provided to the model.\n :param model_kwargs: Keyword arguments provided to the model.\n :return: The initial state representing the state of the kernel. This can be\n any class that is registered as a\n `pytree <https://jax.readthedocs.io/en/latest/pytrees.html>`_.\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def sample(self, state, model_args, model_kwargs):\n \"\"\"\n Given the current `state`, return the next `state` using the given\n transition kernel.\n\n :param state: A `pytree <https://jax.readthedocs.io/en/latest/pytrees.html>`_\n class representing the state for the kernel. For HMC, this is given\n by :data:`~numpyro.infer.hmc.HMCState`. In general, this could be any\n class that supports `getattr`.\n :param model_args: Arguments provided to the model.\n :param model_kwargs: Keyword arguments provided to the model.\n :return: Next `state`.\n \"\"\"\n raise NotImplementedError\n\n @property\n def sample_field(self):\n \"\"\"\n The attribute of the `state` object passed to :meth:`sample` that denotes\n the MCMC sample. This is used by :meth:`postprocess_fn` and for reporting\n results in :meth:`MCMC.print_summary()\n <numpyro.infer.mcmc.MCMC.print_summary>`.\n \"\"\"\n raise NotImplementedError\n\n @property\n def default_fields(self):\n \"\"\"\n The attributes of the `state` object to be collected by default during\n the MCMC run (when :meth:`MCMC.run() <numpyro.infer.MCMC.run>` is called).\n \"\"\"\n return (self.sample_field,)\n\n def get_diagnostics_str(self, state):\n \"\"\"\n Given the current `state`, returns the diagnostics string to\n be added to progress bar for diagnostics purpose.\n \"\"\"\n return \"\"\n\n\ndef _get_progbar_desc_str(num_warmup, phase, i):\n if phase is not None:\n return phase\n return \"warmup\" if i < num_warmup else \"sample\"\n\n\ndef _get_value_from_index(xs, i):\n return tree_map(lambda x: x[i], xs)\n\n\ndef _laxmap(f, xs):\n n = tree_flatten(xs)[0][0].shape[0]\n\n ys = []\n for i in range(n):\n x = jit(_get_value_from_index)(xs, i)\n ys.append(f(x))\n\n return tree_map(lambda *args: jnp.stack(args), *ys)\n\n\ndef _sample_fn_jit_args(state, sampler):\n hmc_state, args, kwargs = state\n return sampler.sample(hmc_state, args, kwargs), args, kwargs\n\n\ndef _sample_fn_nojit_args(state, sampler, args, kwargs):\n # state is a tuple of size 1 - containing HMCState\n return (sampler.sample(state[0], args, kwargs),)\n\n\ndef _collect_fn(collect_fields):\n @cached_by(_collect_fn, collect_fields)\n def collect(x):\n if collect_fields:\n return attrgetter(*collect_fields)(x[0])\n else:\n return x[0]\n\n return collect\n\n\n# XXX: Is there a better hash key that we can use?\ndef _hashable(x):\n # NOTE: When the arguments are JITed, ShapedArray is hashable.\n if isinstance(x, (np.ndarray, jnp.ndarray)):\n return id(x)\n return x\n\n\nclass MCMC(object):\n \"\"\"\n Provides access to Markov Chain Monte Carlo inference algorithms in NumPyro.\n\n .. note:: `chain_method` is an experimental arg, which might be removed in a future version.\n\n .. note:: Setting `progress_bar=False` will improve the speed for many cases. But it might\n require more memory than the other option.\n\n .. note:: If setting `num_chains` greater than `1` in a Jupyter Notebook, then you will need to\n have installed `ipywidgets <https://ipywidgets.readthedocs.io/en/latest/user_install.html>`_\n in the environment from which you launced Jupyter in order for the progress bars to render\n correctly. If you are using Jupyter Notebook or Jupyter Lab, please also install the\n corresponding extension package like `widgetsnbextension` or `jupyterlab_widgets`.\n\n :param MCMCKernel sampler: an instance of :class:`~numpyro.infer.mcmc.MCMCKernel` that\n determines the sampler for running MCMC. Currently, only :class:`~numpyro.infer.hmc.HMC`\n and :class:`~numpyro.infer.hmc.NUTS` are available.\n :param int num_warmup: Number of warmup steps.\n :param int num_samples: Number of samples to generate from the Markov chain.\n :param int thinning: Positive integer that controls the fraction of post-warmup samples that are\n retained. For example if thinning is 2 then every other sample is retained.\n Defaults to 1, i.e. no thinning.\n :param int num_chains: Number of MCMC chains to run. By default, chains will be\n run in parallel using :func:`jax.pmap`. If there are not enough devices\n available, chains will be run in sequence.\n :param postprocess_fn: Post-processing callable - used to convert a collection of unconstrained\n sample values returned from the sampler to constrained values that lie within the support\n of the sample sites. Additionally, this is used to return values at deterministic sites in\n the model.\n :param str chain_method: One of 'parallel' (default), 'sequential', 'vectorized'. The method\n 'parallel' is used to execute the drawing process in parallel on XLA devices (CPUs/GPUs/TPUs),\n If there are not enough devices for 'parallel', we fall back to 'sequential' method to draw\n chains sequentially. 'vectorized' method is an experimental feature which vectorizes the\n drawing method, hence allowing us to collect samples in parallel on a single device.\n :param bool progress_bar: Whether to enable progress bar updates. Defaults to\n ``True``.\n :param bool jit_model_args: If set to `True`, this will compile the potential energy\n computation as a function of model arguments. As such, calling `MCMC.run` again\n on a same sized but different dataset will not result in additional compilation cost.\n Note that currently, this does not take effect for the case ``num_chains > 1``\n and ``chain_method == 'parallel'``.\n\n .. note:: It is possible to mix parallel and vectorized sampling, i.e., run vectorized chains\n on multiple devices using explicit `pmap`. Currently, doing so requires disabling the\n progress bar. For example,\n\n .. code-block:: python\n\n def do_mcmc(rng_key, n_vectorized=8):\n nuts_kernel = NUTS(model)\n mcmc = MCMC(\n nuts_kernel,\n progress_bar=False,\n num_chains=n_vectorized,\n chain_method='vectorized'\n )\n mcmc.run(\n rng_key,\n extra_fields=(\"potential_energy\",),\n )\n return {**mcmc.get_samples(), **mcmc.get_extra_fields()}\n # Number of devices to pmap over\n n_parallel = jax.local_device_count()\n rng_keys = jax.random.split(PRNGKey(rng_seed), n_parallel)\n traces = pmap(do_mcmc)(rng_keys)\n # concatenate traces along pmap'ed axis\n trace = {k: np.concatenate(v) for k, v in traces.items()}\n \"\"\"\n\n def __init__(\n self,\n sampler,\n *,\n num_warmup,\n num_samples,\n num_chains=1,\n thinning=1,\n postprocess_fn=None,\n chain_method=\"parallel\",\n progress_bar=True,\n jit_model_args=False,\n ):\n self.sampler = sampler\n self._sample_field = sampler.sample_field\n self._default_fields = sampler.default_fields\n self.num_warmup = num_warmup\n self.num_samples = num_samples\n self.num_chains = num_chains\n if not isinstance(thinning, int) or thinning < 1:\n raise ValueError(\"thinning must be a positive integer\")\n self.thinning = thinning\n self.postprocess_fn = postprocess_fn\n if chain_method not in [\"parallel\", \"vectorized\", \"sequential\"]:\n raise ValueError(\n \"Only supporting the following methods to draw chains:\"\n ' \"sequential\", \"parallel\", or \"vectorized\"'\n )\n if chain_method == \"parallel\" and local_device_count() < self.num_chains:\n chain_method = \"sequential\"\n warnings.warn(\n \"There are not enough devices to run parallel chains: expected {} but got {}.\"\n \" Chains will be drawn sequentially. If you are running MCMC in CPU,\"\n \" consider using `numpyro.set_host_device_count({})` at the beginning\"\n \" of your program. You can double-check how many devices are available in\"\n \" your system using `jax.local_device_count()`.\".format(\n self.num_chains, local_device_count(), self.num_chains\n ),\n stacklevel=find_stack_level(),\n )\n self.chain_method = chain_method\n self.progress_bar = progress_bar\n if \"CI\" in os.environ or \"PYTEST_XDIST_WORKER\" in os.environ:\n self.progress_bar = False\n self._jit_model_args = jit_model_args\n self._states = None\n self._states_flat = None\n # HMCState returned by last run\n self._last_state = None\n # HMCState returned by last warmup\n self._warmup_state = None\n # HMCState returned by hmc.init_kernel\n self._init_state_cache = {}\n self._cache = {}\n self._collection_params = {}\n self._set_collection_params()\n\n def _get_cached_fns(self):\n if self._jit_model_args:\n args, kwargs = (None,), (None,)\n else:\n args = tree_map(lambda x: _hashable(x), self._args)\n kwargs = tree_map(\n lambda x: _hashable(x), tuple(sorted(self._kwargs.items()))\n )\n key = args + kwargs\n try:\n fns = self._cache.get(key, None)\n # If unhashable arguments are provided, proceed normally\n # without caching\n except TypeError:\n fns, key = None, None\n if fns is None:\n\n def laxmap_postprocess_fn(states, args, kwargs):\n if self.postprocess_fn is None:\n body_fn = self.sampler.postprocess_fn(args, kwargs)\n else:\n body_fn = self.postprocess_fn\n if self.chain_method == \"vectorized\" and self.num_chains > 1:\n body_fn = vmap(body_fn)\n\n return lax.map(body_fn, states)\n\n if self._jit_model_args:\n sample_fn = partial(_sample_fn_jit_args, sampler=self.sampler)\n postprocess_fn = jit(laxmap_postprocess_fn)\n else:\n sample_fn = partial(\n _sample_fn_nojit_args,\n sampler=self.sampler,\n args=self._args,\n kwargs=self._kwargs,\n )\n postprocess_fn = jit(\n partial(laxmap_postprocess_fn, args=self._args, kwargs=self._kwargs)\n )\n\n fns = sample_fn, postprocess_fn\n if key is not None:\n self._cache[key] = fns\n return fns\n\n def _get_cached_init_state(self, rng_key, args, kwargs):\n rng_key = (_hashable(rng_key),)\n args = tree_map(lambda x: _hashable(x), args)\n kwargs = tree_map(lambda x: _hashable(x), tuple(sorted(kwargs.items())))\n key = rng_key + args + kwargs\n try:\n return self._init_state_cache.get(key, None)\n # If unhashable arguments are provided, return None\n except TypeError:\n return None\n\n def _single_chain_mcmc(self, init, args, kwargs, collect_fields):\n rng_key, init_state, init_params = init\n if init_state is None:\n init_state = self.sampler.init(\n rng_key,\n self.num_warmup,\n init_params,\n model_args=args,\n model_kwargs=kwargs,\n )\n sample_fn, postprocess_fn = self._get_cached_fns()\n diagnostics = (\n lambda x: self.sampler.get_diagnostics_str(x[0])\n if rng_key.ndim == 1\n else \"\"\n ) # noqa: E731\n init_val = (init_state, args, kwargs) if self._jit_model_args else (init_state,)\n lower_idx = self._collection_params[\"lower\"]\n upper_idx = self._collection_params[\"upper\"]\n phase = self._collection_params[\"phase\"]\n collection_size = self._collection_params[\"collection_size\"]\n collection_size = (\n collection_size\n if collection_size is None\n else collection_size // self.thinning\n )\n collect_vals = fori_collect(\n lower_idx,\n upper_idx,\n sample_fn,\n init_val,\n transform=_collect_fn(collect_fields),\n progbar=self.progress_bar,\n return_last_val=True,\n thinning=self.thinning,\n collection_size=collection_size,\n progbar_desc=partial(_get_progbar_desc_str, lower_idx, phase),\n diagnostics_fn=diagnostics,\n num_chains=self.num_chains if self.chain_method == \"parallel\" else 1,\n )\n states, last_val = collect_vals\n # Get first argument of type `HMCState`\n last_state = last_val[0]\n if len(collect_fields) == 1:\n states = (states,)\n states = dict(zip(collect_fields, states))\n # Apply constraints if number of samples is non-zero\n site_values = tree_flatten(states[self._sample_field])[0]\n # XXX: lax.map still works if some arrays have 0 size\n # so we only need to filter out the case site_value.shape[0] == 0\n # (which happens when lower_idx==upper_idx)\n if len(site_values) > 0 and jnp.shape(site_values[0])[0] > 0:\n if self._jit_model_args:\n states[self._sample_field] = postprocess_fn(\n states[self._sample_field], args, kwargs\n )\n else:\n states[self._sample_field] = postprocess_fn(states[self._sample_field])\n return states, last_state\n\n def _set_collection_params(\n self, lower=None, upper=None, collection_size=None, phase=None\n ):\n self._collection_params[\"lower\"] = self.num_warmup if lower is None else lower\n self._collection_params[\"upper\"] = (\n self.num_warmup + self.num_samples if upper is None else upper\n )\n self._collection_params[\"collection_size\"] = collection_size\n self._collection_params[\"phase\"] = phase\n\n def _compile(self, rng_key, *args, extra_fields=(), init_params=None, **kwargs):\n self._set_collection_params(0, 0, self.num_samples)\n self.run(\n rng_key, *args, extra_fields=extra_fields, init_params=init_params, **kwargs\n )\n rng_key = (_hashable(rng_key),)\n args = tree_map(lambda x: _hashable(x), args)\n kwargs = tree_map(lambda x: _hashable(x), tuple(sorted(kwargs.items())))\n key = rng_key + args + kwargs\n try:\n self._init_state_cache[key] = self._last_state\n # If unhashable arguments are provided, return None\n except TypeError:\n pass\n\n @property\n def post_warmup_state(self):\n \"\"\"\n The state before the sampling phase. If this attribute is not None,\n :meth:`run` will skip the warmup phase and start with the state\n specified in this attribute.\n\n .. note:: This attribute can be used to sequentially draw MCMC samples. For example,\n\n .. code-block:: python\n\n mcmc = MCMC(NUTS(model), num_warmup=100, num_samples=100)\n mcmc.run(random.PRNGKey(0))\n first_100_samples = mcmc.get_samples()\n mcmc.post_warmup_state = mcmc.last_state\n mcmc.run(mcmc.post_warmup_state.rng_key) # or mcmc.run(random.PRNGKey(1))\n second_100_samples = mcmc.get_samples()\n \"\"\"\n return self._warmup_state\n\n @post_warmup_state.setter\n def post_warmup_state(self, state):\n self._warmup_state = state\n\n @property\n def last_state(self):\n \"\"\"\n The final MCMC state at the end of the sampling phase.\n \"\"\"\n return self._last_state\n\n def warmup(\n self,\n rng_key,\n *args,\n extra_fields=(),\n collect_warmup=False,\n init_params=None,\n **kwargs,\n ):\n \"\"\"\n Run the MCMC warmup adaptation phase. After this call, `self.warmup_state` will be set\n and the :meth:`run` method will skip the warmup adaptation phase. To run `warmup` again\n for the new data, it is required to run :meth:`warmup` again.\n\n :param random.PRNGKey rng_key: Random number generator key to be used for the sampling.\n :param args: Arguments to be provided to the :meth:`numpyro.infer.mcmc.MCMCKernel.init` method.\n These are typically the arguments needed by the `model`.\n :param extra_fields: Extra fields (aside from :meth:`~numpyro.infer.mcmc.MCMCKernel.default_fields`)\n from the state object (e.g. :data:`numpyro.infer.hmc.HMCState` for HMC) to collect during\n the MCMC run.\n :type extra_fields: tuple or list\n :param bool collect_warmup: Whether to collect samples from the warmup phase. Defaults\n to `False`.\n :param init_params: Initial parameters to begin sampling. The type must be consistent\n with the input type to `potential_fn`.\n :param kwargs: Keyword arguments to be provided to the :meth:`numpyro.infer.mcmc.MCMCKernel.init`\n method. These are typically the keyword arguments needed by the `model`.\n \"\"\"\n self._warmup_state = None\n if collect_warmup:\n self._set_collection_params(0, self.num_warmup, self.num_warmup, \"warmup\")\n else:\n self._set_collection_params(\n self.num_warmup, self.num_warmup, self.num_samples, \"warmup\"\n )\n self.run(\n rng_key, *args, extra_fields=extra_fields, init_params=init_params, **kwargs\n )\n self._warmup_state = self._last_state\n\n def run(self, rng_key, *args, extra_fields=(), init_params=None, **kwargs):\n \"\"\"\n Run the MCMC samplers and collect samples.\n\n :param random.PRNGKey rng_key: Random number generator key to be used for the sampling.\n For multi-chains, a batch of `num_chains` keys can be supplied. If `rng_key`\n does not have batch_size, it will be split in to a batch of `num_chains` keys.\n :param args: Arguments to be provided to the :meth:`numpyro.infer.mcmc.MCMCKernel.init` method.\n These are typically the arguments needed by the `model`.\n :param extra_fields: Extra fields (aside from `\"z\"`, `\"diverging\"`) from the\n state object (e.g. :data:`numpyro.infer.hmc.HMCState` for HMC) to be collected\n during the MCMC run. Note that subfields can be accessed using dots, e.g.\n `\"adapt_state.step_size\"` can be used to collect step sizes at each step.\n :type extra_fields: tuple or list of str\n :param init_params: Initial parameters to begin sampling. The type must be consistent\n with the input type to `potential_fn`.\n :param kwargs: Keyword arguments to be provided to the :meth:`numpyro.infer.mcmc.MCMCKernel.init`\n method. These are typically the keyword arguments needed by the `model`.\n\n .. note:: jax allows python code to continue even when the compiled code has not finished yet.\n This can cause troubles when trying to profile the code for speed.\n See https://jax.readthedocs.io/en/latest/async_dispatch.html and\n https://jax.readthedocs.io/en/latest/profiling.html for pointers on profiling jax programs.\n \"\"\"\n init_params = tree_map(\n lambda x: lax.convert_element_type(x, jnp.result_type(x)), init_params\n )\n self._args = args\n self._kwargs = kwargs\n init_state = self._get_cached_init_state(rng_key, args, kwargs)\n if self.num_chains > 1 and rng_key.ndim == 1:\n rng_key = random.split(rng_key, self.num_chains)\n\n if self._warmup_state is not None:\n self._set_collection_params(0, self.num_samples, self.num_samples, \"sample\")\n init_state = self._warmup_state._replace(rng_key=rng_key)\n\n if init_params is not None and self.num_chains > 1:\n prototype_init_val = tree_flatten(init_params)[0][0]\n if jnp.shape(prototype_init_val)[0] != self.num_chains:\n raise ValueError(\n \"`init_params` must have the same leading dimension\"\n \" as `num_chains`.\"\n )\n assert isinstance(extra_fields, (tuple, list))\n collect_fields = tuple(\n set(\n (self._sample_field,)\n + tuple(self._default_fields)\n + tuple(extra_fields)\n )\n )\n partial_map_fn = partial(\n self._single_chain_mcmc,\n args=args,\n kwargs=kwargs,\n collect_fields=collect_fields,\n )\n map_args = (rng_key, init_state, init_params)\n if self.num_chains == 1:\n states_flat, last_state = partial_map_fn(map_args)\n states = tree_map(lambda x: x[jnp.newaxis, ...], states_flat)\n else:\n if self.chain_method == \"sequential\":\n states, last_state = _laxmap(partial_map_fn, map_args)\n elif self.chain_method == \"parallel\":\n states, last_state = pmap(partial_map_fn)(map_args)\n else:\n assert self.chain_method == \"vectorized\"\n states, last_state = partial_map_fn(map_args)\n # swap num_samples x num_chains to num_chains x num_samples\n states = tree_map(lambda x: jnp.swapaxes(x, 0, 1), states)\n states_flat = tree_map(\n # need to calculate first dimension manually; see issue #1328\n lambda x: jnp.reshape(x, (x.shape[0] * x.shape[1],) + x.shape[2:]),\n states,\n )\n self._last_state = last_state\n self._states = states\n self._states_flat = states_flat\n self._set_collection_params()\n\n def get_samples(self, group_by_chain=False):\n \"\"\"\n Get samples from the MCMC run.\n\n :param bool group_by_chain: Whether to preserve the chain dimension. If True,\n all samples will have num_chains as the size of their leading dimension.\n :return: Samples having the same data type as `init_params`. The data type is a\n `dict` keyed on site names if a model containing Pyro primitives is used,\n but can be any :func:`jaxlib.pytree`, more generally (e.g. when defining a\n `potential_fn` for HMC that takes `list` args).\n\n **Example:**\n\n You can then pass those samples to :class:`~numpyro.infer.util.Predictive`::\n\n posterior_samples = mcmc.get_samples()\n predictive = Predictive(model, posterior_samples=posterior_samples)\n samples = predictive(rng_key1, *model_args, **model_kwargs)\n\n \"\"\"\n return (\n self._states[self._sample_field]\n if group_by_chain\n else self._states_flat[self._sample_field]\n )\n\n def get_extra_fields(self, group_by_chain=False):\n \"\"\"\n Get extra fields from the MCMC run.\n\n :param bool group_by_chain: Whether to preserve the chain dimension. If True,\n all samples will have num_chains as the size of their leading dimension.\n :return: Extra fields keyed by field names which are specified in the\n `extra_fields` keyword of :meth:`run`.\n \"\"\"\n states = self._states if group_by_chain else self._states_flat\n return {k: v for k, v in states.items() if k != self._sample_field}\n\n def print_summary(self, prob=0.9, exclude_deterministic=True):\n \"\"\"\n Print the statistics of posterior samples collected during running this MCMC instance.\n\n :param float prob: the probability mass of samples within the credible interval.\n :param bool exclude_deterministic: whether or not print out the statistics\n at deterministic sites.\n \"\"\"\n # Exclude deterministic sites by default\n sites = self._states[self._sample_field]\n if isinstance(sites, dict) and exclude_deterministic:\n state_sample_field = attrgetter(self._sample_field)(self._last_state)\n # XXX: there might be the case that state.z is not a dictionary but\n # its postprocessed value `sites` is a dictionary.\n # TODO: in general, when both `sites` and `state.z` are dictionaries,\n # they can have different key names, not necessary due to deterministic\n # behavior. We might revise this logic if needed in the future.\n if isinstance(state_sample_field, dict):\n sites = {\n k: v\n for k, v in self._states[self._sample_field].items()\n if k in state_sample_field\n }\n print_summary(sites, prob=prob)\n extra_fields = self.get_extra_fields()\n if \"diverging\" in extra_fields:\n print(\n \"Number of divergences: {}\".format(jnp.sum(extra_fields[\"diverging\"]))\n )\n\n def __getstate__(self):\n state = self.__dict__.copy()\n state[\"_cache\"] = {}\n return state\n", "path": "numpyro/infer/mcmc.py" } ]
[ { "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.numpy as jnp\n\nfrom numpyro.infer.hmc_util import (\n IntegratorState,\n build_tree,\n euclidean_kinetic_energy,\n find_reasonable_step_size,\n velocity_verlet,\n warmup_adapter,\n)\nfrom numpyro.infer.mcmc import MCMCKernel\nfrom numpyro.infer.util import ParamInfo, init_to_uniform, initialize_model\nfrom numpyro.util import cond, fori_loop, identity\n\nHMCState = namedtuple(\n \"HMCState\",\n [\n \"i\",\n \"z\",\n \"z_grad\",\n \"potential_energy\",\n \"energy\",\n \"r\",\n \"trajectory_length\",\n \"num_steps\",\n \"accept_prob\",\n \"mean_accept_prob\",\n \"diverging\",\n \"adapt_state\",\n \"rng_key\",\n ],\n)\n\"\"\"\nA :func:`~collections.namedtuple` consisting of the following fields:\n\n - **i** - iteration. This is reset to 0 after warmup.\n - **z** - Python collection representing values (unconstrained samples from\n the posterior) at latent sites.\n - **z_grad** - Gradient of potential energy w.r.t. latent sample sites.\n - **potential_energy** - Potential energy computed at the given value of ``z``.\n - **energy** - Sum of potential energy and kinetic energy of the current state.\n - **r** - The current momentum variable. If this is None, a new momentum variable\n will be drawn at the beginning of each sampling step.\n - **trajectory_length** - The amount of time to run HMC dynamics in each sampling step.\n This field is not used in NUTS.\n - **num_steps** - Number of steps in the Hamiltonian trajectory (for diagnostics).\n In NUTS sampler, the tree depth of a trajectory can be computed from this field\n with `tree_depth = np.log2(num_steps).astype(int) + 1`.\n - **accept_prob** - Acceptance probability of the proposal. Note that ``z``\n does not correspond to the proposal if it is rejected.\n - **mean_accept_prob** - Mean acceptance probability until current iteration\n during warmup adaptation or sampling (for diagnostics).\n - **diverging** - A boolean value to indicate whether the current trajectory is diverging.\n - **adapt_state** - A ``HMCAdaptState`` namedtuple which contains adaptation information\n during warmup:\n\n + **step_size** - Step size to be used by the integrator in the next iteration.\n + **inverse_mass_matrix** - The inverse mass matrix to be used for the next\n iteration.\n + **mass_matrix_sqrt** - The square root of mass matrix to be used for the next\n iteration. In case of dense mass, this is the Cholesky factorization of the\n mass matrix.\n\n - **rng_key** - random number generator seed used for the iteration.\n\"\"\"\n\n\ndef _get_num_steps(step_size, trajectory_length):\n num_steps = jnp.ceil(trajectory_length / step_size)\n # NB: casting to jnp.int64 does not take effect (returns jnp.int32 instead)\n # if jax_enable_x64 is False\n return num_steps.astype(jnp.result_type(int))\n\n\ndef momentum_generator(prototype_r, mass_matrix_sqrt, rng_key):\n if isinstance(mass_matrix_sqrt, dict):\n rng_keys = random.split(rng_key, len(mass_matrix_sqrt))\n r = {}\n for (site_names, mm_sqrt), rng_key in zip(mass_matrix_sqrt.items(), rng_keys):\n r_block = OrderedDict([(k, prototype_r[k]) for k in site_names])\n r.update(momentum_generator(r_block, mm_sqrt, rng_key))\n return r\n\n _, unpack_fn = ravel_pytree(prototype_r)\n eps = random.normal(rng_key, jnp.shape(mass_matrix_sqrt)[:1])\n if mass_matrix_sqrt.ndim == 1:\n r = jnp.multiply(mass_matrix_sqrt, eps)\n return unpack_fn(r)\n elif mass_matrix_sqrt.ndim == 2:\n r = jnp.dot(mass_matrix_sqrt, eps)\n return unpack_fn(r)\n else:\n raise ValueError(\"Mass matrix has incorrect number of dims.\")\n\n\ndef hmc(potential_fn=None, potential_fn_gen=None, kinetic_fn=None, algo=\"NUTS\"):\n r\"\"\"\n Hamiltonian Monte Carlo inference, using either fixed number of\n steps or the No U-Turn Sampler (NUTS) with adaptive path length.\n\n **References:**\n\n 1. *MCMC Using Hamiltonian Dynamics*,\n Radford M. Neal\n 2. *The No-U-turn sampler: adaptively setting path lengths in Hamiltonian Monte Carlo*,\n Matthew D. Hoffman, and Andrew Gelman.\n 3. *A Conceptual Introduction to Hamiltonian Monte Carlo`*,\n Michael Betancourt\n\n :param potential_fn: Python callable that computes the potential energy\n given input parameters. The input parameters to `potential_fn` can be\n any python collection type, provided that `init_params` argument to\n `init_kernel` has the same type.\n :param potential_fn_gen: Python callable that when provided with model\n arguments / keyword arguments returns `potential_fn`. This\n may be provided to do inference on the same model with changing data.\n If the data shape remains the same, we can compile `sample_kernel`\n once, and use the same for multiple inference runs.\n :param kinetic_fn: Python callable that returns the kinetic energy given\n inverse mass matrix and momentum. If not provided, the default is\n euclidean kinetic energy.\n :param str algo: Whether to run ``HMC`` with fixed number of steps or ``NUTS``\n with adaptive path length. Default is ``NUTS``.\n :return: a tuple of callables (`init_kernel`, `sample_kernel`), the first\n one to initialize the sampler, and the second one to generate samples\n given an existing one.\n\n .. warning::\n Instead of using this interface directly, we would highly recommend you\n to use the higher level :class:`~numpyro.infer.mcmc.MCMC` API instead.\n\n **Example**\n\n .. doctest::\n\n >>> import jax\n >>> from jax import random\n >>> import jax.numpy as jnp\n >>> import numpyro\n >>> import numpyro.distributions as dist\n >>> from numpyro.infer.hmc import hmc\n >>> from numpyro.infer.util import initialize_model\n >>> from numpyro.util import fori_collect\n\n >>> true_coefs = jnp.array([1., 2., 3.])\n >>> data = random.normal(random.PRNGKey(2), (2000, 3))\n >>> labels = dist.Bernoulli(logits=(true_coefs * data).sum(-1)).sample(random.PRNGKey(3))\n >>>\n >>> def model(data, labels):\n ... coefs = numpyro.sample('coefs', dist.Normal(jnp.zeros(3), jnp.ones(3)))\n ... intercept = numpyro.sample('intercept', dist.Normal(0., 10.))\n ... return numpyro.sample('y', dist.Bernoulli(logits=(coefs * data + intercept).sum(-1)), obs=labels)\n >>>\n >>> model_info = initialize_model(random.PRNGKey(0), model, model_args=(data, labels,))\n >>> init_kernel, sample_kernel = hmc(model_info.potential_fn, algo='NUTS')\n >>> hmc_state = init_kernel(model_info.param_info,\n ... trajectory_length=10,\n ... num_warmup=300)\n >>> samples = fori_collect(0, 500, sample_kernel, hmc_state,\n ... transform=lambda state: model_info.postprocess_fn(state.z))\n >>> print(jnp.mean(samples['coefs'], axis=0)) # doctest: +SKIP\n [0.9153987 2.0754058 2.9621222]\n \"\"\"\n if kinetic_fn is None:\n kinetic_fn = euclidean_kinetic_energy\n vv_update = None\n max_treedepth = None\n wa_update = None\n wa_steps = None\n forward_mode_ad = False\n max_delta_energy = 1000.0\n fixed_num_steps = None\n if algo not in {\"HMC\", \"NUTS\"}:\n raise ValueError(\"`algo` must be one of `HMC` or `NUTS`.\")\n\n def init_kernel(\n init_params,\n num_warmup,\n step_size=1.0,\n inverse_mass_matrix=None,\n adapt_step_size=True,\n adapt_mass_matrix=True,\n dense_mass=False,\n target_accept_prob=0.8,\n *,\n num_steps=None,\n trajectory_length=2 * math.pi,\n max_tree_depth=10,\n find_heuristic_step_size=False,\n forward_mode_differentiation=False,\n regularize_mass_matrix=True,\n model_args=(),\n model_kwargs=None,\n rng_key=None,\n ):\n \"\"\"\n Initializes the HMC sampler.\n\n :param init_params: Initial parameters to begin sampling. The type must\n be consistent with the input type to `potential_fn`.\n :param int num_warmup: Number of warmup steps; samples generated\n during warmup are discarded.\n :param float step_size: Determines the size of a single step taken by the\n verlet integrator while computing the trajectory using Hamiltonian\n dynamics. If not specified, it will be set to 1.\n :param inverse_mass_matrix: Initial value for inverse mass matrix.\n This may be adapted during warmup if adapt_mass_matrix = True.\n If no value is specified, then it is initialized to the identity matrix.\n For a potential_fn with general JAX pytree parameters, the order of entries\n of the mass matrix is the order of the flattened version of pytree parameters\n obtained with `jax.tree_flatten`, which is a bit ambiguous (see more at\n https://jax.readthedocs.io/en/latest/pytrees.html). If `model` is not None,\n here we can specify a structured block mass matrix as a dictionary, where\n keys are tuple of site names and values are the corresponding block of the\n mass matrix.\n For more information about structured mass matrix, see `dense_mass` argument.\n :type inverse_mass_matrix: numpy.ndarray or dict\n :param bool adapt_step_size: A flag to decide if we want to adapt step_size\n during warm-up phase using Dual Averaging scheme.\n :param bool adapt_mass_matrix: A flag to decide if we want to adapt mass\n matrix during warm-up phase using Welford scheme.\n :param dense_mass: This flag controls whether mass matrix is dense (i.e. full-rank) or\n diagonal (defaults to ``dense_mass=False``). To specify a structured mass matrix,\n users can provide a list of tuples of site names. Each tuple represents\n a block in the joint mass matrix. For example, assuming that the model\n has latent variables \"x\", \"y\", \"z\" (where each variable can be multi-dimensional),\n possible specifications and corresponding mass matrix structures are as follows:\n\n + dense_mass=[(\"x\", \"y\")]: use a dense mass matrix for the joint\n (x, y) and a diagonal mass matrix for z\n + dense_mass=[] (equivalent to dense_mass=False): use a diagonal mass\n matrix for the joint (x, y, z)\n + dense_mass=[(\"x\", \"y\", \"z\")] (equivalent to full_mass=True):\n use a dense mass matrix for the joint (x, y, z)\n + dense_mass=[(\"x\",), (\"y\",), (\"z\")]: use dense mass matrices for\n each of x, y, and z (i.e. block-diagonal with 3 blocks)\n\n :type dense_mass: bool or list\n :param float target_accept_prob: Target acceptance probability for step size\n adaptation using Dual Averaging. Increasing this value will lead to a smaller\n step size, hence the sampling will be slower but more robust. Defaults to 0.8.\n :param int num_steps: if different than None, fix the number of steps allowed for each iteration.\n :param float trajectory_length: Length of a MCMC trajectory for HMC. Default\n value is :math:`2\\\\pi`.\n :param int max_tree_depth: Max depth of the binary tree created during the doubling\n scheme of NUTS sampler. Defaults to 10. This argument also accepts a tuple of\n integers `(d1, d2)`, where `d1` is the max tree depth during warmup phase and\n `d2` is the max tree depth during post warmup phase.\n :param bool find_heuristic_step_size: whether to a heuristic function to adjust the\n step size at the beginning of each adaptation window. Defaults to False.\n :param bool regularize_mass_matrix: whether or not to regularize the estimated mass\n matrix for numerical stability during warmup phase. Defaults to True. This flag\n does not take effect if ``adapt_mass_matrix == False``.\n :param tuple model_args: Model arguments if `potential_fn_gen` is specified.\n :param dict model_kwargs: Model keyword arguments if `potential_fn_gen` is specified.\n :param jax.random.PRNGKey rng_key: random key to be used as the source of\n randomness.\n\n \"\"\"\n rng_key = random.PRNGKey(0) if rng_key is None else rng_key\n step_size = lax.convert_element_type(step_size, jnp.result_type(float))\n if trajectory_length is not None:\n trajectory_length = lax.convert_element_type(\n trajectory_length, jnp.result_type(float)\n )\n nonlocal wa_update, max_treedepth, vv_update, wa_steps, forward_mode_ad, fixed_num_steps\n forward_mode_ad = forward_mode_differentiation\n wa_steps = num_warmup\n max_treedepth = (\n max_tree_depth\n if isinstance(max_tree_depth, tuple)\n else (max_tree_depth, max_tree_depth)\n )\n fixed_num_steps = num_steps\n if isinstance(init_params, ParamInfo):\n z, pe, z_grad = init_params\n else:\n z, pe, z_grad = init_params, None, None\n pe_fn = potential_fn\n if potential_fn_gen:\n if pe_fn is not None:\n raise ValueError(\n \"Only one of `potential_fn` or `potential_fn_gen` must be provided.\"\n )\n else:\n kwargs = {} if model_kwargs is None else model_kwargs\n pe_fn = potential_fn_gen(*model_args, **kwargs)\n\n find_reasonable_ss = None\n if find_heuristic_step_size:\n find_reasonable_ss = partial(\n find_reasonable_step_size, pe_fn, kinetic_fn, momentum_generator\n )\n\n wa_init, wa_update = warmup_adapter(\n num_warmup,\n adapt_step_size=adapt_step_size,\n adapt_mass_matrix=adapt_mass_matrix,\n dense_mass=dense_mass,\n target_accept_prob=target_accept_prob,\n find_reasonable_step_size=find_reasonable_ss,\n regularize_mass_matrix=regularize_mass_matrix,\n )\n\n rng_key_hmc, rng_key_wa, rng_key_momentum = random.split(rng_key, 3)\n z_info = IntegratorState(z=z, potential_energy=pe, z_grad=z_grad)\n wa_state = wa_init(\n z_info, rng_key_wa, step_size, inverse_mass_matrix=inverse_mass_matrix\n )\n r = momentum_generator(z, wa_state.mass_matrix_sqrt, rng_key_momentum)\n vv_init, vv_update = velocity_verlet(pe_fn, kinetic_fn, forward_mode_ad)\n vv_state = vv_init(z, r, potential_energy=pe, z_grad=z_grad)\n energy = vv_state.potential_energy + kinetic_fn(\n wa_state.inverse_mass_matrix, vv_state.r\n )\n zero_int = jnp.array(0, dtype=jnp.result_type(int))\n hmc_state = HMCState(\n zero_int,\n vv_state.z,\n vv_state.z_grad,\n vv_state.potential_energy,\n energy,\n None,\n trajectory_length,\n zero_int,\n jnp.zeros(()),\n jnp.zeros(()),\n jnp.array(False),\n wa_state,\n rng_key_hmc,\n )\n return device_put(hmc_state)\n\n def _hmc_next(\n step_size,\n inverse_mass_matrix,\n vv_state,\n model_args,\n model_kwargs,\n rng_key,\n trajectory_length,\n ):\n if potential_fn_gen:\n nonlocal vv_update, forward_mode_ad\n pe_fn = potential_fn_gen(*model_args, **model_kwargs)\n _, vv_update = velocity_verlet(pe_fn, kinetic_fn, forward_mode_ad)\n\n if fixed_num_steps is not None:\n num_steps = fixed_num_steps\n # no need to spend too many steps if the state z has 0 size (i.e. z is empty)\n elif len(inverse_mass_matrix) == 0:\n num_steps = 1\n else:\n num_steps = _get_num_steps(step_size, trajectory_length)\n # makes sure trajectory length is constant, rather than step_size * num_steps\n step_size = trajectory_length / num_steps\n vv_state_new = fori_loop(\n 0,\n num_steps,\n lambda i, val: vv_update(step_size, inverse_mass_matrix, val),\n vv_state,\n )\n energy_old = vv_state.potential_energy + kinetic_fn(\n inverse_mass_matrix, vv_state.r\n )\n energy_new = vv_state_new.potential_energy + kinetic_fn(\n inverse_mass_matrix, vv_state_new.r\n )\n delta_energy = energy_new - energy_old\n delta_energy = jnp.where(jnp.isnan(delta_energy), jnp.inf, delta_energy)\n accept_prob = jnp.clip(jnp.exp(-delta_energy), a_max=1.0)\n diverging = delta_energy > max_delta_energy\n transition = random.bernoulli(rng_key, accept_prob)\n vv_state, energy = cond(\n transition,\n (vv_state_new, energy_new),\n identity,\n (vv_state, energy_old),\n identity,\n )\n return vv_state, energy, num_steps, accept_prob, diverging\n\n def _nuts_next(\n step_size,\n inverse_mass_matrix,\n vv_state,\n model_args,\n model_kwargs,\n rng_key,\n max_treedepth_current,\n ):\n if potential_fn_gen:\n nonlocal vv_update, forward_mode_ad\n pe_fn = potential_fn_gen(*model_args, **model_kwargs)\n _, vv_update = velocity_verlet(pe_fn, kinetic_fn, forward_mode_ad)\n\n binary_tree = build_tree(\n vv_update,\n kinetic_fn,\n vv_state,\n inverse_mass_matrix,\n step_size,\n rng_key,\n max_delta_energy=max_delta_energy,\n max_tree_depth=(max_treedepth_current, max(max_treedepth)),\n )\n accept_prob = binary_tree.sum_accept_probs / binary_tree.num_proposals\n num_steps = binary_tree.num_proposals\n vv_state = IntegratorState(\n z=binary_tree.z_proposal,\n r=vv_state.r,\n potential_energy=binary_tree.z_proposal_pe,\n z_grad=binary_tree.z_proposal_grad,\n )\n return (\n vv_state,\n binary_tree.z_proposal_energy,\n num_steps,\n accept_prob,\n binary_tree.diverging,\n )\n\n _next = _nuts_next if algo == \"NUTS\" else _hmc_next\n\n def sample_kernel(hmc_state, model_args=(), model_kwargs=None):\n \"\"\"\n Given an existing :data:`~numpyro.infer.mcmc.HMCState`, run HMC with fixed (possibly adapted)\n step size and return a new :data:`~numpyro.infer.mcmc.HMCState`.\n\n :param hmc_state: Current sample (and associated state).\n :param tuple model_args: Model arguments if `potential_fn_gen` is specified.\n :param dict model_kwargs: Model keyword arguments if `potential_fn_gen` is specified.\n :return: new proposed :data:`~numpyro.infer.mcmc.HMCState` from simulating\n Hamiltonian dynamics given existing state.\n\n \"\"\"\n model_kwargs = {} if model_kwargs is None else model_kwargs\n rng_key, rng_key_momentum, rng_key_transition = random.split(\n hmc_state.rng_key, 3\n )\n r = (\n momentum_generator(\n hmc_state.z, hmc_state.adapt_state.mass_matrix_sqrt, rng_key_momentum\n )\n if hmc_state.r is None\n else hmc_state.r\n )\n vv_state = IntegratorState(\n hmc_state.z, r, hmc_state.potential_energy, hmc_state.z_grad\n )\n if algo == \"HMC\":\n hmc_length_args = (hmc_state.trajectory_length,)\n else:\n hmc_length_args = (\n jnp.where(hmc_state.i < wa_steps, max_treedepth[0], max_treedepth[1]),\n )\n vv_state, energy, num_steps, accept_prob, diverging = _next(\n hmc_state.adapt_state.step_size,\n hmc_state.adapt_state.inverse_mass_matrix,\n vv_state,\n model_args,\n model_kwargs,\n rng_key_transition,\n *hmc_length_args,\n )\n # not update adapt_state after warmup phase\n adapt_state = cond(\n hmc_state.i < wa_steps,\n (hmc_state.i, accept_prob, vv_state, hmc_state.adapt_state),\n lambda args: wa_update(*args),\n hmc_state.adapt_state,\n identity,\n )\n\n itr = hmc_state.i + 1\n n = jnp.where(hmc_state.i < wa_steps, itr, itr - wa_steps)\n mean_accept_prob = (\n hmc_state.mean_accept_prob + (accept_prob - hmc_state.mean_accept_prob) / n\n )\n\n r = vv_state.r if hmc_state.r is not None else None\n return HMCState(\n itr,\n vv_state.z,\n vv_state.z_grad,\n vv_state.potential_energy,\n energy,\n r,\n hmc_state.trajectory_length,\n num_steps,\n accept_prob,\n mean_accept_prob,\n diverging,\n adapt_state,\n rng_key,\n )\n\n # Make `init_kernel` and `sample_kernel` visible from the global scope once\n # `hmc` is called for sphinx doc generation.\n if \"SPHINX_BUILD\" in os.environ:\n hmc.init_kernel = init_kernel\n hmc.sample_kernel = sample_kernel\n\n return init_kernel, sample_kernel\n\n\nclass HMC(MCMCKernel):\n \"\"\"\n Hamiltonian Monte Carlo inference, using fixed trajectory length, with\n provision for step size and mass matrix adaptation.\n\n .. note:: Until the kernel is used in an MCMC run, `postprocess_fn` will return the\n identity function.\n\n .. note:: The default init strategy ``init_to_uniform`` might not be a good strategy\n for some models. You might want to try other init strategies like ``init_to_median``.\n\n **References:**\n\n 1. *MCMC Using Hamiltonian Dynamics*,\n Radford M. Neal\n\n :param model: Python callable containing Pyro :mod:`~numpyro.primitives`.\n If model is provided, `potential_fn` will be inferred using the model.\n :param potential_fn: Python callable that computes the potential energy\n given input parameters. The input parameters to `potential_fn` can be\n any python collection type, provided that `init_params` argument to\n :meth:`init` has the same type.\n :param kinetic_fn: Python callable that returns the kinetic energy given\n inverse mass matrix and momentum. If not provided, the default is\n euclidean kinetic energy.\n :param float step_size: Determines the size of a single step taken by the\n verlet integrator while computing the trajectory using Hamiltonian\n dynamics. If not specified, it will be set to 1.\n :param inverse_mass_matrix: Initial value for inverse mass matrix.\n This may be adapted during warmup if adapt_mass_matrix = True.\n If no value is specified, then it is initialized to the identity matrix.\n For a potential_fn with general JAX pytree parameters, the order of entries\n of the mass matrix is the order of the flattened version of pytree parameters\n obtained with `jax.tree_flatten`, which is a bit ambiguous (see more at\n https://jax.readthedocs.io/en/latest/pytrees.html). If `model` is not None,\n here we can specify a structured block mass matrix as a dictionary, where\n keys are tuple of site names and values are the corresponding block of the\n mass matrix.\n For more information about structured mass matrix, see `dense_mass` argument.\n :type inverse_mass_matrix: numpy.ndarray or dict\n :param bool adapt_step_size: A flag to decide if we want to adapt step_size\n during warm-up phase using Dual Averaging scheme.\n :param bool adapt_mass_matrix: A flag to decide if we want to adapt mass\n matrix during warm-up phase using Welford scheme.\n :param dense_mass: This flag controls whether mass matrix is dense (i.e. full-rank) or\n diagonal (defaults to ``dense_mass=False``). To specify a structured mass matrix,\n users can provide a list of tuples of site names. Each tuple represents\n a block in the joint mass matrix. For example, assuming that the model\n has latent variables \"x\", \"y\", \"z\" (where each variable can be multi-dimensional),\n possible specifications and corresponding mass matrix structures are as follows:\n\n + dense_mass=[(\"x\", \"y\")]: use a dense mass matrix for the joint\n (x, y) and a diagonal mass matrix for z\n + dense_mass=[] (equivalent to dense_mass=False): use a diagonal mass\n matrix for the joint (x, y, z)\n + dense_mass=[(\"x\", \"y\", \"z\")] (equivalent to full_mass=True):\n use a dense mass matrix for the joint (x, y, z)\n + dense_mass=[(\"x\",), (\"y\",), (\"z\")]: use dense mass matrices for\n each of x, y, and z (i.e. block-diagonal with 3 blocks)\n\n :type dense_mass: bool or list\n :param float target_accept_prob: Target acceptance probability for step size\n adaptation using Dual Averaging. Increasing this value will lead to a smaller\n step size, hence the sampling will be slower but more robust. Defaults to 0.8.\n :param int num_steps: if different than None, fix the number of steps allowed for each iteration.\n :param float trajectory_length: Length of a MCMC trajectory for HMC. Default\n value is :math:`2\\\\pi`.\n :param callable init_strategy: a per-site initialization function.\n See :ref:`init_strategy` section for available functions.\n :param bool find_heuristic_step_size: whether or not to use a heuristic function\n to adjust the step size at the beginning of each adaptation window. Defaults\n to False.\n :param bool forward_mode_differentiation: whether to use forward-mode differentiation\n or reverse-mode differentiation. By default, we use reverse mode but the forward\n mode can be useful in some cases to improve the performance. In addition, some\n control flow utility on JAX such as `jax.lax.while_loop` or `jax.lax.fori_loop`\n only supports forward-mode differentiation. See\n `JAX's The Autodiff Cookbook <https://jax.readthedocs.io/en/latest/notebooks/autodiff_cookbook.html>`_\n for more information.\n :param bool regularize_mass_matrix: whether or not to regularize the estimated mass\n matrix for numerical stability during warmup phase. Defaults to True. This flag\n does not take effect if ``adapt_mass_matrix == False``.\n \"\"\"\n\n def __init__(\n self,\n model=None,\n potential_fn=None,\n kinetic_fn=None,\n step_size=1.0,\n inverse_mass_matrix=None,\n adapt_step_size=True,\n adapt_mass_matrix=True,\n dense_mass=False,\n target_accept_prob=0.8,\n num_steps=None,\n trajectory_length=2 * math.pi,\n init_strategy=init_to_uniform,\n find_heuristic_step_size=False,\n forward_mode_differentiation=False,\n regularize_mass_matrix=True,\n ):\n if not (model is None) ^ (potential_fn is None):\n raise ValueError(\"Only one of `model` or `potential_fn` must be specified.\")\n self._model = model\n self._potential_fn = potential_fn\n self._kinetic_fn = (\n kinetic_fn if kinetic_fn is not None else euclidean_kinetic_energy\n )\n self._num_steps = num_steps\n self._step_size = float(step_size) if isinstance(step_size, int) else step_size\n self._inverse_mass_matrix = inverse_mass_matrix\n self._adapt_step_size = adapt_step_size\n self._adapt_mass_matrix = adapt_mass_matrix\n self._dense_mass = dense_mass\n self._target_accept_prob = target_accept_prob\n self._trajectory_length = (\n float(trajectory_length)\n if isinstance(trajectory_length, int)\n else trajectory_length\n )\n self._algo = \"HMC\"\n self._max_tree_depth = 10\n self._init_strategy = init_strategy\n self._find_heuristic_step_size = find_heuristic_step_size\n self._forward_mode_differentiation = forward_mode_differentiation\n self._regularize_mass_matrix = regularize_mass_matrix\n # Set on first call to init\n self._init_fn = None\n self._potential_fn_gen = None\n self._postprocess_fn = None\n self._sample_fn = None\n\n def _init_state(self, rng_key, model_args, model_kwargs, init_params):\n if self._model is not None:\n (\n new_init_params,\n potential_fn,\n postprocess_fn,\n model_trace,\n ) = initialize_model(\n rng_key,\n self._model,\n dynamic_args=True,\n init_strategy=self._init_strategy,\n model_args=model_args,\n model_kwargs=model_kwargs,\n forward_mode_differentiation=self._forward_mode_differentiation,\n )\n if init_params is None:\n init_params = new_init_params\n if self._init_fn is None:\n self._init_fn, self._sample_fn = hmc(\n potential_fn_gen=potential_fn,\n kinetic_fn=self._kinetic_fn,\n algo=self._algo,\n )\n self._potential_fn_gen = potential_fn\n self._postprocess_fn = postprocess_fn\n elif self._init_fn is None:\n self._init_fn, self._sample_fn = hmc(\n potential_fn=self._potential_fn,\n kinetic_fn=self._kinetic_fn,\n algo=self._algo,\n )\n\n return init_params\n\n @property\n def model(self):\n return self._model\n\n @property\n def sample_field(self):\n return \"z\"\n\n @property\n def default_fields(self):\n return (\"z\", \"diverging\")\n\n def get_diagnostics_str(self, state):\n return \"{} steps of size {:.2e}. acc. prob={:.2f}\".format(\n state.num_steps, state.adapt_state.step_size, state.mean_accept_prob\n )\n\n def init(\n self, rng_key, num_warmup, init_params=None, model_args=(), model_kwargs={}\n ):\n # non-vectorized\n if rng_key.ndim == 1:\n rng_key, rng_key_init_model = random.split(rng_key)\n # vectorized\n else:\n rng_key, rng_key_init_model = jnp.swapaxes(\n vmap(random.split)(rng_key), 0, 1\n )\n init_params = self._init_state(\n rng_key_init_model, model_args, model_kwargs, init_params\n )\n if self._potential_fn and init_params is None:\n raise ValueError(\n \"Valid value of `init_params` must be provided with\" \" `potential_fn`.\"\n )\n\n # change dense_mass to a structural form\n dense_mass = self._dense_mass\n inverse_mass_matrix = self._inverse_mass_matrix\n if self._model is not None:\n z = init_params[0] if isinstance(init_params, ParamInfo) else init_params\n if isinstance(dense_mass, bool):\n # XXX: by default, the order variables are sorted by their names,\n # this is to be compatible with older numpyro versions\n # and to match autoguide scale parameter and jax flatten utils\n dense_mass = [tuple(sorted(z))] if dense_mass else []\n assert isinstance(dense_mass, list)\n\n hmc_init_fn = lambda init_params, rng_key: self._init_fn( # noqa: E731\n init_params,\n num_warmup=num_warmup,\n step_size=self._step_size,\n num_steps=self._num_steps,\n inverse_mass_matrix=inverse_mass_matrix,\n adapt_step_size=self._adapt_step_size,\n adapt_mass_matrix=self._adapt_mass_matrix,\n dense_mass=dense_mass,\n target_accept_prob=self._target_accept_prob,\n trajectory_length=self._trajectory_length,\n max_tree_depth=self._max_tree_depth,\n find_heuristic_step_size=self._find_heuristic_step_size,\n forward_mode_differentiation=self._forward_mode_differentiation,\n regularize_mass_matrix=self._regularize_mass_matrix,\n model_args=model_args,\n model_kwargs=model_kwargs,\n rng_key=rng_key,\n )\n if rng_key.ndim == 1:\n init_state = hmc_init_fn(init_params, rng_key)\n else:\n # XXX it is safe to run hmc_init_fn under vmap despite that hmc_init_fn changes some\n # nonlocal variables: momentum_generator, wa_update, trajectory_len, max_treedepth,\n # wa_steps because those variables do not depend on traced args: init_params, rng_key.\n init_state = vmap(hmc_init_fn)(init_params, rng_key)\n sample_fn = vmap(self._sample_fn, in_axes=(0, None, None))\n self._sample_fn = sample_fn\n return init_state\n\n def postprocess_fn(self, args, kwargs):\n if self._postprocess_fn is None:\n return identity\n return self._postprocess_fn(*args, **kwargs)\n\n def sample(self, state, model_args, model_kwargs):\n \"\"\"\n Run HMC from the given :data:`~numpyro.infer.hmc.HMCState` and return the resulting\n :data:`~numpyro.infer.hmc.HMCState`.\n\n :param HMCState state: Represents the current state.\n :param model_args: Arguments provided to the model.\n :param model_kwargs: Keyword arguments provided to the model.\n :return: Next `state` after running HMC.\n \"\"\"\n return self._sample_fn(state, model_args, model_kwargs)\n\n def __getstate__(self):\n state = self.__dict__.copy()\n state[\"_sample_fn\"] = None\n state[\"_init_fn\"] = None\n return state\n\n\nclass NUTS(HMC):\n \"\"\"\n Hamiltonian Monte Carlo inference, using the No U-Turn Sampler (NUTS)\n with adaptive path length and mass matrix adaptation.\n\n .. note:: Until the kernel is used in an MCMC run, `postprocess_fn` will return the\n identity function.\n\n .. note:: The default init strategy ``init_to_uniform`` might not be a good strategy\n for some models. You might want to try other init strategies like ``init_to_median``.\n\n **References:**\n\n 1. *MCMC Using Hamiltonian Dynamics*,\n Radford M. Neal\n 2. *The No-U-turn sampler: adaptively setting path lengths in Hamiltonian Monte Carlo*,\n Matthew D. Hoffman, and Andrew Gelman.\n 3. *A Conceptual Introduction to Hamiltonian Monte Carlo`*,\n Michael Betancourt\n\n :param model: Python callable containing Pyro :mod:`~numpyro.primitives`.\n If model is provided, `potential_fn` will be inferred using the model.\n :param potential_fn: Python callable that computes the potential energy\n given input parameters. The input parameters to `potential_fn` can be\n any python collection type, provided that `init_params` argument to\n `init_kernel` has the same type.\n :param kinetic_fn: Python callable that returns the kinetic energy given\n inverse mass matrix and momentum. If not provided, the default is\n euclidean kinetic energy.\n :param float step_size: Determines the size of a single step taken by the\n verlet integrator while computing the trajectory using Hamiltonian\n dynamics. If not specified, it will be set to 1.\n :param inverse_mass_matrix: Initial value for inverse mass matrix.\n This may be adapted during warmup if adapt_mass_matrix = True.\n If no value is specified, then it is initialized to the identity matrix.\n For a potential_fn with general JAX pytree parameters, the order of entries\n of the mass matrix is the order of the flattened version of pytree parameters\n obtained with `jax.tree_flatten`, which is a bit ambiguous (see more at\n https://jax.readthedocs.io/en/latest/pytrees.html). If `model` is not None,\n here we can specify a structured block mass matrix as a dictionary, where\n keys are tuple of site names and values are the corresponding block of the\n mass matrix.\n For more information about structured mass matrix, see `dense_mass` argument.\n :type inverse_mass_matrix: numpy.ndarray or dict\n :param bool adapt_step_size: A flag to decide if we want to adapt step_size\n during warm-up phase using Dual Averaging scheme.\n :param bool adapt_mass_matrix: A flag to decide if we want to adapt mass\n matrix during warm-up phase using Welford scheme.\n :param dense_mass: This flag controls whether mass matrix is dense (i.e. full-rank) or\n diagonal (defaults to ``dense_mass=False``). To specify a structured mass matrix,\n users can provide a list of tuples of site names. Each tuple represents\n a block in the joint mass matrix. For example, assuming that the model\n has latent variables \"x\", \"y\", \"z\" (where each variable can be multi-dimensional),\n possible specifications and corresponding mass matrix structures are as follows:\n\n + dense_mass=[(\"x\", \"y\")]: use a dense mass matrix for the joint\n (x, y) and a diagonal mass matrix for z\n + dense_mass=[] (equivalent to dense_mass=False): use a diagonal mass\n matrix for the joint (x, y, z)\n + dense_mass=[(\"x\", \"y\", \"z\")] (equivalent to full_mass=True):\n use a dense mass matrix for the joint (x, y, z)\n + dense_mass=[(\"x\",), (\"y\",), (\"z\")]: use dense mass matrices for\n each of x, y, and z (i.e. block-diagonal with 3 blocks)\n\n :type dense_mass: bool or list\n :param float target_accept_prob: Target acceptance probability for step size\n adaptation using Dual Averaging. Increasing this value will lead to a smaller\n step size, hence the sampling will be slower but more robust. Defaults to 0.8.\n :param float trajectory_length: Length of a MCMC trajectory for HMC. This arg has\n no effect in NUTS sampler.\n :param int max_tree_depth: Max depth of the binary tree created during the doubling\n scheme of NUTS sampler. Defaults to 10. This argument also accepts a tuple of\n integers `(d1, d2)`, where `d1` is the max tree depth during warmup phase and\n `d2` is the max tree depth during post warmup phase.\n :param callable init_strategy: a per-site initialization function.\n See :ref:`init_strategy` section for available functions.\n :param bool find_heuristic_step_size: whether or not to use a heuristic function\n to adjust the step size at the beginning of each adaptation window. Defaults\n to False.\n :param bool forward_mode_differentiation: whether to use forward-mode differentiation\n or reverse-mode differentiation. By default, we use reverse mode but the forward\n mode can be useful in some cases to improve the performance. In addition, some\n control flow utility on JAX such as `jax.lax.while_loop` or `jax.lax.fori_loop`\n only supports forward-mode differentiation. See\n `JAX's The Autodiff Cookbook <https://jax.readthedocs.io/en/latest/notebooks/autodiff_cookbook.html>`_\n for more information.\n \"\"\"\n\n def __init__(\n self,\n model=None,\n potential_fn=None,\n kinetic_fn=None,\n step_size=1.0,\n inverse_mass_matrix=None,\n adapt_step_size=True,\n adapt_mass_matrix=True,\n dense_mass=False,\n target_accept_prob=0.8,\n trajectory_length=None,\n max_tree_depth=10,\n init_strategy=init_to_uniform,\n find_heuristic_step_size=False,\n forward_mode_differentiation=False,\n regularize_mass_matrix=True,\n ):\n super(NUTS, self).__init__(\n potential_fn=potential_fn,\n model=model,\n kinetic_fn=kinetic_fn,\n step_size=step_size,\n inverse_mass_matrix=inverse_mass_matrix,\n adapt_step_size=adapt_step_size,\n adapt_mass_matrix=adapt_mass_matrix,\n dense_mass=dense_mass,\n target_accept_prob=target_accept_prob,\n trajectory_length=trajectory_length,\n init_strategy=init_strategy,\n find_heuristic_step_size=find_heuristic_step_size,\n forward_mode_differentiation=forward_mode_differentiation,\n regularize_mass_matrix=regularize_mass_matrix,\n )\n self._max_tree_depth = max_tree_depth\n self._algo = \"NUTS\"\n", "path": "numpyro/infer/hmc.py" }, { "content": "# Copyright Contributors to the Pyro project.\n# SPDX-License-Identifier: Apache-2.0\n\nfrom abc import ABC, abstractmethod\nfrom functools import partial\nfrom operator import attrgetter\nimport os\nimport warnings\n\nimport numpy as np\n\nfrom jax import jit, lax, local_device_count, pmap, random, vmap\nimport jax.numpy as jnp\nfrom jax.tree_util import tree_flatten, tree_map\n\nfrom numpyro.diagnostics import print_summary\nfrom numpyro.util import cached_by, find_stack_level, fori_collect, identity\n\n__all__ = [\n \"MCMCKernel\",\n \"MCMC\",\n]\n\n\nclass MCMCKernel(ABC):\n \"\"\"\n Defines the interface for the Markov transition kernel that is\n used for :class:`~numpyro.infer.mcmc.MCMC` inference.\n\n **Example:**\n\n .. doctest::\n\n >>> from collections import namedtuple\n >>> from jax import random\n >>> import jax.numpy as jnp\n >>> import numpyro\n >>> import numpyro.distributions as dist\n >>> from numpyro.infer import MCMC\n\n >>> MHState = namedtuple(\"MHState\", [\"u\", \"rng_key\"])\n\n >>> class MetropolisHastings(numpyro.infer.mcmc.MCMCKernel):\n ... sample_field = \"u\"\n ...\n ... def __init__(self, potential_fn, step_size=0.1):\n ... self.potential_fn = potential_fn\n ... self.step_size = step_size\n ...\n ... def init(self, rng_key, num_warmup, init_params, model_args, model_kwargs):\n ... return MHState(init_params, rng_key)\n ...\n ... def sample(self, state, model_args, model_kwargs):\n ... u, rng_key = state\n ... rng_key, key_proposal, key_accept = random.split(rng_key, 3)\n ... u_proposal = dist.Normal(u, self.step_size).sample(key_proposal)\n ... accept_prob = jnp.exp(self.potential_fn(u) - self.potential_fn(u_proposal))\n ... u_new = jnp.where(dist.Uniform().sample(key_accept) < accept_prob, u_proposal, u)\n ... return MHState(u_new, rng_key)\n\n >>> def f(x):\n ... return ((x - 2) ** 2).sum()\n\n >>> kernel = MetropolisHastings(f)\n >>> mcmc = MCMC(kernel, num_warmup=1000, num_samples=1000)\n >>> mcmc.run(random.PRNGKey(0), init_params=jnp.array([1., 2.]))\n >>> posterior_samples = mcmc.get_samples()\n >>> mcmc.print_summary() # doctest: +SKIP\n \"\"\"\n\n def postprocess_fn(self, model_args, model_kwargs):\n \"\"\"\n Get a function that transforms unconstrained values at sample sites to values\n constrained to the site's support, in addition to returning deterministic\n sites in the model.\n\n :param model_args: Arguments to the model.\n :param model_kwargs: Keyword arguments to the model.\n \"\"\"\n return identity\n\n @abstractmethod\n def init(self, rng_key, num_warmup, init_params, model_args, model_kwargs):\n \"\"\"\n Initialize the `MCMCKernel` and return an initial state to begin sampling\n from.\n\n :param random.PRNGKey rng_key: Random number generator key to initialize\n the kernel.\n :param int num_warmup: Number of warmup steps. This can be useful\n when doing adaptation during warmup.\n :param tuple init_params: Initial parameters to begin sampling. The type must\n be consistent with the input type to `potential_fn`.\n :param model_args: Arguments provided to the model.\n :param model_kwargs: Keyword arguments provided to the model.\n :return: The initial state representing the state of the kernel. This can be\n any class that is registered as a\n `pytree <https://jax.readthedocs.io/en/latest/pytrees.html>`_.\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def sample(self, state, model_args, model_kwargs):\n \"\"\"\n Given the current `state`, return the next `state` using the given\n transition kernel.\n\n :param state: A `pytree <https://jax.readthedocs.io/en/latest/pytrees.html>`_\n class representing the state for the kernel. For HMC, this is given\n by :data:`~numpyro.infer.hmc.HMCState`. In general, this could be any\n class that supports `getattr`.\n :param model_args: Arguments provided to the model.\n :param model_kwargs: Keyword arguments provided to the model.\n :return: Next `state`.\n \"\"\"\n raise NotImplementedError\n\n @property\n def sample_field(self):\n \"\"\"\n The attribute of the `state` object passed to :meth:`sample` that denotes\n the MCMC sample. This is used by :meth:`postprocess_fn` and for reporting\n results in :meth:`MCMC.print_summary()\n <numpyro.infer.mcmc.MCMC.print_summary>`.\n \"\"\"\n raise NotImplementedError\n\n @property\n def default_fields(self):\n \"\"\"\n The attributes of the `state` object to be collected by default during\n the MCMC run (when :meth:`MCMC.run() <numpyro.infer.MCMC.run>` is called).\n \"\"\"\n return (self.sample_field,)\n\n def get_diagnostics_str(self, state):\n \"\"\"\n Given the current `state`, returns the diagnostics string to\n be added to progress bar for diagnostics purpose.\n \"\"\"\n return \"\"\n\n\ndef _get_progbar_desc_str(num_warmup, phase, i):\n if phase is not None:\n return phase\n return \"warmup\" if i < num_warmup else \"sample\"\n\n\ndef _get_value_from_index(xs, i):\n return tree_map(lambda x: x[i], xs)\n\n\ndef _laxmap(f, xs):\n n = tree_flatten(xs)[0][0].shape[0]\n\n ys = []\n for i in range(n):\n x = jit(_get_value_from_index)(xs, i)\n ys.append(f(x))\n\n return tree_map(lambda *args: jnp.stack(args), *ys)\n\n\ndef _sample_fn_jit_args(state, sampler):\n hmc_state, args, kwargs = state\n return sampler.sample(hmc_state, args, kwargs), args, kwargs\n\n\ndef _sample_fn_nojit_args(state, sampler, args, kwargs):\n # state is a tuple of size 1 - containing HMCState\n return (sampler.sample(state[0], args, kwargs),)\n\n\ndef _collect_fn(collect_fields):\n @cached_by(_collect_fn, collect_fields)\n def collect(x):\n if collect_fields:\n return attrgetter(*collect_fields)(x[0])\n else:\n return x[0]\n\n return collect\n\n\n# XXX: Is there a better hash key that we can use?\ndef _hashable(x):\n # NOTE: When the arguments are JITed, ShapedArray is hashable.\n if isinstance(x, (np.ndarray, jnp.ndarray)):\n return id(x)\n return x\n\n\nclass MCMC(object):\n \"\"\"\n Provides access to Markov Chain Monte Carlo inference algorithms in NumPyro.\n\n .. note:: `chain_method` is an experimental arg, which might be removed in a future version.\n\n .. note:: Setting `progress_bar=False` will improve the speed for many cases. But it might\n require more memory than the other option.\n\n .. note:: If setting `num_chains` greater than `1` in a Jupyter Notebook, then you will need to\n have installed `ipywidgets <https://ipywidgets.readthedocs.io/en/latest/user_install.html>`_\n in the environment from which you launced Jupyter in order for the progress bars to render\n correctly. If you are using Jupyter Notebook or Jupyter Lab, please also install the\n corresponding extension package like `widgetsnbextension` or `jupyterlab_widgets`.\n\n :param MCMCKernel sampler: an instance of :class:`~numpyro.infer.mcmc.MCMCKernel` that\n determines the sampler for running MCMC. Currently, only :class:`~numpyro.infer.hmc.HMC`\n and :class:`~numpyro.infer.hmc.NUTS` are available.\n :param int num_warmup: Number of warmup steps.\n :param int num_samples: Number of samples to generate from the Markov chain.\n :param int thinning: Positive integer that controls the fraction of post-warmup samples that are\n retained. For example if thinning is 2 then every other sample is retained.\n Defaults to 1, i.e. no thinning.\n :param int num_chains: Number of MCMC chains to run. By default, chains will be\n run in parallel using :func:`jax.pmap`. If there are not enough devices\n available, chains will be run in sequence.\n :param postprocess_fn: Post-processing callable - used to convert a collection of unconstrained\n sample values returned from the sampler to constrained values that lie within the support\n of the sample sites. Additionally, this is used to return values at deterministic sites in\n the model.\n :param str chain_method: One of 'parallel' (default), 'sequential', 'vectorized'. The method\n 'parallel' is used to execute the drawing process in parallel on XLA devices (CPUs/GPUs/TPUs),\n If there are not enough devices for 'parallel', we fall back to 'sequential' method to draw\n chains sequentially. 'vectorized' method is an experimental feature which vectorizes the\n drawing method, hence allowing us to collect samples in parallel on a single device.\n :param bool progress_bar: Whether to enable progress bar updates. Defaults to\n ``True``.\n :param bool jit_model_args: If set to `True`, this will compile the potential energy\n computation as a function of model arguments. As such, calling `MCMC.run` again\n on a same sized but different dataset will not result in additional compilation cost.\n Note that currently, this does not take effect for the case ``num_chains > 1``\n and ``chain_method == 'parallel'``.\n\n .. note:: It is possible to mix parallel and vectorized sampling, i.e., run vectorized chains\n on multiple devices using explicit `pmap`. Currently, doing so requires disabling the\n progress bar. For example,\n\n .. code-block:: python\n\n def do_mcmc(rng_key, n_vectorized=8):\n nuts_kernel = NUTS(model)\n mcmc = MCMC(\n nuts_kernel,\n progress_bar=False,\n num_chains=n_vectorized,\n chain_method='vectorized'\n )\n mcmc.run(\n rng_key,\n extra_fields=(\"potential_energy\",),\n )\n return {**mcmc.get_samples(), **mcmc.get_extra_fields()}\n # Number of devices to pmap over\n n_parallel = jax.local_device_count()\n rng_keys = jax.random.split(PRNGKey(rng_seed), n_parallel)\n traces = pmap(do_mcmc)(rng_keys)\n # concatenate traces along pmap'ed axis\n trace = {k: np.concatenate(v) for k, v in traces.items()}\n \"\"\"\n\n def __init__(\n self,\n sampler,\n *,\n num_warmup,\n num_samples,\n num_chains=1,\n thinning=1,\n postprocess_fn=None,\n chain_method=\"parallel\",\n progress_bar=True,\n jit_model_args=False,\n ):\n self.sampler = sampler\n self._sample_field = sampler.sample_field\n self._default_fields = sampler.default_fields\n self.num_warmup = num_warmup\n self.num_samples = num_samples\n self.num_chains = num_chains\n if not isinstance(thinning, int) or thinning < 1:\n raise ValueError(\"thinning must be a positive integer\")\n self.thinning = thinning\n self.postprocess_fn = postprocess_fn\n if chain_method not in [\"parallel\", \"vectorized\", \"sequential\"]:\n raise ValueError(\n \"Only supporting the following methods to draw chains:\"\n ' \"sequential\", \"parallel\", or \"vectorized\"'\n )\n if chain_method == \"parallel\" and local_device_count() < self.num_chains:\n chain_method = \"sequential\"\n warnings.warn(\n \"There are not enough devices to run parallel chains: expected {} but got {}.\"\n \" Chains will be drawn sequentially. If you are running MCMC in CPU,\"\n \" consider using `numpyro.set_host_device_count({})` at the beginning\"\n \" of your program. You can double-check how many devices are available in\"\n \" your system using `jax.local_device_count()`.\".format(\n self.num_chains, local_device_count(), self.num_chains\n ),\n stacklevel=find_stack_level(),\n )\n self.chain_method = chain_method\n self.progress_bar = progress_bar\n if \"CI\" in os.environ or \"PYTEST_XDIST_WORKER\" in os.environ:\n self.progress_bar = False\n self._jit_model_args = jit_model_args\n self._states = None\n self._states_flat = None\n # HMCState returned by last run\n self._last_state = None\n # HMCState returned by last warmup\n self._warmup_state = None\n # HMCState returned by hmc.init_kernel\n self._init_state_cache = {}\n self._cache = {}\n self._collection_params = {}\n self._set_collection_params()\n\n def _get_cached_fns(self):\n if self._jit_model_args:\n args, kwargs = (None,), (None,)\n else:\n args = tree_map(lambda x: _hashable(x), self._args)\n kwargs = tree_map(\n lambda x: _hashable(x), tuple(sorted(self._kwargs.items()))\n )\n key = args + kwargs\n try:\n fns = self._cache.get(key, None)\n # If unhashable arguments are provided, proceed normally\n # without caching\n except TypeError:\n fns, key = None, None\n if fns is None:\n\n def laxmap_postprocess_fn(states, args, kwargs):\n if self.postprocess_fn is None:\n body_fn = self.sampler.postprocess_fn(args, kwargs)\n else:\n body_fn = self.postprocess_fn\n if self.chain_method == \"vectorized\" and self.num_chains > 1:\n body_fn = vmap(body_fn)\n\n return lax.map(body_fn, states)\n\n if self._jit_model_args:\n sample_fn = partial(_sample_fn_jit_args, sampler=self.sampler)\n postprocess_fn = jit(laxmap_postprocess_fn)\n else:\n sample_fn = partial(\n _sample_fn_nojit_args,\n sampler=self.sampler,\n args=self._args,\n kwargs=self._kwargs,\n )\n postprocess_fn = jit(\n partial(laxmap_postprocess_fn, args=self._args, kwargs=self._kwargs)\n )\n\n fns = sample_fn, postprocess_fn\n if key is not None:\n self._cache[key] = fns\n return fns\n\n def _get_cached_init_state(self, rng_key, args, kwargs):\n rng_key = (_hashable(rng_key),)\n args = tree_map(lambda x: _hashable(x), args)\n kwargs = tree_map(lambda x: _hashable(x), tuple(sorted(kwargs.items())))\n key = rng_key + args + kwargs\n try:\n return self._init_state_cache.get(key, None)\n # If unhashable arguments are provided, return None\n except TypeError:\n return None\n\n def _single_chain_mcmc(self, init, args, kwargs, collect_fields):\n rng_key, init_state, init_params = init\n if init_state is None:\n init_state = self.sampler.init(\n rng_key,\n self.num_warmup,\n init_params,\n model_args=args,\n model_kwargs=kwargs,\n )\n sample_fn, postprocess_fn = self._get_cached_fns()\n diagnostics = (\n lambda x: self.sampler.get_diagnostics_str(x[0])\n if rng_key.ndim == 1\n else \"\"\n ) # noqa: E731\n init_val = (init_state, args, kwargs) if self._jit_model_args else (init_state,)\n lower_idx = self._collection_params[\"lower\"]\n upper_idx = self._collection_params[\"upper\"]\n phase = self._collection_params[\"phase\"]\n collection_size = self._collection_params[\"collection_size\"]\n collection_size = (\n collection_size\n if collection_size is None\n else collection_size // self.thinning\n )\n collect_vals = fori_collect(\n lower_idx,\n upper_idx,\n sample_fn,\n init_val,\n transform=_collect_fn(collect_fields),\n progbar=self.progress_bar,\n return_last_val=True,\n thinning=self.thinning,\n collection_size=collection_size,\n progbar_desc=partial(_get_progbar_desc_str, lower_idx, phase),\n diagnostics_fn=diagnostics,\n num_chains=self.num_chains if self.chain_method == \"parallel\" else 1,\n )\n states, last_val = collect_vals\n # Get first argument of type `HMCState`\n last_state = last_val[0]\n if len(collect_fields) == 1:\n states = (states,)\n states = dict(zip(collect_fields, states))\n # Apply constraints if number of samples is non-zero\n site_values = tree_flatten(states[self._sample_field])[0]\n # XXX: lax.map still works if some arrays have 0 size\n # so we only need to filter out the case site_value.shape[0] == 0\n # (which happens when lower_idx==upper_idx)\n if len(site_values) > 0 and jnp.shape(site_values[0])[0] > 0:\n if self._jit_model_args:\n states[self._sample_field] = postprocess_fn(\n states[self._sample_field], args, kwargs\n )\n else:\n states[self._sample_field] = postprocess_fn(states[self._sample_field])\n return states, last_state\n\n def _set_collection_params(\n self, lower=None, upper=None, collection_size=None, phase=None\n ):\n self._collection_params[\"lower\"] = self.num_warmup if lower is None else lower\n self._collection_params[\"upper\"] = (\n self.num_warmup + self.num_samples if upper is None else upper\n )\n self._collection_params[\"collection_size\"] = collection_size\n self._collection_params[\"phase\"] = phase\n\n def _compile(self, rng_key, *args, extra_fields=(), init_params=None, **kwargs):\n self._set_collection_params(0, 0, self.num_samples)\n self.run(\n rng_key, *args, extra_fields=extra_fields, init_params=init_params, **kwargs\n )\n rng_key = (_hashable(rng_key),)\n args = tree_map(lambda x: _hashable(x), args)\n kwargs = tree_map(lambda x: _hashable(x), tuple(sorted(kwargs.items())))\n key = rng_key + args + kwargs\n try:\n self._init_state_cache[key] = self._last_state\n # If unhashable arguments are provided, return None\n except TypeError:\n pass\n\n @property\n def post_warmup_state(self):\n \"\"\"\n The state before the sampling phase. If this attribute is not None,\n :meth:`run` will skip the warmup phase and start with the state\n specified in this attribute.\n\n .. note:: This attribute can be used to sequentially draw MCMC samples. For example,\n\n .. code-block:: python\n\n mcmc = MCMC(NUTS(model), num_warmup=100, num_samples=100)\n mcmc.run(random.PRNGKey(0))\n first_100_samples = mcmc.get_samples()\n mcmc.post_warmup_state = mcmc.last_state\n mcmc.run(mcmc.post_warmup_state.rng_key) # or mcmc.run(random.PRNGKey(1))\n second_100_samples = mcmc.get_samples()\n \"\"\"\n return self._warmup_state\n\n @post_warmup_state.setter\n def post_warmup_state(self, state):\n self._warmup_state = state\n\n @property\n def last_state(self):\n \"\"\"\n The final MCMC state at the end of the sampling phase.\n \"\"\"\n return self._last_state\n\n def warmup(\n self,\n rng_key,\n *args,\n extra_fields=(),\n collect_warmup=False,\n init_params=None,\n **kwargs,\n ):\n \"\"\"\n Run the MCMC warmup adaptation phase. After this call, `self.warmup_state` will be set\n and the :meth:`run` method will skip the warmup adaptation phase. To run `warmup` again\n for the new data, it is required to run :meth:`warmup` again.\n\n :param random.PRNGKey rng_key: Random number generator key to be used for the sampling.\n :param args: Arguments to be provided to the :meth:`numpyro.infer.mcmc.MCMCKernel.init` method.\n These are typically the arguments needed by the `model`.\n :param extra_fields: Extra fields (aside from :meth:`~numpyro.infer.mcmc.MCMCKernel.default_fields`)\n from the state object (e.g. :data:`numpyro.infer.hmc.HMCState` for HMC) to collect during\n the MCMC run.\n :type extra_fields: tuple or list\n :param bool collect_warmup: Whether to collect samples from the warmup phase. Defaults\n to `False`.\n :param init_params: Initial parameters to begin sampling. The type must be consistent\n with the input type to `potential_fn` provided to the kernel. If the kernel is\n instantiated by a numpyro model, the initial parameters here correspond to latent\n values in unconstrained space.\n :param kwargs: Keyword arguments to be provided to the :meth:`numpyro.infer.mcmc.MCMCKernel.init`\n method. These are typically the keyword arguments needed by the `model`.\n \"\"\"\n self._warmup_state = None\n if collect_warmup:\n self._set_collection_params(0, self.num_warmup, self.num_warmup, \"warmup\")\n else:\n self._set_collection_params(\n self.num_warmup, self.num_warmup, self.num_samples, \"warmup\"\n )\n self.run(\n rng_key, *args, extra_fields=extra_fields, init_params=init_params, **kwargs\n )\n self._warmup_state = self._last_state\n\n def run(self, rng_key, *args, extra_fields=(), init_params=None, **kwargs):\n \"\"\"\n Run the MCMC samplers and collect samples.\n\n :param random.PRNGKey rng_key: Random number generator key to be used for the sampling.\n For multi-chains, a batch of `num_chains` keys can be supplied. If `rng_key`\n does not have batch_size, it will be split in to a batch of `num_chains` keys.\n :param args: Arguments to be provided to the :meth:`numpyro.infer.mcmc.MCMCKernel.init` method.\n These are typically the arguments needed by the `model`.\n :param extra_fields: Extra fields (aside from `\"z\"`, `\"diverging\"`) from the\n state object (e.g. :data:`numpyro.infer.hmc.HMCState` for HMC) to be collected\n during the MCMC run. Note that subfields can be accessed using dots, e.g.\n `\"adapt_state.step_size\"` can be used to collect step sizes at each step.\n :type extra_fields: tuple or list of str\n :param init_params: Initial parameters to begin sampling. The type must be consistent\n with the input type to `potential_fn` provided to the kernel. If the kernel is\n instantiated by a numpyro model, the initial parameters here correspond to latent\n values in unconstrained space.\n :param kwargs: Keyword arguments to be provided to the :meth:`numpyro.infer.mcmc.MCMCKernel.init`\n method. These are typically the keyword arguments needed by the `model`.\n\n .. note:: jax allows python code to continue even when the compiled code has not finished yet.\n This can cause troubles when trying to profile the code for speed.\n See https://jax.readthedocs.io/en/latest/async_dispatch.html and\n https://jax.readthedocs.io/en/latest/profiling.html for pointers on profiling jax programs.\n \"\"\"\n init_params = tree_map(\n lambda x: lax.convert_element_type(x, jnp.result_type(x)), init_params\n )\n self._args = args\n self._kwargs = kwargs\n init_state = self._get_cached_init_state(rng_key, args, kwargs)\n if self.num_chains > 1 and rng_key.ndim == 1:\n rng_key = random.split(rng_key, self.num_chains)\n\n if self._warmup_state is not None:\n self._set_collection_params(0, self.num_samples, self.num_samples, \"sample\")\n init_state = self._warmup_state._replace(rng_key=rng_key)\n\n if init_params is not None and self.num_chains > 1:\n prototype_init_val = tree_flatten(init_params)[0][0]\n if jnp.shape(prototype_init_val)[0] != self.num_chains:\n raise ValueError(\n \"`init_params` must have the same leading dimension\"\n \" as `num_chains`.\"\n )\n assert isinstance(extra_fields, (tuple, list))\n collect_fields = tuple(\n set(\n (self._sample_field,)\n + tuple(self._default_fields)\n + tuple(extra_fields)\n )\n )\n partial_map_fn = partial(\n self._single_chain_mcmc,\n args=args,\n kwargs=kwargs,\n collect_fields=collect_fields,\n )\n map_args = (rng_key, init_state, init_params)\n if self.num_chains == 1:\n states_flat, last_state = partial_map_fn(map_args)\n states = tree_map(lambda x: x[jnp.newaxis, ...], states_flat)\n else:\n if self.chain_method == \"sequential\":\n states, last_state = _laxmap(partial_map_fn, map_args)\n elif self.chain_method == \"parallel\":\n states, last_state = pmap(partial_map_fn)(map_args)\n else:\n assert self.chain_method == \"vectorized\"\n states, last_state = partial_map_fn(map_args)\n # swap num_samples x num_chains to num_chains x num_samples\n states = tree_map(lambda x: jnp.swapaxes(x, 0, 1), states)\n states_flat = tree_map(\n # need to calculate first dimension manually; see issue #1328\n lambda x: jnp.reshape(x, (x.shape[0] * x.shape[1],) + x.shape[2:]),\n states,\n )\n self._last_state = last_state\n self._states = states\n self._states_flat = states_flat\n self._set_collection_params()\n\n def get_samples(self, group_by_chain=False):\n \"\"\"\n Get samples from the MCMC run.\n\n :param bool group_by_chain: Whether to preserve the chain dimension. If True,\n all samples will have num_chains as the size of their leading dimension.\n :return: Samples having the same data type as `init_params`. The data type is a\n `dict` keyed on site names if a model containing Pyro primitives is used,\n but can be any :func:`jaxlib.pytree`, more generally (e.g. when defining a\n `potential_fn` for HMC that takes `list` args).\n\n **Example:**\n\n You can then pass those samples to :class:`~numpyro.infer.util.Predictive`::\n\n posterior_samples = mcmc.get_samples()\n predictive = Predictive(model, posterior_samples=posterior_samples)\n samples = predictive(rng_key1, *model_args, **model_kwargs)\n\n \"\"\"\n return (\n self._states[self._sample_field]\n if group_by_chain\n else self._states_flat[self._sample_field]\n )\n\n def get_extra_fields(self, group_by_chain=False):\n \"\"\"\n Get extra fields from the MCMC run.\n\n :param bool group_by_chain: Whether to preserve the chain dimension. If True,\n all samples will have num_chains as the size of their leading dimension.\n :return: Extra fields keyed by field names which are specified in the\n `extra_fields` keyword of :meth:`run`.\n \"\"\"\n states = self._states if group_by_chain else self._states_flat\n return {k: v for k, v in states.items() if k != self._sample_field}\n\n def print_summary(self, prob=0.9, exclude_deterministic=True):\n \"\"\"\n Print the statistics of posterior samples collected during running this MCMC instance.\n\n :param float prob: the probability mass of samples within the credible interval.\n :param bool exclude_deterministic: whether or not print out the statistics\n at deterministic sites.\n \"\"\"\n # Exclude deterministic sites by default\n sites = self._states[self._sample_field]\n if isinstance(sites, dict) and exclude_deterministic:\n state_sample_field = attrgetter(self._sample_field)(self._last_state)\n # XXX: there might be the case that state.z is not a dictionary but\n # its postprocessed value `sites` is a dictionary.\n # TODO: in general, when both `sites` and `state.z` are dictionaries,\n # they can have different key names, not necessary due to deterministic\n # behavior. We might revise this logic if needed in the future.\n if isinstance(state_sample_field, dict):\n sites = {\n k: v\n for k, v in self._states[self._sample_field].items()\n if k in state_sample_field\n }\n print_summary(sites, prob=prob)\n extra_fields = self.get_extra_fields()\n if \"diverging\" in extra_fields:\n print(\n \"Number of divergences: {}\".format(jnp.sum(extra_fields[\"diverging\"]))\n )\n\n def __getstate__(self):\n state = self.__dict__.copy()\n state[\"_cache\"] = {}\n return state\n", "path": "numpyro/infer/mcmc.py" } ]
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 (Soumith Chintala)\n# Copyright (c) 2011-2014 Idiap Research Institute (Ronan Collobert)\n# Copyright (c) 2012-2014 Deepmind Technologies (Koray Kavukcuoglu)\n# Copyright (c) 2011-2012 NEC Laboratories America (Koray Kavukcuoglu)\n# Copyright (c) 2011-2013 NYU (Clement Farabet)\n# Copyright (c) 2006-2010 NEC Laboratories America (Ronan Collobert, Leon Bottou, Iain Melvin, Jason Weston)\n# Copyright (c) 2006 Idiap Research Institute (Samy Bengio)\n# Copyright (c) 2001-2004 Idiap Research Institute (Ronan Collobert, Samy Bengio, Johnny Mariethoz)\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\nfrom collections import OrderedDict\nfrom contextlib import contextmanager\nimport warnings\n\nfrom jax import lax, tree_util\nimport jax.numpy as jnp\n\nfrom numpyro.distributions.constraints import is_dependent, real\nfrom numpyro.distributions.transforms import Transform\nfrom numpyro.distributions.util import lazy_property, promote_shapes, sum_rightmost, validate_sample\nfrom numpyro.util import not_jax_tracer\n\n_VALIDATION_ENABLED = False\n\n\ndef enable_validation(is_validate=True):\n \"\"\"\n Enable or disable validation checks in NumPyro. Validation checks provide useful warnings and\n errors, e.g. NaN checks, validating distribution arguments and support values, etc. which is\n useful for debugging.\n\n .. note:: This utility does not take effect under JAX's JIT compilation or vectorized\n transformation :func:`jax.vmap`.\n\n :param bool is_validate: whether to enable validation checks.\n \"\"\"\n global _VALIDATION_ENABLED\n _VALIDATION_ENABLED = is_validate\n Distribution.set_default_validate_args(is_validate)\n\n\n@contextmanager\ndef validation_enabled(is_validate=True):\n \"\"\"\n Context manager that is useful when temporarily enabling/disabling validation checks.\n\n :param bool is_validate: whether to enable validation checks.\n \"\"\"\n distribution_validation_status = _VALIDATION_ENABLED\n try:\n enable_validation(is_validate)\n yield\n finally:\n enable_validation(distribution_validation_status)\n\n\nclass Distribution(object):\n \"\"\"\n Base class for probability distributions in NumPyro. The design largely\n follows from :mod:`torch.distributions`.\n\n :param batch_shape: The batch shape for the distribution. This designates\n independent (possibly non-identical) dimensions of a sample from the\n distribution. This is fixed for a distribution instance and is inferred\n from the shape of the distribution parameters.\n :param event_shape: The event shape for the distribution. This designates\n the dependent dimensions of a sample from the distribution. These are\n collapsed when we evaluate the log probability density of a batch of\n samples using `.log_prob`.\n :param validate_args: Whether to enable validation of distribution\n parameters and arguments to `.log_prob` method.\n\n As an example:\n\n .. doctest::\n\n >>> import jax.numpy as jnp\n >>> import numpyro.distributions as dist\n >>> d = dist.Dirichlet(jnp.ones((2, 3, 4)))\n >>> d.batch_shape\n (2, 3)\n >>> d.event_shape\n (4,)\n \"\"\"\n arg_constraints = {}\n support = None\n has_enumerate_support = False\n is_discrete = False\n reparametrized_params = []\n _validate_args = False\n\n # register Distribution as a pytree\n # ref: https://github.com/google/jax/issues/2916\n def __init_subclass__(cls, **kwargs):\n super().__init_subclass__(**kwargs)\n tree_util.register_pytree_node(cls,\n cls.tree_flatten,\n cls.tree_unflatten)\n\n def tree_flatten(self):\n return tuple(getattr(self, param) for param in sorted(self.arg_constraints.keys())), None\n\n @classmethod\n def tree_unflatten(cls, aux_data, params):\n return cls(**dict(zip(sorted(cls.arg_constraints.keys()), params)))\n\n @staticmethod\n def set_default_validate_args(value):\n if value not in [True, False]:\n raise ValueError\n Distribution._validate_args = value\n\n def __init__(self, batch_shape=(), event_shape=(), validate_args=None):\n self._batch_shape = batch_shape\n self._event_shape = event_shape\n if validate_args is not None:\n self._validate_args = validate_args\n if self._validate_args:\n for param, constraint in self.arg_constraints.items():\n if param not in self.__dict__ and isinstance(getattr(type(self), param), lazy_property):\n continue\n if is_dependent(constraint):\n continue # skip constraints that cannot be checked\n is_valid = jnp.all(constraint(getattr(self, param)))\n if not_jax_tracer(is_valid):\n if not is_valid:\n raise ValueError(\"The parameter {} has invalid values\".format(param))\n super(Distribution, self).__init__()\n\n @property\n def batch_shape(self):\n \"\"\"\n Returns the shape over which the distribution parameters are batched.\n\n :return: batch shape of the distribution.\n :rtype: tuple\n \"\"\"\n return self._batch_shape\n\n @property\n def event_shape(self):\n \"\"\"\n Returns the shape of a single sample from the distribution without\n batching.\n\n :return: event shape of the distribution.\n :rtype: tuple\n \"\"\"\n return self._event_shape\n\n @property\n def event_dim(self):\n \"\"\"\n :return: Number of dimensions of individual events.\n :rtype: int\n \"\"\"\n return len(self.event_shape)\n\n def shape(self, sample_shape=()):\n \"\"\"\n The tensor shape of samples from this distribution.\n\n Samples are of shape::\n\n d.shape(sample_shape) == sample_shape + d.batch_shape + d.event_shape\n\n :param tuple sample_shape: the size of the iid batch to be drawn from the\n distribution.\n :return: shape of samples.\n :rtype: tuple\n \"\"\"\n return sample_shape + self.batch_shape + self.event_shape\n\n def sample(self, key, sample_shape=()):\n \"\"\"\n Returns a sample from the distribution having shape given by\n `sample_shape + batch_shape + event_shape`. Note that when `sample_shape` is non-empty,\n leading dimensions (of size `sample_shape`) of the returned sample will\n be filled with iid draws from the distribution instance.\n\n :param jax.random.PRNGKey key: the rng_key key to be used for the distribution.\n :param tuple sample_shape: the sample shape for the distribution.\n :return: an array of shape `sample_shape + batch_shape + event_shape`\n :rtype: numpy.ndarray\n \"\"\"\n raise NotImplementedError\n\n def sample_with_intermediates(self, key, sample_shape=()):\n \"\"\"\n Same as ``sample`` except that any intermediate computations are\n returned (useful for `TransformedDistribution`).\n\n :param jax.random.PRNGKey key: the rng_key key to be used for the distribution.\n :param tuple sample_shape: the sample shape for the distribution.\n :return: an array of shape `sample_shape + batch_shape + event_shape`\n :rtype: numpy.ndarray\n \"\"\"\n return self.sample(key, sample_shape=sample_shape), []\n\n def log_prob(self, value):\n \"\"\"\n Evaluates the log probability density for a batch of samples given by\n `value`.\n\n :param value: A batch of samples from the distribution.\n :return: an array with shape `value.shape[:-self.event_shape]`\n :rtype: numpy.ndarray\n \"\"\"\n raise NotImplementedError\n\n @property\n def mean(self):\n \"\"\"\n Mean of the distribution.\n \"\"\"\n raise NotImplementedError\n\n @property\n def variance(self):\n \"\"\"\n Variance of the distribution.\n \"\"\"\n raise NotImplementedError\n\n def _validate_sample(self, value):\n mask = self.support(value)\n if not_jax_tracer(mask):\n if not jnp.all(mask):\n warnings.warn('Out-of-support values provided to log prob method. '\n 'The value argument should be within the support.')\n return mask\n\n def __call__(self, *args, **kwargs):\n key = kwargs.pop('rng_key')\n sample_intermediates = kwargs.pop('sample_intermediates', False)\n if sample_intermediates:\n return self.sample_with_intermediates(key, *args, **kwargs)\n return self.sample(key, *args, **kwargs)\n\n def to_event(self, reinterpreted_batch_ndims=None):\n \"\"\"\n Interpret the rightmost `reinterpreted_batch_ndims` batch dimensions as\n dependent event dimensions.\n\n :param reinterpreted_batch_ndims: Number of rightmost batch dims to\n interpret as event dims.\n :return: An instance of `Independent` distribution.\n :rtype: numpyro.distributions.distribution.Independent\n \"\"\"\n if reinterpreted_batch_ndims is None:\n reinterpreted_batch_ndims = len(self.batch_shape)\n elif reinterpreted_batch_ndims == 0:\n return self\n return Independent(self, reinterpreted_batch_ndims)\n\n def enumerate_support(self, expand=True):\n \"\"\"\n Returns an array with shape `len(support) x batch_shape`\n containing all values in the support.\n \"\"\"\n raise NotImplementedError\n\n def expand(self, batch_shape):\n \"\"\"\n Returns a new :class:`ExpandedDistribution` instance with batch\n dimensions expanded to `batch_shape`.\n\n :param tuple batch_shape: batch shape to expand to.\n :return: an instance of `ExpandedDistribution`.\n :rtype: :class:`ExpandedDistribution`\n \"\"\"\n batch_shape = tuple(batch_shape)\n if batch_shape == self.batch_shape:\n return self\n return ExpandedDistribution(self, batch_shape)\n\n def expand_by(self, sample_shape):\n \"\"\"\n Expands a distribution by adding ``sample_shape`` to the left side of\n its :attr:`~numpyro.distributions.distribution.Distribution.batch_shape`.\n To expand internal dims of ``self.batch_shape`` from 1 to something\n larger, use :meth:`expand` instead.\n\n :param tuple sample_shape: The size of the iid batch to be drawn\n from the distribution.\n :return: An expanded version of this distribution.\n :rtype: :class:`ExpandedDistribution`\n \"\"\"\n return self.expand(tuple(sample_shape) + self.batch_shape)\n\n def mask(self, mask):\n \"\"\"\n Masks a distribution by a boolean or boolean-valued array that is\n broadcastable to the distributions\n :attr:`Distribution.batch_shape` .\n\n :param mask: A boolean or boolean valued array (`True` includes\n a site, `False` excludes a site).\n :type mask: bool or jnp.ndarray\n :return: A masked copy of this distribution.\n :rtype: :class:`MaskedDistribution`\n \"\"\"\n if mask is True:\n return self\n return MaskedDistribution(self, mask)\n\n\nclass ExpandedDistribution(Distribution):\n arg_constraints = {}\n\n def __init__(self, base_dist, batch_shape=()):\n if isinstance(base_dist, ExpandedDistribution):\n batch_shape, _, _ = self._broadcast_shape(base_dist.batch_shape, batch_shape)\n base_dist = base_dist.base_dist\n self.base_dist = base_dist\n\n # adjust batch shape\n # Do basic validation. e.g. we should not \"unexpand\" distributions even if that is possible.\n new_shape, _, _ = self._broadcast_shape(base_dist.batch_shape, batch_shape)\n # Record interstitial and expanded dims/sizes w.r.t. the base distribution\n new_shape, expanded_sizes, interstitial_sizes = self._broadcast_shape(base_dist.batch_shape,\n new_shape)\n self._expanded_sizes = expanded_sizes\n self._interstitial_sizes = interstitial_sizes\n super().__init__(new_shape, base_dist.event_shape)\n\n @staticmethod\n def _broadcast_shape(existing_shape, new_shape):\n if len(new_shape) < len(existing_shape):\n raise ValueError(\"Cannot broadcast distribution of shape {} to shape {}\"\n .format(existing_shape, new_shape))\n reversed_shape = list(reversed(existing_shape))\n expanded_sizes, interstitial_sizes = [], []\n for i, size in enumerate(reversed(new_shape)):\n if i >= len(reversed_shape):\n reversed_shape.append(size)\n expanded_sizes.append((-i - 1, size))\n elif reversed_shape[i] == 1:\n if size != 1:\n reversed_shape[i] = size\n interstitial_sizes.append((-i - 1, size))\n elif reversed_shape[i] != size:\n raise ValueError(\"Cannot broadcast distribution of shape {} to shape {}\"\n .format(existing_shape, new_shape))\n return tuple(reversed(reversed_shape)), OrderedDict(expanded_sizes), OrderedDict(interstitial_sizes)\n\n @property\n def has_enumerate_support(self):\n return self.base_dist.has_enumerate_support\n\n @property\n def is_discrete(self):\n return self.base_dist.is_discrete\n\n @property\n def support(self):\n return self.base_dist.support\n\n def sample(self, key, sample_shape=()):\n interstitial_dims = tuple(self._interstitial_sizes.keys())\n event_dim = len(self.event_shape)\n interstitial_dims = tuple(i - event_dim for i in interstitial_dims)\n interstitial_sizes = tuple(self._interstitial_sizes.values())\n expanded_sizes = tuple(self._expanded_sizes.values())\n batch_shape = expanded_sizes + interstitial_sizes\n samples = self.base_dist(rng_key=key, sample_shape=sample_shape + batch_shape)\n interstitial_idx = len(sample_shape) + len(expanded_sizes)\n interstitial_sample_dims = tuple(range(interstitial_idx, interstitial_idx + len(interstitial_sizes)))\n for dim1, dim2 in zip(interstitial_dims, interstitial_sample_dims):\n samples = jnp.swapaxes(samples, dim1, dim2)\n return samples.reshape(sample_shape + self.batch_shape + self.event_shape)\n\n def log_prob(self, value):\n shape = lax.broadcast_shapes(self.batch_shape,\n jnp.shape(value)[:max(jnp.ndim(value) - self.event_dim, 0)])\n log_prob = self.base_dist.log_prob(value)\n return jnp.broadcast_to(log_prob, shape)\n\n def enumerate_support(self, expand=True):\n samples = self.base_dist.enumerate_support(expand=False)\n enum_shape = samples.shape[:1]\n samples = samples.reshape(enum_shape + (1,) * len(self.batch_shape))\n if expand:\n samples = samples.expand(enum_shape + self.batch_shape)\n return samples\n\n @property\n def mean(self):\n return jnp.broadcast_to(self.base_dist.mean, self.batch_shape + self.event_shape)\n\n @property\n def variance(self):\n return jnp.broadcast_to(self.base_dist.variance, self.batch_shape + self.event_shape)\n\n def tree_flatten(self):\n prepend_ndim = len(self.batch_shape) - len(self.base_dist.batch_shape)\n base_dist = tree_util.tree_map(\n lambda x: promote_shapes(x, shape=(1,) * prepend_ndim + jnp.shape(x))[0],\n self.base_dist)\n base_flatten, base_aux = base_dist.tree_flatten()\n return base_flatten, (type(self.base_dist), base_aux, self.batch_shape)\n\n @classmethod\n def tree_unflatten(cls, aux_data, params):\n base_cls, base_aux, batch_shape = aux_data\n base_dist = base_cls.tree_unflatten(base_aux, params)\n prepend_shape = base_dist.batch_shape[:len(base_dist.batch_shape) - len(batch_shape)]\n return cls(base_dist, batch_shape=prepend_shape + batch_shape)\n\n\nclass ImproperUniform(Distribution):\n \"\"\"\n A helper distribution with zero :meth:`log_prob` over the `support` domain.\n\n .. note:: `sample` method is not implemented for this distribution. In autoguide and mcmc,\n initial parameters for improper sites are derived from `init_to_uniform` or `init_to_value`\n strategies.\n\n **Usage:**\n\n .. doctest::\n\n >>> from numpyro import sample\n >>> from numpyro.distributions import ImproperUniform, Normal, constraints\n >>>\n >>> def model():\n ... # ordered vector with length 10\n ... x = sample('x', ImproperUniform(constraints.ordered_vector, (), event_shape=(10,)))\n ...\n ... # real matrix with shape (3, 4)\n ... y = sample('y', ImproperUniform(constraints.real, (), event_shape=(3, 4)))\n ...\n ... # a shape-(6, 8) batch of length-5 vectors greater than 3\n ... z = sample('z', ImproperUniform(constraints.greater_than(3), (6, 8), event_shape=(5,)))\n\n If you want to set improper prior over all values greater than `a`, where `a` is\n another random variable, you might use\n\n >>> def model():\n ... a = sample('a', Normal(0, 1))\n ... x = sample('x', ImproperUniform(constraints.greater_than(a), (), event_shape=()))\n\n or if you want to reparameterize it\n\n >>> from numpyro.distributions import TransformedDistribution, transforms\n >>> from numpyro.handlers import reparam\n >>> from numpyro.infer.reparam import TransformReparam\n >>>\n >>> def model():\n ... a = sample('a', Normal(0, 1))\n ... with reparam(config={'x': TransformReparam()}):\n ... x = sample('x',\n ... TransformedDistribution(ImproperUniform(constraints.positive, (), ()),\n ... transforms.AffineTransform(a, 1)))\n\n :param ~numpyro.distributions.constraints.Constraint support: the support of this distribution.\n :param tuple batch_shape: batch shape of this distribution. It is usually safe to\n set `batch_shape=()`.\n :param tuple event_shape: event shape of this distribution.\n \"\"\"\n arg_constraints = {}\n\n def __init__(self, support, batch_shape, event_shape, validate_args=None):\n self.support = support\n super().__init__(batch_shape, event_shape, validate_args=validate_args)\n\n @validate_sample\n def log_prob(self, value):\n batch_shape = jnp.shape(value)[:jnp.ndim(value) - len(self.event_shape)]\n batch_shape = lax.broadcast_shapes(batch_shape, self.batch_shape)\n return jnp.zeros(batch_shape)\n\n def _validate_sample(self, value):\n mask = super(ImproperUniform, self)._validate_sample(value)\n batch_dim = jnp.ndim(value) - len(self.event_shape)\n if batch_dim < jnp.ndim(mask):\n mask = jnp.all(jnp.reshape(mask, jnp.shape(mask)[:batch_dim] + (-1,)), -1)\n return mask\n\n def tree_flatten(self):\n raise NotImplementedError(\n \"Cannot flattening ImproperPrior distribution for general supports. \"\n \"Please raising a feature request for your specific `support`. \"\n \"Alternatively, you can use '.mask(False)' pattern. \"\n \"For example, to define an improper prior over positive domain, \"\n \"we can use the distribution `dist.LogNormal(0, 1).mask(False)`.\")\n\n\nclass Independent(Distribution):\n \"\"\"\n Reinterprets batch dimensions of a distribution as event dims by shifting\n the batch-event dim boundary further to the left.\n\n From a practical standpoint, this is useful when changing the result of\n :meth:`log_prob`. For example, a univariate Normal distribution can be\n interpreted as a multivariate Normal with diagonal covariance:\n\n .. doctest::\n\n >>> import numpyro.distributions as dist\n >>> normal = dist.Normal(jnp.zeros(3), jnp.ones(3))\n >>> [normal.batch_shape, normal.event_shape]\n [(3,), ()]\n >>> diag_normal = dist.Independent(normal, 1)\n >>> [diag_normal.batch_shape, diag_normal.event_shape]\n [(), (3,)]\n\n :param numpyro.distribution.Distribution base_distribution: a distribution instance.\n :param int reinterpreted_batch_ndims: the number of batch dims to reinterpret as event dims.\n \"\"\"\n arg_constraints = {}\n\n def __init__(self, base_dist, reinterpreted_batch_ndims, validate_args=None):\n if reinterpreted_batch_ndims > len(base_dist.batch_shape):\n raise ValueError(\"Expected reinterpreted_batch_ndims <= len(base_distribution.batch_shape), \"\n \"actual {} vs {}\".format(reinterpreted_batch_ndims,\n len(base_dist.batch_shape)))\n shape = base_dist.batch_shape + base_dist.event_shape\n event_dim = reinterpreted_batch_ndims + len(base_dist.event_shape)\n batch_shape = shape[:len(shape) - event_dim]\n event_shape = shape[len(shape) - event_dim:]\n self.base_dist = base_dist\n self.reinterpreted_batch_ndims = reinterpreted_batch_ndims\n super(Independent, self).__init__(batch_shape, event_shape, validate_args=validate_args)\n\n @property\n def support(self):\n return self.base_dist.support\n\n @property\n def has_enumerate_support(self):\n return self.base_dist.has_enumerate_support\n\n @property\n def is_discrete(self):\n return self.base_dist.is_discrete\n\n @property\n def reparameterized_params(self):\n return self.base_dist.reparameterized_params\n\n @property\n def mean(self):\n return self.base_dist.mean\n\n @property\n def variance(self):\n return self.base_dist.variance\n\n def sample(self, key, sample_shape=()):\n return self.base_dist(rng_key=key, sample_shape=sample_shape)\n\n def log_prob(self, value):\n log_prob = self.base_dist.log_prob(value)\n return sum_rightmost(log_prob, self.reinterpreted_batch_ndims)\n\n def expand(self, batch_shape):\n base_batch_shape = batch_shape + self.event_shape[:self.reinterpreted_batch_ndims]\n return self.base_dist.expand(base_batch_shape).to_event(self.reinterpreted_batch_ndims)\n\n def tree_flatten(self):\n base_flatten, base_aux = self.base_dist.tree_flatten()\n return base_flatten, (type(self.base_dist), base_aux, self.reinterpreted_batch_ndims)\n\n @classmethod\n def tree_unflatten(cls, aux_data, params):\n base_cls, base_aux, reinterpreted_batch_ndims = aux_data\n base_dist = base_cls.tree_unflatten(base_aux, params)\n return cls(base_dist, reinterpreted_batch_ndims)\n\n\nclass MaskedDistribution(Distribution):\n \"\"\"\n Masks a distribution by a boolean array that is broadcastable to the\n distribution's :attr:`Distribution.batch_shape`.\n In the special case ``mask is False``, computation of :meth:`log_prob` , is skipped,\n and constant zero values are returned instead.\n\n :param mask: A boolean or boolean-valued array.\n :type mask: jnp.ndarray or bool\n \"\"\"\n arg_constraints = {}\n\n def __init__(self, base_dist, mask):\n if isinstance(mask, bool):\n self._mask = mask\n else:\n batch_shape = lax.broadcast_shapes(jnp.shape(mask), tuple(base_dist.batch_shape))\n if mask.shape != batch_shape:\n mask = jnp.broadcast_to(mask, batch_shape)\n if base_dist.batch_shape != batch_shape:\n base_dist = base_dist.expand(batch_shape)\n self._mask = mask.astype('bool')\n self.base_dist = base_dist\n super().__init__(base_dist.batch_shape, base_dist.event_shape)\n\n @property\n def has_enumerate_support(self):\n return self.base_dist.has_enumerate_support\n\n @property\n def is_discrete(self):\n return self.base_dist.is_discrete\n\n @property\n def support(self):\n return self.base_dist.support\n\n def sample(self, key, sample_shape=()):\n return self.base_dist(rng_key=key, sample_shape=sample_shape)\n\n def log_prob(self, value):\n if self._mask is False:\n shape = lax.broadcast_shapes(tuple(self.base_dist.batch_shape),\n jnp.shape(value)[:max(jnp.ndim(value) - len(self.event_shape), 0)])\n return jnp.zeros(shape)\n if self._mask is True:\n return self.base_dist.log_prob(value)\n return jnp.where(self._mask, self.base_dist.log_prob(value), 0.)\n\n def enumerate_support(self, expand=True):\n return self.base_dist.enumerate_support(expand=expand)\n\n @property\n def mean(self):\n return self.base_dist.mean\n\n @property\n def variance(self):\n return self.base_dist.variance\n\n def tree_flatten(self):\n base_flatten, base_aux = self.base_dist.tree_flatten()\n if isinstance(self._mask, bool):\n return base_flatten, (type(self.base_dist), base_aux, self._mask)\n else:\n return (base_flatten, self._mask), (type(self.base_dist), base_aux)\n\n @classmethod\n def tree_unflatten(cls, aux_data, params):\n if len(aux_data) == 2:\n base_flatten, mask = params\n base_cls, base_aux = aux_data\n else:\n base_flatten = params\n base_cls, base_aux, mask = aux_data\n base_dist = base_cls.tree_unflatten(base_aux, base_flatten)\n return cls(base_dist, mask)\n\n\nclass TransformedDistribution(Distribution):\n \"\"\"\n Returns a distribution instance obtained as a result of applying\n a sequence of transforms to a base distribution. For an example,\n see :class:`~numpyro.distributions.LogNormal` and\n :class:`~numpyro.distributions.HalfNormal`.\n\n :param base_distribution: the base distribution over which to apply transforms.\n :param transforms: a single transform or a list of transforms.\n :param validate_args: Whether to enable validation of distribution\n parameters and arguments to `.log_prob` method.\n \"\"\"\n arg_constraints = {}\n\n def __init__(self, base_distribution, transforms, validate_args=None):\n if isinstance(transforms, Transform):\n transforms = [transforms, ]\n elif isinstance(transforms, list):\n if not all(isinstance(t, Transform) for t in transforms):\n raise ValueError(\"transforms must be a Transform or a list of Transforms\")\n else:\n raise ValueError(\"transforms must be a Transform or list, but was {}\".format(transforms))\n # XXX: this logic will not be valid when IndependentDistribution is support;\n # in that case, it is more involved to support Transform(Indep(Transform));\n # however, we might not need to support such kind of distribution\n # and should raise an error if base_distribution is an Indep one\n if isinstance(base_distribution, TransformedDistribution):\n self.base_dist = base_distribution.base_dist\n self.transforms = base_distribution.transforms + transforms\n else:\n self.base_dist = base_distribution\n self.transforms = transforms\n # NB: here we assume that base_dist.shape == transformed_dist.shape\n # but that might not be True for some transforms such as StickBreakingTransform\n # because the event dimension is transformed from (n - 1,) to (n,).\n # Currently, we have no mechanism to fix this issue. Given that\n # this is just an edge case, we might skip this issue but need\n # to pay attention to any inference function that inspects\n # transformed distribution's shape.\n shape = base_distribution.batch_shape + base_distribution.event_shape\n event_dim = max([len(base_distribution.event_shape)] + [t.event_dim for t in transforms])\n batch_shape = shape[:len(shape) - event_dim]\n event_shape = shape[len(shape) - event_dim:]\n super(TransformedDistribution, self).__init__(batch_shape, event_shape, validate_args=validate_args)\n\n @property\n def support(self):\n domain = self.base_dist.support\n for t in self.transforms:\n t.domain = domain\n domain = t.codomain\n return domain\n\n def sample(self, key, sample_shape=()):\n x = self.base_dist(rng_key=key, sample_shape=sample_shape)\n for transform in self.transforms:\n x = transform(x)\n return x\n\n def sample_with_intermediates(self, key, sample_shape=()):\n x = self.base_dist(rng_key=key, sample_shape=sample_shape)\n intermediates = []\n for transform in self.transforms:\n x_tmp = x\n x, t_inter = transform.call_with_intermediates(x)\n intermediates.append([x_tmp, t_inter])\n return x, intermediates\n\n @validate_sample\n def log_prob(self, value, intermediates=None):\n if intermediates is not None:\n if len(intermediates) != len(self.transforms):\n raise ValueError('Intermediates array has length = {}. Expected = {}.'\n .format(len(intermediates), len(self.transforms)))\n event_dim = len(self.event_shape)\n log_prob = 0.0\n y = value\n for i, transform in enumerate(reversed(self.transforms)):\n x = transform.inv(y) if intermediates is None else intermediates[-i - 1][0]\n t_inter = None if intermediates is None else intermediates[-i - 1][1]\n t_log_det = transform.log_abs_det_jacobian(x, y, t_inter)\n log_prob = log_prob - sum_rightmost(t_log_det, event_dim - transform.event_dim)\n y = x\n\n log_prob = log_prob + sum_rightmost(self.base_dist.log_prob(y),\n event_dim - len(self.base_dist.event_shape))\n return log_prob\n\n @property\n def mean(self):\n raise NotImplementedError\n\n @property\n def variance(self):\n raise NotImplementedError\n\n def tree_flatten(self):\n raise NotImplementedError(\n \"Flatenning TransformedDistribution is only supported for some specific cases.\"\n \" Consider using `TransformReparam` to convert this distribution to the base_dist,\"\n \" which is supported in most situtations. In addition, please reach out to us with\"\n \" your usage cases.\")\n\n\nclass Unit(Distribution):\n \"\"\"\n Trivial nonnormalized distribution representing the unit type.\n\n The unit type has a single value with no data, i.e. ``value.size == 0``.\n\n This is used for :func:`numpyro.factor` statements.\n \"\"\"\n arg_constraints = {'log_factor': real}\n support = real\n\n def __init__(self, log_factor, validate_args=None):\n batch_shape = jnp.shape(log_factor)\n event_shape = (0,) # This satisfies .size == 0.\n self.log_factor = log_factor\n super(Unit, self).__init__(batch_shape, event_shape, validate_args=validate_args)\n\n def sample(self, key, sample_shape=()):\n return jnp.empty(sample_shape + self.batch_shape + self.event_shape)\n\n def log_prob(self, value):\n shape = lax.broadcast_shapes(self.batch_shape, jnp.shape(value)[:-1])\n return jnp.broadcast_to(self.log_factor, shape)\n", "path": "numpyro/distributions/distribution.py" }, { "content": "# Copyright Contributors to the Pyro project.\n# SPDX-License-Identifier: Apache-2.0\n\nfrom collections import namedtuple\nfrom functools import partial\nimport warnings\n\nimport numpy as np\n\nfrom jax import device_get, lax, random, value_and_grad\nfrom jax.flatten_util import ravel_pytree\nimport jax.numpy as jnp\n\nimport numpyro\nimport numpyro.distributions as dist\nfrom numpyro.distributions.constraints import _GreaterThan, _Interval, real, real_vector\nfrom numpyro.distributions.transforms import biject_to\nfrom numpyro.distributions.util import is_identically_one, sum_rightmost\nfrom numpyro.handlers import seed, substitute, trace\nfrom numpyro.infer.initialization import init_to_uniform, init_to_value\nfrom numpyro.util import not_jax_tracer, soft_vmap, while_loop\n\n__all__ = [\n 'find_valid_initial_params',\n 'get_potential_fn',\n 'log_density',\n 'log_likelihood',\n 'potential_energy',\n 'initialize_model',\n 'Predictive',\n]\n\nModelInfo = namedtuple('ModelInfo', ['param_info', 'potential_fn', 'postprocess_fn', 'model_trace'])\nParamInfo = namedtuple('ParamInfo', ['z', 'potential_energy', 'z_grad'])\n\n\ndef log_density(model, model_args, model_kwargs, params):\n \"\"\"\n (EXPERIMENTAL INTERFACE) Computes log of joint density for the model given\n latent values ``params``.\n\n :param model: Python callable containing NumPyro primitives.\n :param tuple model_args: args provided to the model.\n :param dict model_kwargs: kwargs provided to the model.\n :param dict params: dictionary of current parameter values keyed by site\n name.\n :return: log of joint density and a corresponding model trace\n \"\"\"\n model = substitute(model, data=params)\n model_trace = trace(model).get_trace(*model_args, **model_kwargs)\n log_joint = jnp.array(0.)\n for site in model_trace.values():\n if site['type'] == 'sample' and not isinstance(site['fn'], dist.PRNGIdentity):\n value = site['value']\n intermediates = site['intermediates']\n scale = site['scale']\n if intermediates:\n log_prob = site['fn'].log_prob(value, intermediates)\n else:\n log_prob = site['fn'].log_prob(value)\n\n if (scale is not None) and (not is_identically_one(scale)):\n log_prob = scale * log_prob\n\n log_prob = jnp.sum(log_prob)\n log_joint = log_joint + log_prob\n return log_joint, model_trace\n\n\ndef transform_fn(transforms, params, invert=False):\n \"\"\"\n (EXPERIMENTAL INTERFACE) Callable that applies a transformation from the `transforms`\n dict to values in the `params` dict and returns the transformed values keyed on\n the same names.\n\n :param transforms: Dictionary of transforms keyed by names. Names in\n `transforms` and `params` should align.\n :param params: Dictionary of arrays keyed by names.\n :param invert: Whether to apply the inverse of the transforms.\n :return: `dict` of transformed params.\n \"\"\"\n if invert:\n transforms = {k: v.inv for k, v in transforms.items()}\n return {k: transforms[k](v) if k in transforms else v\n for k, v in params.items()}\n\n\ndef constrain_fn(model, model_args, model_kwargs, params, return_deterministic=False):\n \"\"\"\n (EXPERIMENTAL INTERFACE) Gets value at each latent site in `model` given\n unconstrained parameters `params`. The `transforms` is used to transform these\n unconstrained parameters to base values of the corresponding priors in `model`.\n If a prior is a transformed distribution, the corresponding base value lies in\n the support of base distribution. Otherwise, the base value lies in the support\n of the distribution.\n\n :param model: a callable containing NumPyro primitives.\n :param tuple model_args: args provided to the model.\n :param dict model_kwargs: kwargs provided to the model.\n :param dict params: dictionary of unconstrained values keyed by site\n names.\n :param bool return_deterministic: whether to return the value of `deterministic`\n sites from the model. Defaults to `False`.\n :return: `dict` of transformed params.\n \"\"\"\n\n def substitute_fn(site):\n if site['name'] in params:\n return biject_to(site['fn'].support)(params[site['name']])\n\n substituted_model = substitute(model, substitute_fn=substitute_fn)\n model_trace = trace(substituted_model).get_trace(*model_args, **model_kwargs)\n return {k: v['value'] for k, v in model_trace.items() if (k in params) or\n (return_deterministic and (v['type'] == 'deterministic'))}\n\n\ndef _unconstrain_reparam(params, site):\n name = site['name']\n if name in params:\n p = params[name]\n support = site['fn'].support\n if support in [real, real_vector]:\n return p\n t = biject_to(support)\n value = t(p)\n\n log_det = t.log_abs_det_jacobian(p, value)\n log_det = sum_rightmost(log_det, jnp.ndim(log_det) - jnp.ndim(value) + len(site['fn'].event_shape))\n if site['scale'] is not None:\n log_det = site['scale'] * log_det\n numpyro.factor('_{}_log_det'.format(name), log_det)\n return value\n\n\ndef potential_energy(model, model_args, model_kwargs, params, enum=False):\n \"\"\"\n (EXPERIMENTAL INTERFACE) Computes potential energy of a model given unconstrained params.\n The `inv_transforms` is used to transform these unconstrained parameters to base values\n of the corresponding priors in `model`. If a prior is a transformed distribution,\n the corresponding base value lies in the support of base distribution. Otherwise,\n the base value lies in the support of the distribution.\n\n :param model: a callable containing NumPyro primitives.\n :param tuple model_args: args provided to the model.\n :param dict model_kwargs: kwargs provided to the model.\n :param dict params: unconstrained parameters of `model`.\n :param bool enum: whether to enumerate over discrete latent sites.\n :return: potential energy given unconstrained parameters.\n \"\"\"\n if enum:\n from numpyro.contrib.funsor import log_density as log_density_\n else:\n log_density_ = log_density\n\n substituted_model = substitute(model, substitute_fn=partial(_unconstrain_reparam, params))\n # no param is needed for log_density computation because we already substitute\n log_joint, model_trace = log_density_(substituted_model, model_args, model_kwargs, {})\n return - log_joint\n\n\ndef _init_to_unconstrained_value(site=None, values={}):\n if site is None:\n return partial(_init_to_unconstrained_value, values=values)\n\n\ndef find_valid_initial_params(rng_key, model,\n init_strategy=init_to_uniform,\n enum=False,\n model_args=(),\n model_kwargs=None,\n prototype_params=None):\n \"\"\"\n (EXPERIMENTAL INTERFACE) Given a model with Pyro primitives, returns an initial\n valid unconstrained value for all the parameters. This function also returns\n the corresponding potential energy, the gradients, and an\n `is_valid` flag to say whether the initial parameters are valid. Parameter values\n are considered valid if the values and the gradients for the log density have\n finite values.\n\n :param jax.random.PRNGKey rng_key: random number generator seed to\n sample from the prior. The returned `init_params` will have the\n batch shape ``rng_key.shape[:-1]``.\n :param model: Python callable containing Pyro primitives.\n :param callable init_strategy: a per-site initialization function.\n :param bool enum: whether to enumerate over discrete latent sites.\n :param tuple model_args: args provided to the model.\n :param dict model_kwargs: kwargs provided to the model.\n :param dict prototype_params: an optional prototype parameters, which is used\n to define the shape for initial parameters.\n :return: tuple of `init_params_info` and `is_valid`, where `init_params_info` is the tuple\n containing the initial params, their potential energy, and their gradients.\n \"\"\"\n model_kwargs = {} if model_kwargs is None else model_kwargs\n init_strategy = init_strategy if isinstance(init_strategy, partial) else init_strategy()\n # handle those init strategies differently to save computation\n if init_strategy.func is init_to_uniform:\n radius = init_strategy.keywords.get(\"radius\")\n init_values = {}\n elif init_strategy.func is _init_to_unconstrained_value:\n radius = 2\n init_values = init_strategy.keywords.get(\"values\")\n else:\n radius = None\n\n def cond_fn(state):\n i, _, _, is_valid = state\n return (i < 100) & (~is_valid)\n\n def body_fn(state):\n i, key, _, _ = state\n key, subkey = random.split(key)\n\n if radius is None or prototype_params is None:\n # Wrap model in a `substitute` handler to initialize from `init_loc_fn`.\n seeded_model = substitute(seed(model, subkey), substitute_fn=init_strategy)\n model_trace = trace(seeded_model).get_trace(*model_args, **model_kwargs)\n constrained_values, inv_transforms = {}, {}\n for k, v in model_trace.items():\n if v['type'] == 'sample' and not v['is_observed'] and not v['fn'].is_discrete:\n constrained_values[k] = v['value']\n inv_transforms[k] = biject_to(v['fn'].support)\n params = transform_fn(inv_transforms,\n {k: v for k, v in constrained_values.items()},\n invert=True)\n else: # this branch doesn't require tracing the model\n params = {}\n for k, v in prototype_params.items():\n if k in init_values:\n params[k] = init_values[k]\n else:\n params[k] = random.uniform(subkey, jnp.shape(v), minval=-radius, maxval=radius)\n key, subkey = random.split(key)\n\n potential_fn = partial(potential_energy, model, model_args, model_kwargs, enum=enum)\n pe, z_grad = value_and_grad(potential_fn)(params)\n z_grad_flat = ravel_pytree(z_grad)[0]\n is_valid = jnp.isfinite(pe) & jnp.all(jnp.isfinite(z_grad_flat))\n return i + 1, key, (params, pe, z_grad), is_valid\n\n def _find_valid_params(rng_key, exit_early=False):\n init_state = (0, rng_key, (prototype_params, 0., prototype_params), False)\n if exit_early and not_jax_tracer(rng_key):\n # Early return if valid params found. This is only helpful for single chain,\n # where we can avoid compiling body_fn in while_loop.\n _, _, (init_params, pe, z_grad), is_valid = init_state = body_fn(init_state)\n if not_jax_tracer(is_valid):\n if device_get(is_valid):\n return (init_params, pe, z_grad), is_valid\n\n # XXX: this requires compiling the model, so for multi-chain, we trace the model 2-times\n # even if the init_state is a valid result\n _, _, (init_params, pe, z_grad), is_valid = while_loop(cond_fn, body_fn, init_state)\n return (init_params, pe, z_grad), is_valid\n\n # Handle possible vectorization\n if rng_key.ndim == 1:\n (init_params, pe, z_grad), is_valid = _find_valid_params(rng_key, exit_early=True)\n else:\n (init_params, pe, z_grad), is_valid = lax.map(_find_valid_params, rng_key)\n return (init_params, pe, z_grad), is_valid\n\n\ndef _get_model_transforms(model, model_args=(), model_kwargs=None):\n model_kwargs = {} if model_kwargs is None else model_kwargs\n model_trace = trace(model).get_trace(*model_args, **model_kwargs)\n inv_transforms = {}\n # model code may need to be replayed in the presence of deterministic sites\n replay_model = False\n has_enumerate_support = False\n for k, v in model_trace.items():\n if v['type'] == 'sample' and not v['is_observed']:\n if v['fn'].is_discrete:\n has_enumerate_support = True\n if not v['fn'].has_enumerate_support:\n raise RuntimeError(\"MCMC only supports continuous sites or discrete sites \"\n f\"with enumerate support, but got {type(v['fn']).__name__}.\")\n else:\n support = v['fn'].support\n inv_transforms[k] = biject_to(support)\n # XXX: the following code filters out most situations with dynamic supports\n args = ()\n if isinstance(support, _GreaterThan):\n args = ('lower_bound',)\n elif isinstance(support, _Interval):\n args = ('lower_bound', 'upper_bound')\n for arg in args:\n if not isinstance(getattr(support, arg), (int, float)):\n replay_model = True\n elif v['type'] == 'deterministic':\n replay_model = True\n return inv_transforms, replay_model, has_enumerate_support, model_trace\n\n\ndef get_potential_fn(model, inv_transforms, enum=False, replay_model=False,\n dynamic_args=False, model_args=(), model_kwargs=None):\n \"\"\"\n (EXPERIMENTAL INTERFACE) Given a model with Pyro primitives, returns a\n function which, given unconstrained parameters, evaluates the potential\n energy (negative log joint density). In addition, this returns a\n function to transform unconstrained values at sample sites to constrained\n values within their respective support.\n\n :param model: Python callable containing Pyro primitives.\n :param dict inv_transforms: dictionary of transforms keyed by names.\n :param bool enum: whether to enumerate over discrete latent sites.\n :param bool replay_model: whether we need to replay model in\n `postprocess_fn` to obtain `deterministic` sites.\n :param bool dynamic_args: if `True`, the `potential_fn` and\n `constraints_fn` are themselves dependent on model arguments.\n When provided a `*model_args, **model_kwargs`, they return\n `potential_fn` and `constraints_fn` callables, respectively.\n :param tuple model_args: args provided to the model.\n :param dict model_kwargs: kwargs provided to the model.\n :return: tuple of (`potential_fn`, `postprocess_fn`). The latter is used\n to constrain unconstrained samples (e.g. those returned by HMC)\n to values that lie within the site's support, and return values at\n `deterministic` sites in the model.\n \"\"\"\n if dynamic_args:\n def potential_fn(*args, **kwargs):\n return partial(potential_energy, model, args, kwargs, enum=enum)\n\n def postprocess_fn(*args, **kwargs):\n if replay_model:\n # XXX: we seed to sample discrete sites (but not collect them)\n model_ = seed(model.fn, 0) if enum else model\n return partial(constrain_fn, model_, args, kwargs, return_deterministic=True)\n else:\n return partial(transform_fn, inv_transforms)\n else:\n model_kwargs = {} if model_kwargs is None else model_kwargs\n potential_fn = partial(potential_energy, model, model_args, model_kwargs, enum=enum)\n if replay_model:\n model_ = seed(model.fn, 0) if enum else model\n postprocess_fn = partial(constrain_fn, model_, model_args, model_kwargs,\n return_deterministic=True)\n else:\n postprocess_fn = partial(transform_fn, inv_transforms)\n\n return potential_fn, postprocess_fn\n\n\ndef _guess_max_plate_nesting(model_trace):\n \"\"\"\n Guesses max_plate_nesting by using model trace.\n This optimistically assumes static model\n structure.\n \"\"\"\n sites = [site for site in model_trace.values()\n if site[\"type\"] == \"sample\"]\n\n dims = [frame.dim\n for site in sites\n for frame in site[\"cond_indep_stack\"]\n if frame.dim is not None]\n max_plate_nesting = -min(dims) if dims else 0\n return max_plate_nesting\n\n\ndef initialize_model(rng_key, model,\n init_strategy=init_to_uniform,\n dynamic_args=False,\n model_args=(),\n model_kwargs=None):\n \"\"\"\n (EXPERIMENTAL INTERFACE) Helper function that calls :func:`~numpyro.infer.util.get_potential_fn`\n and :func:`~numpyro.infer.util.find_valid_initial_params` under the hood\n to return a tuple of (`init_params_info`, `potential_fn`, `postprocess_fn`, `model_trace`).\n\n :param jax.random.PRNGKey rng_key: random number generator seed to\n sample from the prior. The returned `init_params` will have the\n batch shape ``rng_key.shape[:-1]``.\n :param model: Python callable containing Pyro primitives.\n :param callable init_strategy: a per-site initialization function.\n See :ref:`init_strategy` section for available functions.\n :param bool dynamic_args: if `True`, the `potential_fn` and\n `constraints_fn` are themselves dependent on model arguments.\n When provided a `*model_args, **model_kwargs`, they return\n `potential_fn` and `constraints_fn` callables, respectively.\n :param tuple model_args: args provided to the model.\n :param dict model_kwargs: kwargs provided to the model.\n :return: a namedtupe `ModelInfo` which contains the fields\n (`param_info`, `potential_fn`, `postprocess_fn`, `model_trace`), where\n `param_info` is a namedtuple `ParamInfo` containing values from the prior\n used to initiate MCMC, their corresponding potential energy, and their gradients;\n `postprocess_fn` is a callable that uses inverse transforms\n to convert unconstrained HMC samples to constrained values that\n lie within the site's support, in addition to returning values\n at `deterministic` sites in the model.\n \"\"\"\n model_kwargs = {} if model_kwargs is None else model_kwargs\n substituted_model = substitute(seed(model, rng_key if jnp.ndim(rng_key) == 1 else rng_key[0]),\n substitute_fn=init_strategy)\n inv_transforms, replay_model, has_enumerate_support, model_trace = _get_model_transforms(\n substituted_model, model_args, model_kwargs)\n constrained_values = {k: v['value'] for k, v in model_trace.items()\n if v['type'] == 'sample' and not v['is_observed']\n and not v['fn'].is_discrete}\n\n if has_enumerate_support:\n from numpyro.contrib.funsor import config_enumerate, enum\n\n if not isinstance(model, enum):\n max_plate_nesting = _guess_max_plate_nesting(model_trace)\n model = enum(config_enumerate(model), -max_plate_nesting - 1)\n\n potential_fn, postprocess_fn = get_potential_fn(model,\n inv_transforms,\n replay_model=replay_model,\n enum=has_enumerate_support,\n dynamic_args=dynamic_args,\n model_args=model_args,\n model_kwargs=model_kwargs)\n\n init_strategy = init_strategy if isinstance(init_strategy, partial) else init_strategy()\n if (init_strategy.func is init_to_value) and not replay_model:\n init_values = init_strategy.keywords.get(\"values\")\n unconstrained_values = transform_fn(inv_transforms, init_values, invert=True)\n init_strategy = _init_to_unconstrained_value(values=unconstrained_values)\n prototype_params = transform_fn(inv_transforms, constrained_values, invert=True)\n (init_params, pe, grad), is_valid = find_valid_initial_params(rng_key, model,\n init_strategy=init_strategy,\n enum=has_enumerate_support,\n model_args=model_args,\n model_kwargs=model_kwargs,\n prototype_params=prototype_params)\n\n if not_jax_tracer(is_valid):\n if device_get(~jnp.all(is_valid)):\n raise RuntimeError(\"Cannot find valid initial parameters. Please check your model again.\")\n return ModelInfo(ParamInfo(init_params, pe, grad), potential_fn, postprocess_fn, model_trace)\n\n\ndef _predictive(rng_key, model, posterior_samples, batch_shape, return_sites=None,\n parallel=True, model_args=(), model_kwargs={}):\n\n def single_prediction(val):\n rng_key, samples = val\n model_trace = trace(seed(substitute(model, samples), rng_key)).get_trace(\n *model_args, **model_kwargs)\n if return_sites is not None:\n if return_sites == '':\n sites = {k for k, site in model_trace.items() if site['type'] != 'plate'}\n else:\n sites = return_sites\n else:\n sites = {k for k, site in model_trace.items()\n if (site['type'] == 'sample' and k not in samples) or (site['type'] == 'deterministic')}\n return {name: site['value'] for name, site in model_trace.items() if name in sites}\n\n num_samples = int(np.prod(batch_shape))\n if num_samples > 1:\n rng_key = random.split(rng_key, num_samples)\n rng_key = rng_key.reshape(batch_shape + (2,))\n chunk_size = num_samples if parallel else 1\n return soft_vmap(single_prediction, (rng_key, posterior_samples), len(batch_shape), chunk_size)\n\n\nclass Predictive(object):\n \"\"\"\n This class is used to construct predictive distribution. The predictive distribution is obtained\n by running model conditioned on latent samples from `posterior_samples`.\n\n .. warning::\n The interface for the `Predictive` class is experimental, and\n might change in the future.\n\n :param model: Python callable containing Pyro primitives.\n :param dict posterior_samples: dictionary of samples from the posterior.\n :param callable guide: optional guide to get posterior samples of sites not present\n in `posterior_samples`.\n :param dict params: dictionary of values for param sites of model/guide.\n :param int num_samples: number of samples\n :param list return_sites: sites to return; by default only sample sites not present\n in `posterior_samples` are returned.\n :param bool parallel: whether to predict in parallel using JAX vectorized map :func:`jax.vmap`.\n Defaults to False.\n :param batch_ndims: the number of batch dimensions in posterior samples. Some usages:\n\n + set `batch_ndims=0` to get prediction for 1 single sample\n\n + set `batch_ndims=1` to get prediction for `posterior_samples`\n with shapes `(num_samples x ...)`\n\n + set `batch_ndims=2` to get prediction for `posterior_samples`\n with shapes `(num_chains x N x ...)`. Note that if `num_samples`\n argument is not None, its value should be equal to `num_chains x N`.\n\n :return: dict of samples from the predictive distribution.\n \"\"\"\n\n def __init__(self, model, posterior_samples=None, guide=None, params=None, num_samples=None,\n return_sites=None, parallel=False, batch_ndims=1):\n if posterior_samples is None and num_samples is None:\n raise ValueError(\"Either posterior_samples or num_samples must be specified.\")\n\n posterior_samples = {} if posterior_samples is None else posterior_samples\n\n prototype_site = batch_shape = batch_size = None\n for name, sample in posterior_samples.items():\n if batch_shape is not None and sample.shape[:batch_ndims] != batch_shape:\n raise ValueError(f\"Batch shapes at site {name} and {prototype_site} \"\n f\"should be the same, but got \"\n f\"{sample.shape[:batch_ndims]} and {batch_shape}\")\n else:\n prototype_site = name\n batch_shape = sample.shape[:batch_ndims]\n batch_size = int(np.prod(batch_shape))\n if (num_samples is not None) and (num_samples != batch_size):\n warnings.warn(\"Sample's batch dimension size {} is different from the \"\n \"provided {} num_samples argument. Defaulting to {}.\"\n .format(batch_size, num_samples, batch_size), UserWarning)\n num_samples = batch_size\n\n if num_samples is None:\n raise ValueError(\"No sample sites in posterior samples to infer `num_samples`.\")\n\n if batch_shape is None:\n batch_shape = (1,) * (batch_ndims - 1) + (num_samples,)\n\n if return_sites is not None:\n assert isinstance(return_sites, (list, tuple, set))\n\n self.model = model\n self.posterior_samples = {} if posterior_samples is None else posterior_samples\n self.num_samples = num_samples\n self.guide = guide\n self.params = {} if params is None else params\n self.return_sites = return_sites\n self.parallel = parallel\n self.batch_ndims = batch_ndims\n self._batch_shape = batch_shape\n\n def __call__(self, rng_key, *args, **kwargs):\n \"\"\"\n Returns dict of samples from the predictive distribution. By default, only sample sites not\n contained in `posterior_samples` are returned. This can be modified by changing the\n `return_sites` keyword argument of this :class:`Predictive` instance.\n\n :param jax.random.PRNGKey rng_key: random key to draw samples.\n :param args: model arguments.\n :param kwargs: model kwargs.\n \"\"\"\n posterior_samples = self.posterior_samples\n if self.guide is not None:\n rng_key, guide_rng_key = random.split(rng_key)\n # use return_sites='' as a special signal to return all sites\n guide = substitute(self.guide, self.params)\n posterior_samples = _predictive(guide_rng_key, guide, posterior_samples,\n self._batch_shape, return_sites='', parallel=self.parallel,\n model_args=args, model_kwargs=kwargs)\n model = substitute(self.model, self.params)\n return _predictive(rng_key, model, posterior_samples, self._batch_shape,\n return_sites=self.return_sites, parallel=self.parallel,\n model_args=args, model_kwargs=kwargs)\n\n\ndef log_likelihood(model, posterior_samples, *args, parallel=False, batch_ndims=1, **kwargs):\n \"\"\"\n (EXPERIMENTAL INTERFACE) Returns log likelihood at observation nodes of model,\n given samples of all latent variables.\n\n :param model: Python callable containing Pyro primitives.\n :param dict posterior_samples: dictionary of samples from the posterior.\n :param args: model arguments.\n :param batch_ndims: the number of batch dimensions in posterior samples. Some usages:\n\n + set `batch_ndims=0` to get prediction for 1 single sample\n\n + set `batch_ndims=1` to get prediction for `posterior_samples`\n with shapes `(num_samples x ...)`\n\n + set `batch_ndims=2` to get prediction for `posterior_samples`\n with shapes `(num_chains x N x ...)`\n\n :param kwargs: model kwargs.\n :return: dict of log likelihoods at observation sites.\n \"\"\"\n\n def single_loglik(samples):\n substituted_model = substitute(model, samples) if isinstance(samples, dict) else model\n model_trace = trace(substituted_model).get_trace(*args, **kwargs)\n return {name: site['fn'].log_prob(site['value']) for name, site in model_trace.items()\n if site['type'] == 'sample' and site['is_observed']}\n\n prototype_site = batch_shape = None\n for name, sample in posterior_samples.items():\n if batch_shape is not None and sample.shape[:batch_ndims] != batch_shape:\n raise ValueError(f\"Batch shapes at site {name} and {prototype_site} \"\n f\"should be the same, but got \"\n f\"{sample.shape[:batch_ndims]} and {batch_shape}\")\n else:\n prototype_site = name\n batch_shape = sample.shape[:batch_ndims]\n\n if batch_shape is None: # posterior_samples is an empty dict\n batch_shape = (1,) * batch_ndims\n posterior_samples = np.zeros(batch_shape)\n\n batch_size = int(np.prod(batch_shape))\n chunk_size = batch_size if parallel else 1\n return soft_vmap(single_loglik, posterior_samples, len(batch_shape), chunk_size)\n", "path": "numpyro/infer/util.py" } ]
[ { "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 (Soumith Chintala)\n# Copyright (c) 2011-2014 Idiap Research Institute (Ronan Collobert)\n# Copyright (c) 2012-2014 Deepmind Technologies (Koray Kavukcuoglu)\n# Copyright (c) 2011-2012 NEC Laboratories America (Koray Kavukcuoglu)\n# Copyright (c) 2011-2013 NYU (Clement Farabet)\n# Copyright (c) 2006-2010 NEC Laboratories America (Ronan Collobert, Leon Bottou, Iain Melvin, Jason Weston)\n# Copyright (c) 2006 Idiap Research Institute (Samy Bengio)\n# Copyright (c) 2001-2004 Idiap Research Institute (Ronan Collobert, Samy Bengio, Johnny Mariethoz)\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\nfrom collections import OrderedDict\nfrom contextlib import contextmanager\nimport warnings\n\nfrom jax import lax, tree_util\nimport jax.numpy as jnp\n\nfrom numpyro.distributions.constraints import is_dependent, real\nfrom numpyro.distributions.transforms import Transform\nfrom numpyro.distributions.util import lazy_property, promote_shapes, sum_rightmost, validate_sample\nfrom numpyro.util import not_jax_tracer\n\n_VALIDATION_ENABLED = False\n\n\ndef enable_validation(is_validate=True):\n \"\"\"\n Enable or disable validation checks in NumPyro. Validation checks provide useful warnings and\n errors, e.g. NaN checks, validating distribution arguments and support values, etc. which is\n useful for debugging.\n\n .. note:: This utility does not take effect under JAX's JIT compilation or vectorized\n transformation :func:`jax.vmap`.\n\n :param bool is_validate: whether to enable validation checks.\n \"\"\"\n global _VALIDATION_ENABLED\n _VALIDATION_ENABLED = is_validate\n Distribution.set_default_validate_args(is_validate)\n\n\n@contextmanager\ndef validation_enabled(is_validate=True):\n \"\"\"\n Context manager that is useful when temporarily enabling/disabling validation checks.\n\n :param bool is_validate: whether to enable validation checks.\n \"\"\"\n distribution_validation_status = _VALIDATION_ENABLED\n try:\n enable_validation(is_validate)\n yield\n finally:\n enable_validation(distribution_validation_status)\n\n\nclass Distribution(object):\n \"\"\"\n Base class for probability distributions in NumPyro. The design largely\n follows from :mod:`torch.distributions`.\n\n :param batch_shape: The batch shape for the distribution. This designates\n independent (possibly non-identical) dimensions of a sample from the\n distribution. This is fixed for a distribution instance and is inferred\n from the shape of the distribution parameters.\n :param event_shape: The event shape for the distribution. This designates\n the dependent dimensions of a sample from the distribution. These are\n collapsed when we evaluate the log probability density of a batch of\n samples using `.log_prob`.\n :param validate_args: Whether to enable validation of distribution\n parameters and arguments to `.log_prob` method.\n\n As an example:\n\n .. doctest::\n\n >>> import jax.numpy as jnp\n >>> import numpyro.distributions as dist\n >>> d = dist.Dirichlet(jnp.ones((2, 3, 4)))\n >>> d.batch_shape\n (2, 3)\n >>> d.event_shape\n (4,)\n \"\"\"\n arg_constraints = {}\n support = None\n has_enumerate_support = False\n is_discrete = False\n reparametrized_params = []\n _validate_args = False\n\n # register Distribution as a pytree\n # ref: https://github.com/google/jax/issues/2916\n def __init_subclass__(cls, **kwargs):\n super().__init_subclass__(**kwargs)\n tree_util.register_pytree_node(cls,\n cls.tree_flatten,\n cls.tree_unflatten)\n\n def tree_flatten(self):\n return tuple(getattr(self, param) for param in sorted(self.arg_constraints.keys())), None\n\n @classmethod\n def tree_unflatten(cls, aux_data, params):\n return cls(**dict(zip(sorted(cls.arg_constraints.keys()), params)))\n\n @staticmethod\n def set_default_validate_args(value):\n if value not in [True, False]:\n raise ValueError\n Distribution._validate_args = value\n\n def __init__(self, batch_shape=(), event_shape=(), validate_args=None):\n self._batch_shape = batch_shape\n self._event_shape = event_shape\n if validate_args is not None:\n self._validate_args = validate_args\n if self._validate_args:\n for param, constraint in self.arg_constraints.items():\n if param not in self.__dict__ and isinstance(getattr(type(self), param), lazy_property):\n continue\n if is_dependent(constraint):\n continue # skip constraints that cannot be checked\n is_valid = jnp.all(constraint(getattr(self, param)))\n if not_jax_tracer(is_valid):\n if not is_valid:\n raise ValueError(\"{} distribution got invalid {} parameter.\".format(\n self.__class__.__name__, param))\n super(Distribution, self).__init__()\n\n @property\n def batch_shape(self):\n \"\"\"\n Returns the shape over which the distribution parameters are batched.\n\n :return: batch shape of the distribution.\n :rtype: tuple\n \"\"\"\n return self._batch_shape\n\n @property\n def event_shape(self):\n \"\"\"\n Returns the shape of a single sample from the distribution without\n batching.\n\n :return: event shape of the distribution.\n :rtype: tuple\n \"\"\"\n return self._event_shape\n\n @property\n def event_dim(self):\n \"\"\"\n :return: Number of dimensions of individual events.\n :rtype: int\n \"\"\"\n return len(self.event_shape)\n\n def shape(self, sample_shape=()):\n \"\"\"\n The tensor shape of samples from this distribution.\n\n Samples are of shape::\n\n d.shape(sample_shape) == sample_shape + d.batch_shape + d.event_shape\n\n :param tuple sample_shape: the size of the iid batch to be drawn from the\n distribution.\n :return: shape of samples.\n :rtype: tuple\n \"\"\"\n return sample_shape + self.batch_shape + self.event_shape\n\n def sample(self, key, sample_shape=()):\n \"\"\"\n Returns a sample from the distribution having shape given by\n `sample_shape + batch_shape + event_shape`. Note that when `sample_shape` is non-empty,\n leading dimensions (of size `sample_shape`) of the returned sample will\n be filled with iid draws from the distribution instance.\n\n :param jax.random.PRNGKey key: the rng_key key to be used for the distribution.\n :param tuple sample_shape: the sample shape for the distribution.\n :return: an array of shape `sample_shape + batch_shape + event_shape`\n :rtype: numpy.ndarray\n \"\"\"\n raise NotImplementedError\n\n def sample_with_intermediates(self, key, sample_shape=()):\n \"\"\"\n Same as ``sample`` except that any intermediate computations are\n returned (useful for `TransformedDistribution`).\n\n :param jax.random.PRNGKey key: the rng_key key to be used for the distribution.\n :param tuple sample_shape: the sample shape for the distribution.\n :return: an array of shape `sample_shape + batch_shape + event_shape`\n :rtype: numpy.ndarray\n \"\"\"\n return self.sample(key, sample_shape=sample_shape), []\n\n def log_prob(self, value):\n \"\"\"\n Evaluates the log probability density for a batch of samples given by\n `value`.\n\n :param value: A batch of samples from the distribution.\n :return: an array with shape `value.shape[:-self.event_shape]`\n :rtype: numpy.ndarray\n \"\"\"\n raise NotImplementedError\n\n @property\n def mean(self):\n \"\"\"\n Mean of the distribution.\n \"\"\"\n raise NotImplementedError\n\n @property\n def variance(self):\n \"\"\"\n Variance of the distribution.\n \"\"\"\n raise NotImplementedError\n\n def _validate_sample(self, value):\n mask = self.support(value)\n if not_jax_tracer(mask):\n if not jnp.all(mask):\n warnings.warn('Out-of-support values provided to log prob method. '\n 'The value argument should be within the support.')\n return mask\n\n def __call__(self, *args, **kwargs):\n key = kwargs.pop('rng_key')\n sample_intermediates = kwargs.pop('sample_intermediates', False)\n if sample_intermediates:\n return self.sample_with_intermediates(key, *args, **kwargs)\n return self.sample(key, *args, **kwargs)\n\n def to_event(self, reinterpreted_batch_ndims=None):\n \"\"\"\n Interpret the rightmost `reinterpreted_batch_ndims` batch dimensions as\n dependent event dimensions.\n\n :param reinterpreted_batch_ndims: Number of rightmost batch dims to\n interpret as event dims.\n :return: An instance of `Independent` distribution.\n :rtype: numpyro.distributions.distribution.Independent\n \"\"\"\n if reinterpreted_batch_ndims is None:\n reinterpreted_batch_ndims = len(self.batch_shape)\n elif reinterpreted_batch_ndims == 0:\n return self\n return Independent(self, reinterpreted_batch_ndims)\n\n def enumerate_support(self, expand=True):\n \"\"\"\n Returns an array with shape `len(support) x batch_shape`\n containing all values in the support.\n \"\"\"\n raise NotImplementedError\n\n def expand(self, batch_shape):\n \"\"\"\n Returns a new :class:`ExpandedDistribution` instance with batch\n dimensions expanded to `batch_shape`.\n\n :param tuple batch_shape: batch shape to expand to.\n :return: an instance of `ExpandedDistribution`.\n :rtype: :class:`ExpandedDistribution`\n \"\"\"\n batch_shape = tuple(batch_shape)\n if batch_shape == self.batch_shape:\n return self\n return ExpandedDistribution(self, batch_shape)\n\n def expand_by(self, sample_shape):\n \"\"\"\n Expands a distribution by adding ``sample_shape`` to the left side of\n its :attr:`~numpyro.distributions.distribution.Distribution.batch_shape`.\n To expand internal dims of ``self.batch_shape`` from 1 to something\n larger, use :meth:`expand` instead.\n\n :param tuple sample_shape: The size of the iid batch to be drawn\n from the distribution.\n :return: An expanded version of this distribution.\n :rtype: :class:`ExpandedDistribution`\n \"\"\"\n return self.expand(tuple(sample_shape) + self.batch_shape)\n\n def mask(self, mask):\n \"\"\"\n Masks a distribution by a boolean or boolean-valued array that is\n broadcastable to the distributions\n :attr:`Distribution.batch_shape` .\n\n :param mask: A boolean or boolean valued array (`True` includes\n a site, `False` excludes a site).\n :type mask: bool or jnp.ndarray\n :return: A masked copy of this distribution.\n :rtype: :class:`MaskedDistribution`\n \"\"\"\n if mask is True:\n return self\n return MaskedDistribution(self, mask)\n\n\nclass ExpandedDistribution(Distribution):\n arg_constraints = {}\n\n def __init__(self, base_dist, batch_shape=()):\n if isinstance(base_dist, ExpandedDistribution):\n batch_shape, _, _ = self._broadcast_shape(base_dist.batch_shape, batch_shape)\n base_dist = base_dist.base_dist\n self.base_dist = base_dist\n\n # adjust batch shape\n # Do basic validation. e.g. we should not \"unexpand\" distributions even if that is possible.\n new_shape, _, _ = self._broadcast_shape(base_dist.batch_shape, batch_shape)\n # Record interstitial and expanded dims/sizes w.r.t. the base distribution\n new_shape, expanded_sizes, interstitial_sizes = self._broadcast_shape(base_dist.batch_shape,\n new_shape)\n self._expanded_sizes = expanded_sizes\n self._interstitial_sizes = interstitial_sizes\n super().__init__(new_shape, base_dist.event_shape)\n\n @staticmethod\n def _broadcast_shape(existing_shape, new_shape):\n if len(new_shape) < len(existing_shape):\n raise ValueError(\"Cannot broadcast distribution of shape {} to shape {}\"\n .format(existing_shape, new_shape))\n reversed_shape = list(reversed(existing_shape))\n expanded_sizes, interstitial_sizes = [], []\n for i, size in enumerate(reversed(new_shape)):\n if i >= len(reversed_shape):\n reversed_shape.append(size)\n expanded_sizes.append((-i - 1, size))\n elif reversed_shape[i] == 1:\n if size != 1:\n reversed_shape[i] = size\n interstitial_sizes.append((-i - 1, size))\n elif reversed_shape[i] != size:\n raise ValueError(\"Cannot broadcast distribution of shape {} to shape {}\"\n .format(existing_shape, new_shape))\n return tuple(reversed(reversed_shape)), OrderedDict(expanded_sizes), OrderedDict(interstitial_sizes)\n\n @property\n def has_enumerate_support(self):\n return self.base_dist.has_enumerate_support\n\n @property\n def is_discrete(self):\n return self.base_dist.is_discrete\n\n @property\n def support(self):\n return self.base_dist.support\n\n def sample(self, key, sample_shape=()):\n interstitial_dims = tuple(self._interstitial_sizes.keys())\n event_dim = len(self.event_shape)\n interstitial_dims = tuple(i - event_dim for i in interstitial_dims)\n interstitial_sizes = tuple(self._interstitial_sizes.values())\n expanded_sizes = tuple(self._expanded_sizes.values())\n batch_shape = expanded_sizes + interstitial_sizes\n samples = self.base_dist(rng_key=key, sample_shape=sample_shape + batch_shape)\n interstitial_idx = len(sample_shape) + len(expanded_sizes)\n interstitial_sample_dims = tuple(range(interstitial_idx, interstitial_idx + len(interstitial_sizes)))\n for dim1, dim2 in zip(interstitial_dims, interstitial_sample_dims):\n samples = jnp.swapaxes(samples, dim1, dim2)\n return samples.reshape(sample_shape + self.batch_shape + self.event_shape)\n\n def log_prob(self, value):\n shape = lax.broadcast_shapes(self.batch_shape,\n jnp.shape(value)[:max(jnp.ndim(value) - self.event_dim, 0)])\n log_prob = self.base_dist.log_prob(value)\n return jnp.broadcast_to(log_prob, shape)\n\n def enumerate_support(self, expand=True):\n samples = self.base_dist.enumerate_support(expand=False)\n enum_shape = samples.shape[:1]\n samples = samples.reshape(enum_shape + (1,) * len(self.batch_shape))\n if expand:\n samples = samples.expand(enum_shape + self.batch_shape)\n return samples\n\n @property\n def mean(self):\n return jnp.broadcast_to(self.base_dist.mean, self.batch_shape + self.event_shape)\n\n @property\n def variance(self):\n return jnp.broadcast_to(self.base_dist.variance, self.batch_shape + self.event_shape)\n\n def tree_flatten(self):\n prepend_ndim = len(self.batch_shape) - len(self.base_dist.batch_shape)\n base_dist = tree_util.tree_map(\n lambda x: promote_shapes(x, shape=(1,) * prepend_ndim + jnp.shape(x))[0],\n self.base_dist)\n base_flatten, base_aux = base_dist.tree_flatten()\n return base_flatten, (type(self.base_dist), base_aux, self.batch_shape)\n\n @classmethod\n def tree_unflatten(cls, aux_data, params):\n base_cls, base_aux, batch_shape = aux_data\n base_dist = base_cls.tree_unflatten(base_aux, params)\n prepend_shape = base_dist.batch_shape[:len(base_dist.batch_shape) - len(batch_shape)]\n return cls(base_dist, batch_shape=prepend_shape + batch_shape)\n\n\nclass ImproperUniform(Distribution):\n \"\"\"\n A helper distribution with zero :meth:`log_prob` over the `support` domain.\n\n .. note:: `sample` method is not implemented for this distribution. In autoguide and mcmc,\n initial parameters for improper sites are derived from `init_to_uniform` or `init_to_value`\n strategies.\n\n **Usage:**\n\n .. doctest::\n\n >>> from numpyro import sample\n >>> from numpyro.distributions import ImproperUniform, Normal, constraints\n >>>\n >>> def model():\n ... # ordered vector with length 10\n ... x = sample('x', ImproperUniform(constraints.ordered_vector, (), event_shape=(10,)))\n ...\n ... # real matrix with shape (3, 4)\n ... y = sample('y', ImproperUniform(constraints.real, (), event_shape=(3, 4)))\n ...\n ... # a shape-(6, 8) batch of length-5 vectors greater than 3\n ... z = sample('z', ImproperUniform(constraints.greater_than(3), (6, 8), event_shape=(5,)))\n\n If you want to set improper prior over all values greater than `a`, where `a` is\n another random variable, you might use\n\n >>> def model():\n ... a = sample('a', Normal(0, 1))\n ... x = sample('x', ImproperUniform(constraints.greater_than(a), (), event_shape=()))\n\n or if you want to reparameterize it\n\n >>> from numpyro.distributions import TransformedDistribution, transforms\n >>> from numpyro.handlers import reparam\n >>> from numpyro.infer.reparam import TransformReparam\n >>>\n >>> def model():\n ... a = sample('a', Normal(0, 1))\n ... with reparam(config={'x': TransformReparam()}):\n ... x = sample('x',\n ... TransformedDistribution(ImproperUniform(constraints.positive, (), ()),\n ... transforms.AffineTransform(a, 1)))\n\n :param ~numpyro.distributions.constraints.Constraint support: the support of this distribution.\n :param tuple batch_shape: batch shape of this distribution. It is usually safe to\n set `batch_shape=()`.\n :param tuple event_shape: event shape of this distribution.\n \"\"\"\n arg_constraints = {}\n\n def __init__(self, support, batch_shape, event_shape, validate_args=None):\n self.support = support\n super().__init__(batch_shape, event_shape, validate_args=validate_args)\n\n @validate_sample\n def log_prob(self, value):\n batch_shape = jnp.shape(value)[:jnp.ndim(value) - len(self.event_shape)]\n batch_shape = lax.broadcast_shapes(batch_shape, self.batch_shape)\n return jnp.zeros(batch_shape)\n\n def _validate_sample(self, value):\n mask = super(ImproperUniform, self)._validate_sample(value)\n batch_dim = jnp.ndim(value) - len(self.event_shape)\n if batch_dim < jnp.ndim(mask):\n mask = jnp.all(jnp.reshape(mask, jnp.shape(mask)[:batch_dim] + (-1,)), -1)\n return mask\n\n def tree_flatten(self):\n raise NotImplementedError(\n \"Cannot flattening ImproperPrior distribution for general supports. \"\n \"Please raising a feature request for your specific `support`. \"\n \"Alternatively, you can use '.mask(False)' pattern. \"\n \"For example, to define an improper prior over positive domain, \"\n \"we can use the distribution `dist.LogNormal(0, 1).mask(False)`.\")\n\n\nclass Independent(Distribution):\n \"\"\"\n Reinterprets batch dimensions of a distribution as event dims by shifting\n the batch-event dim boundary further to the left.\n\n From a practical standpoint, this is useful when changing the result of\n :meth:`log_prob`. For example, a univariate Normal distribution can be\n interpreted as a multivariate Normal with diagonal covariance:\n\n .. doctest::\n\n >>> import numpyro.distributions as dist\n >>> normal = dist.Normal(jnp.zeros(3), jnp.ones(3))\n >>> [normal.batch_shape, normal.event_shape]\n [(3,), ()]\n >>> diag_normal = dist.Independent(normal, 1)\n >>> [diag_normal.batch_shape, diag_normal.event_shape]\n [(), (3,)]\n\n :param numpyro.distribution.Distribution base_distribution: a distribution instance.\n :param int reinterpreted_batch_ndims: the number of batch dims to reinterpret as event dims.\n \"\"\"\n arg_constraints = {}\n\n def __init__(self, base_dist, reinterpreted_batch_ndims, validate_args=None):\n if reinterpreted_batch_ndims > len(base_dist.batch_shape):\n raise ValueError(\"Expected reinterpreted_batch_ndims <= len(base_distribution.batch_shape), \"\n \"actual {} vs {}\".format(reinterpreted_batch_ndims,\n len(base_dist.batch_shape)))\n shape = base_dist.batch_shape + base_dist.event_shape\n event_dim = reinterpreted_batch_ndims + len(base_dist.event_shape)\n batch_shape = shape[:len(shape) - event_dim]\n event_shape = shape[len(shape) - event_dim:]\n self.base_dist = base_dist\n self.reinterpreted_batch_ndims = reinterpreted_batch_ndims\n super(Independent, self).__init__(batch_shape, event_shape, validate_args=validate_args)\n\n @property\n def support(self):\n return self.base_dist.support\n\n @property\n def has_enumerate_support(self):\n return self.base_dist.has_enumerate_support\n\n @property\n def is_discrete(self):\n return self.base_dist.is_discrete\n\n @property\n def reparameterized_params(self):\n return self.base_dist.reparameterized_params\n\n @property\n def mean(self):\n return self.base_dist.mean\n\n @property\n def variance(self):\n return self.base_dist.variance\n\n def sample(self, key, sample_shape=()):\n return self.base_dist(rng_key=key, sample_shape=sample_shape)\n\n def log_prob(self, value):\n log_prob = self.base_dist.log_prob(value)\n return sum_rightmost(log_prob, self.reinterpreted_batch_ndims)\n\n def expand(self, batch_shape):\n base_batch_shape = batch_shape + self.event_shape[:self.reinterpreted_batch_ndims]\n return self.base_dist.expand(base_batch_shape).to_event(self.reinterpreted_batch_ndims)\n\n def tree_flatten(self):\n base_flatten, base_aux = self.base_dist.tree_flatten()\n return base_flatten, (type(self.base_dist), base_aux, self.reinterpreted_batch_ndims)\n\n @classmethod\n def tree_unflatten(cls, aux_data, params):\n base_cls, base_aux, reinterpreted_batch_ndims = aux_data\n base_dist = base_cls.tree_unflatten(base_aux, params)\n return cls(base_dist, reinterpreted_batch_ndims)\n\n\nclass MaskedDistribution(Distribution):\n \"\"\"\n Masks a distribution by a boolean array that is broadcastable to the\n distribution's :attr:`Distribution.batch_shape`.\n In the special case ``mask is False``, computation of :meth:`log_prob` , is skipped,\n and constant zero values are returned instead.\n\n :param mask: A boolean or boolean-valued array.\n :type mask: jnp.ndarray or bool\n \"\"\"\n arg_constraints = {}\n\n def __init__(self, base_dist, mask):\n if isinstance(mask, bool):\n self._mask = mask\n else:\n batch_shape = lax.broadcast_shapes(jnp.shape(mask), tuple(base_dist.batch_shape))\n if mask.shape != batch_shape:\n mask = jnp.broadcast_to(mask, batch_shape)\n if base_dist.batch_shape != batch_shape:\n base_dist = base_dist.expand(batch_shape)\n self._mask = mask.astype('bool')\n self.base_dist = base_dist\n super().__init__(base_dist.batch_shape, base_dist.event_shape)\n\n @property\n def has_enumerate_support(self):\n return self.base_dist.has_enumerate_support\n\n @property\n def is_discrete(self):\n return self.base_dist.is_discrete\n\n @property\n def support(self):\n return self.base_dist.support\n\n def sample(self, key, sample_shape=()):\n return self.base_dist(rng_key=key, sample_shape=sample_shape)\n\n def log_prob(self, value):\n if self._mask is False:\n shape = lax.broadcast_shapes(tuple(self.base_dist.batch_shape),\n jnp.shape(value)[:max(jnp.ndim(value) - len(self.event_shape), 0)])\n return jnp.zeros(shape)\n if self._mask is True:\n return self.base_dist.log_prob(value)\n return jnp.where(self._mask, self.base_dist.log_prob(value), 0.)\n\n def enumerate_support(self, expand=True):\n return self.base_dist.enumerate_support(expand=expand)\n\n @property\n def mean(self):\n return self.base_dist.mean\n\n @property\n def variance(self):\n return self.base_dist.variance\n\n def tree_flatten(self):\n base_flatten, base_aux = self.base_dist.tree_flatten()\n if isinstance(self._mask, bool):\n return base_flatten, (type(self.base_dist), base_aux, self._mask)\n else:\n return (base_flatten, self._mask), (type(self.base_dist), base_aux)\n\n @classmethod\n def tree_unflatten(cls, aux_data, params):\n if len(aux_data) == 2:\n base_flatten, mask = params\n base_cls, base_aux = aux_data\n else:\n base_flatten = params\n base_cls, base_aux, mask = aux_data\n base_dist = base_cls.tree_unflatten(base_aux, base_flatten)\n return cls(base_dist, mask)\n\n\nclass TransformedDistribution(Distribution):\n \"\"\"\n Returns a distribution instance obtained as a result of applying\n a sequence of transforms to a base distribution. For an example,\n see :class:`~numpyro.distributions.LogNormal` and\n :class:`~numpyro.distributions.HalfNormal`.\n\n :param base_distribution: the base distribution over which to apply transforms.\n :param transforms: a single transform or a list of transforms.\n :param validate_args: Whether to enable validation of distribution\n parameters and arguments to `.log_prob` method.\n \"\"\"\n arg_constraints = {}\n\n def __init__(self, base_distribution, transforms, validate_args=None):\n if isinstance(transforms, Transform):\n transforms = [transforms, ]\n elif isinstance(transforms, list):\n if not all(isinstance(t, Transform) for t in transforms):\n raise ValueError(\"transforms must be a Transform or a list of Transforms\")\n else:\n raise ValueError(\"transforms must be a Transform or list, but was {}\".format(transforms))\n # XXX: this logic will not be valid when IndependentDistribution is support;\n # in that case, it is more involved to support Transform(Indep(Transform));\n # however, we might not need to support such kind of distribution\n # and should raise an error if base_distribution is an Indep one\n if isinstance(base_distribution, TransformedDistribution):\n self.base_dist = base_distribution.base_dist\n self.transforms = base_distribution.transforms + transforms\n else:\n self.base_dist = base_distribution\n self.transforms = transforms\n # NB: here we assume that base_dist.shape == transformed_dist.shape\n # but that might not be True for some transforms such as StickBreakingTransform\n # because the event dimension is transformed from (n - 1,) to (n,).\n # Currently, we have no mechanism to fix this issue. Given that\n # this is just an edge case, we might skip this issue but need\n # to pay attention to any inference function that inspects\n # transformed distribution's shape.\n shape = base_distribution.batch_shape + base_distribution.event_shape\n event_dim = max([len(base_distribution.event_shape)] + [t.event_dim for t in transforms])\n batch_shape = shape[:len(shape) - event_dim]\n event_shape = shape[len(shape) - event_dim:]\n super(TransformedDistribution, self).__init__(batch_shape, event_shape, validate_args=validate_args)\n\n @property\n def support(self):\n domain = self.base_dist.support\n for t in self.transforms:\n t.domain = domain\n domain = t.codomain\n return domain\n\n def sample(self, key, sample_shape=()):\n x = self.base_dist(rng_key=key, sample_shape=sample_shape)\n for transform in self.transforms:\n x = transform(x)\n return x\n\n def sample_with_intermediates(self, key, sample_shape=()):\n x = self.base_dist(rng_key=key, sample_shape=sample_shape)\n intermediates = []\n for transform in self.transforms:\n x_tmp = x\n x, t_inter = transform.call_with_intermediates(x)\n intermediates.append([x_tmp, t_inter])\n return x, intermediates\n\n @validate_sample\n def log_prob(self, value, intermediates=None):\n if intermediates is not None:\n if len(intermediates) != len(self.transforms):\n raise ValueError('Intermediates array has length = {}. Expected = {}.'\n .format(len(intermediates), len(self.transforms)))\n event_dim = len(self.event_shape)\n log_prob = 0.0\n y = value\n for i, transform in enumerate(reversed(self.transforms)):\n x = transform.inv(y) if intermediates is None else intermediates[-i - 1][0]\n t_inter = None if intermediates is None else intermediates[-i - 1][1]\n t_log_det = transform.log_abs_det_jacobian(x, y, t_inter)\n log_prob = log_prob - sum_rightmost(t_log_det, event_dim - transform.event_dim)\n y = x\n\n log_prob = log_prob + sum_rightmost(self.base_dist.log_prob(y),\n event_dim - len(self.base_dist.event_shape))\n return log_prob\n\n @property\n def mean(self):\n raise NotImplementedError\n\n @property\n def variance(self):\n raise NotImplementedError\n\n def tree_flatten(self):\n raise NotImplementedError(\n \"Flatenning TransformedDistribution is only supported for some specific cases.\"\n \" Consider using `TransformReparam` to convert this distribution to the base_dist,\"\n \" which is supported in most situtations. In addition, please reach out to us with\"\n \" your usage cases.\")\n\n\nclass Unit(Distribution):\n \"\"\"\n Trivial nonnormalized distribution representing the unit type.\n\n The unit type has a single value with no data, i.e. ``value.size == 0``.\n\n This is used for :func:`numpyro.factor` statements.\n \"\"\"\n arg_constraints = {'log_factor': real}\n support = real\n\n def __init__(self, log_factor, validate_args=None):\n batch_shape = jnp.shape(log_factor)\n event_shape = (0,) # This satisfies .size == 0.\n self.log_factor = log_factor\n super(Unit, self).__init__(batch_shape, event_shape, validate_args=validate_args)\n\n def sample(self, key, sample_shape=()):\n return jnp.empty(sample_shape + self.batch_shape + self.event_shape)\n\n def log_prob(self, value):\n shape = lax.broadcast_shapes(self.batch_shape, jnp.shape(value)[:-1])\n return jnp.broadcast_to(self.log_factor, shape)\n", "path": "numpyro/distributions/distribution.py" }, { "content": "# Copyright Contributors to the Pyro project.\n# SPDX-License-Identifier: Apache-2.0\n\nfrom collections import namedtuple\nfrom functools import partial\nimport warnings\n\nimport numpy as np\n\nfrom jax import device_get, lax, random, value_and_grad\nfrom jax.flatten_util import ravel_pytree\nimport jax.numpy as jnp\n\nimport numpyro\nimport numpyro.distributions as dist\nfrom numpyro.distributions.constraints import _GreaterThan, _Interval, real, real_vector\nfrom numpyro.distributions.transforms import biject_to\nfrom numpyro.distributions.util import is_identically_one, sum_rightmost\nfrom numpyro.handlers import seed, substitute, trace\nfrom numpyro.infer.initialization import init_to_uniform, init_to_value\nfrom numpyro.util import not_jax_tracer, soft_vmap, while_loop\n\n__all__ = [\n 'find_valid_initial_params',\n 'get_potential_fn',\n 'log_density',\n 'log_likelihood',\n 'potential_energy',\n 'initialize_model',\n 'Predictive',\n]\n\nModelInfo = namedtuple('ModelInfo', ['param_info', 'potential_fn', 'postprocess_fn', 'model_trace'])\nParamInfo = namedtuple('ParamInfo', ['z', 'potential_energy', 'z_grad'])\n\n\ndef log_density(model, model_args, model_kwargs, params):\n \"\"\"\n (EXPERIMENTAL INTERFACE) Computes log of joint density for the model given\n latent values ``params``.\n\n :param model: Python callable containing NumPyro primitives.\n :param tuple model_args: args provided to the model.\n :param dict model_kwargs: kwargs provided to the model.\n :param dict params: dictionary of current parameter values keyed by site\n name.\n :return: log of joint density and a corresponding model trace\n \"\"\"\n model = substitute(model, data=params)\n model_trace = trace(model).get_trace(*model_args, **model_kwargs)\n log_joint = jnp.array(0.)\n for site in model_trace.values():\n if site['type'] == 'sample' and not isinstance(site['fn'], dist.PRNGIdentity):\n value = site['value']\n intermediates = site['intermediates']\n scale = site['scale']\n if intermediates:\n log_prob = site['fn'].log_prob(value, intermediates)\n else:\n log_prob = site['fn'].log_prob(value)\n\n if (scale is not None) and (not is_identically_one(scale)):\n log_prob = scale * log_prob\n\n log_prob = jnp.sum(log_prob)\n log_joint = log_joint + log_prob\n return log_joint, model_trace\n\n\ndef transform_fn(transforms, params, invert=False):\n \"\"\"\n (EXPERIMENTAL INTERFACE) Callable that applies a transformation from the `transforms`\n dict to values in the `params` dict and returns the transformed values keyed on\n the same names.\n\n :param transforms: Dictionary of transforms keyed by names. Names in\n `transforms` and `params` should align.\n :param params: Dictionary of arrays keyed by names.\n :param invert: Whether to apply the inverse of the transforms.\n :return: `dict` of transformed params.\n \"\"\"\n if invert:\n transforms = {k: v.inv for k, v in transforms.items()}\n return {k: transforms[k](v) if k in transforms else v\n for k, v in params.items()}\n\n\ndef constrain_fn(model, model_args, model_kwargs, params, return_deterministic=False):\n \"\"\"\n (EXPERIMENTAL INTERFACE) Gets value at each latent site in `model` given\n unconstrained parameters `params`. The `transforms` is used to transform these\n unconstrained parameters to base values of the corresponding priors in `model`.\n If a prior is a transformed distribution, the corresponding base value lies in\n the support of base distribution. Otherwise, the base value lies in the support\n of the distribution.\n\n :param model: a callable containing NumPyro primitives.\n :param tuple model_args: args provided to the model.\n :param dict model_kwargs: kwargs provided to the model.\n :param dict params: dictionary of unconstrained values keyed by site\n names.\n :param bool return_deterministic: whether to return the value of `deterministic`\n sites from the model. Defaults to `False`.\n :return: `dict` of transformed params.\n \"\"\"\n\n def substitute_fn(site):\n if site['name'] in params:\n return biject_to(site['fn'].support)(params[site['name']])\n\n substituted_model = substitute(model, substitute_fn=substitute_fn)\n model_trace = trace(substituted_model).get_trace(*model_args, **model_kwargs)\n return {k: v['value'] for k, v in model_trace.items() if (k in params) or\n (return_deterministic and (v['type'] == 'deterministic'))}\n\n\ndef _unconstrain_reparam(params, site):\n name = site['name']\n if name in params:\n p = params[name]\n support = site['fn'].support\n if support in [real, real_vector]:\n return p\n t = biject_to(support)\n value = t(p)\n\n log_det = t.log_abs_det_jacobian(p, value)\n log_det = sum_rightmost(log_det, jnp.ndim(log_det) - jnp.ndim(value) + len(site['fn'].event_shape))\n if site['scale'] is not None:\n log_det = site['scale'] * log_det\n numpyro.factor('_{}_log_det'.format(name), log_det)\n return value\n\n\ndef potential_energy(model, model_args, model_kwargs, params, enum=False):\n \"\"\"\n (EXPERIMENTAL INTERFACE) Computes potential energy of a model given unconstrained params.\n The `inv_transforms` is used to transform these unconstrained parameters to base values\n of the corresponding priors in `model`. If a prior is a transformed distribution,\n the corresponding base value lies in the support of base distribution. Otherwise,\n the base value lies in the support of the distribution.\n\n :param model: a callable containing NumPyro primitives.\n :param tuple model_args: args provided to the model.\n :param dict model_kwargs: kwargs provided to the model.\n :param dict params: unconstrained parameters of `model`.\n :param bool enum: whether to enumerate over discrete latent sites.\n :return: potential energy given unconstrained parameters.\n \"\"\"\n if enum:\n from numpyro.contrib.funsor import log_density as log_density_\n else:\n log_density_ = log_density\n\n substituted_model = substitute(model, substitute_fn=partial(_unconstrain_reparam, params))\n # no param is needed for log_density computation because we already substitute\n log_joint, model_trace = log_density_(substituted_model, model_args, model_kwargs, {})\n return - log_joint\n\n\ndef _init_to_unconstrained_value(site=None, values={}):\n if site is None:\n return partial(_init_to_unconstrained_value, values=values)\n\n\ndef find_valid_initial_params(rng_key, model,\n init_strategy=init_to_uniform,\n enum=False,\n model_args=(),\n model_kwargs=None,\n prototype_params=None):\n \"\"\"\n (EXPERIMENTAL INTERFACE) Given a model with Pyro primitives, returns an initial\n valid unconstrained value for all the parameters. This function also returns\n the corresponding potential energy, the gradients, and an\n `is_valid` flag to say whether the initial parameters are valid. Parameter values\n are considered valid if the values and the gradients for the log density have\n finite values.\n\n :param jax.random.PRNGKey rng_key: random number generator seed to\n sample from the prior. The returned `init_params` will have the\n batch shape ``rng_key.shape[:-1]``.\n :param model: Python callable containing Pyro primitives.\n :param callable init_strategy: a per-site initialization function.\n :param bool enum: whether to enumerate over discrete latent sites.\n :param tuple model_args: args provided to the model.\n :param dict model_kwargs: kwargs provided to the model.\n :param dict prototype_params: an optional prototype parameters, which is used\n to define the shape for initial parameters.\n :return: tuple of `init_params_info` and `is_valid`, where `init_params_info` is the tuple\n containing the initial params, their potential energy, and their gradients.\n \"\"\"\n model_kwargs = {} if model_kwargs is None else model_kwargs\n init_strategy = init_strategy if isinstance(init_strategy, partial) else init_strategy()\n # handle those init strategies differently to save computation\n if init_strategy.func is init_to_uniform:\n radius = init_strategy.keywords.get(\"radius\")\n init_values = {}\n elif init_strategy.func is _init_to_unconstrained_value:\n radius = 2\n init_values = init_strategy.keywords.get(\"values\")\n else:\n radius = None\n\n def cond_fn(state):\n i, _, _, is_valid = state\n return (i < 100) & (~is_valid)\n\n def body_fn(state):\n i, key, _, _ = state\n key, subkey = random.split(key)\n\n if radius is None or prototype_params is None:\n # Wrap model in a `substitute` handler to initialize from `init_loc_fn`.\n seeded_model = substitute(seed(model, subkey), substitute_fn=init_strategy)\n model_trace = trace(seeded_model).get_trace(*model_args, **model_kwargs)\n constrained_values, inv_transforms = {}, {}\n for k, v in model_trace.items():\n if v['type'] == 'sample' and not v['is_observed'] and not v['fn'].is_discrete:\n constrained_values[k] = v['value']\n inv_transforms[k] = biject_to(v['fn'].support)\n params = transform_fn(inv_transforms,\n {k: v for k, v in constrained_values.items()},\n invert=True)\n else: # this branch doesn't require tracing the model\n params = {}\n for k, v in prototype_params.items():\n if k in init_values:\n params[k] = init_values[k]\n else:\n params[k] = random.uniform(subkey, jnp.shape(v), minval=-radius, maxval=radius)\n key, subkey = random.split(key)\n\n potential_fn = partial(potential_energy, model, model_args, model_kwargs, enum=enum)\n pe, z_grad = value_and_grad(potential_fn)(params)\n z_grad_flat = ravel_pytree(z_grad)[0]\n is_valid = jnp.isfinite(pe) & jnp.all(jnp.isfinite(z_grad_flat))\n return i + 1, key, (params, pe, z_grad), is_valid\n\n def _find_valid_params(rng_key, exit_early=False):\n init_state = (0, rng_key, (prototype_params, 0., prototype_params), False)\n if exit_early and not_jax_tracer(rng_key):\n # Early return if valid params found. This is only helpful for single chain,\n # where we can avoid compiling body_fn in while_loop.\n _, _, (init_params, pe, z_grad), is_valid = init_state = body_fn(init_state)\n if not_jax_tracer(is_valid):\n if device_get(is_valid):\n return (init_params, pe, z_grad), is_valid\n\n # XXX: this requires compiling the model, so for multi-chain, we trace the model 2-times\n # even if the init_state is a valid result\n _, _, (init_params, pe, z_grad), is_valid = while_loop(cond_fn, body_fn, init_state)\n return (init_params, pe, z_grad), is_valid\n\n # Handle possible vectorization\n if rng_key.ndim == 1:\n (init_params, pe, z_grad), is_valid = _find_valid_params(rng_key, exit_early=True)\n else:\n (init_params, pe, z_grad), is_valid = lax.map(_find_valid_params, rng_key)\n return (init_params, pe, z_grad), is_valid\n\n\ndef _get_model_transforms(model, model_args=(), model_kwargs=None):\n model_kwargs = {} if model_kwargs is None else model_kwargs\n model_trace = trace(model).get_trace(*model_args, **model_kwargs)\n inv_transforms = {}\n # model code may need to be replayed in the presence of deterministic sites\n replay_model = False\n has_enumerate_support = False\n for k, v in model_trace.items():\n if v['type'] == 'sample' and not v['is_observed']:\n if v['fn'].is_discrete:\n has_enumerate_support = True\n if not v['fn'].has_enumerate_support:\n raise RuntimeError(\"MCMC only supports continuous sites or discrete sites \"\n f\"with enumerate support, but got {type(v['fn']).__name__}.\")\n else:\n support = v['fn'].support\n inv_transforms[k] = biject_to(support)\n # XXX: the following code filters out most situations with dynamic supports\n args = ()\n if isinstance(support, _GreaterThan):\n args = ('lower_bound',)\n elif isinstance(support, _Interval):\n args = ('lower_bound', 'upper_bound')\n for arg in args:\n if not isinstance(getattr(support, arg), (int, float)):\n replay_model = True\n elif v['type'] == 'deterministic':\n replay_model = True\n return inv_transforms, replay_model, has_enumerate_support, model_trace\n\n\ndef get_potential_fn(model, inv_transforms, enum=False, replay_model=False,\n dynamic_args=False, model_args=(), model_kwargs=None):\n \"\"\"\n (EXPERIMENTAL INTERFACE) Given a model with Pyro primitives, returns a\n function which, given unconstrained parameters, evaluates the potential\n energy (negative log joint density). In addition, this returns a\n function to transform unconstrained values at sample sites to constrained\n values within their respective support.\n\n :param model: Python callable containing Pyro primitives.\n :param dict inv_transforms: dictionary of transforms keyed by names.\n :param bool enum: whether to enumerate over discrete latent sites.\n :param bool replay_model: whether we need to replay model in\n `postprocess_fn` to obtain `deterministic` sites.\n :param bool dynamic_args: if `True`, the `potential_fn` and\n `constraints_fn` are themselves dependent on model arguments.\n When provided a `*model_args, **model_kwargs`, they return\n `potential_fn` and `constraints_fn` callables, respectively.\n :param tuple model_args: args provided to the model.\n :param dict model_kwargs: kwargs provided to the model.\n :return: tuple of (`potential_fn`, `postprocess_fn`). The latter is used\n to constrain unconstrained samples (e.g. those returned by HMC)\n to values that lie within the site's support, and return values at\n `deterministic` sites in the model.\n \"\"\"\n if dynamic_args:\n def potential_fn(*args, **kwargs):\n return partial(potential_energy, model, args, kwargs, enum=enum)\n\n def postprocess_fn(*args, **kwargs):\n if replay_model:\n # XXX: we seed to sample discrete sites (but not collect them)\n model_ = seed(model.fn, 0) if enum else model\n return partial(constrain_fn, model_, args, kwargs, return_deterministic=True)\n else:\n return partial(transform_fn, inv_transforms)\n else:\n model_kwargs = {} if model_kwargs is None else model_kwargs\n potential_fn = partial(potential_energy, model, model_args, model_kwargs, enum=enum)\n if replay_model:\n model_ = seed(model.fn, 0) if enum else model\n postprocess_fn = partial(constrain_fn, model_, model_args, model_kwargs,\n return_deterministic=True)\n else:\n postprocess_fn = partial(transform_fn, inv_transforms)\n\n return potential_fn, postprocess_fn\n\n\ndef _guess_max_plate_nesting(model_trace):\n \"\"\"\n Guesses max_plate_nesting by using model trace.\n This optimistically assumes static model\n structure.\n \"\"\"\n sites = [site for site in model_trace.values()\n if site[\"type\"] == \"sample\"]\n\n dims = [frame.dim\n for site in sites\n for frame in site[\"cond_indep_stack\"]\n if frame.dim is not None]\n max_plate_nesting = -min(dims) if dims else 0\n return max_plate_nesting\n\n\ndef initialize_model(rng_key, model,\n init_strategy=init_to_uniform,\n dynamic_args=False,\n model_args=(),\n model_kwargs=None):\n \"\"\"\n (EXPERIMENTAL INTERFACE) Helper function that calls :func:`~numpyro.infer.util.get_potential_fn`\n and :func:`~numpyro.infer.util.find_valid_initial_params` under the hood\n to return a tuple of (`init_params_info`, `potential_fn`, `postprocess_fn`, `model_trace`).\n\n :param jax.random.PRNGKey rng_key: random number generator seed to\n sample from the prior. The returned `init_params` will have the\n batch shape ``rng_key.shape[:-1]``.\n :param model: Python callable containing Pyro primitives.\n :param callable init_strategy: a per-site initialization function.\n See :ref:`init_strategy` section for available functions.\n :param bool dynamic_args: if `True`, the `potential_fn` and\n `constraints_fn` are themselves dependent on model arguments.\n When provided a `*model_args, **model_kwargs`, they return\n `potential_fn` and `constraints_fn` callables, respectively.\n :param tuple model_args: args provided to the model.\n :param dict model_kwargs: kwargs provided to the model.\n :return: a namedtupe `ModelInfo` which contains the fields\n (`param_info`, `potential_fn`, `postprocess_fn`, `model_trace`), where\n `param_info` is a namedtuple `ParamInfo` containing values from the prior\n used to initiate MCMC, their corresponding potential energy, and their gradients;\n `postprocess_fn` is a callable that uses inverse transforms\n to convert unconstrained HMC samples to constrained values that\n lie within the site's support, in addition to returning values\n at `deterministic` sites in the model.\n \"\"\"\n model_kwargs = {} if model_kwargs is None else model_kwargs\n substituted_model = substitute(seed(model, rng_key if jnp.ndim(rng_key) == 1 else rng_key[0]),\n substitute_fn=init_strategy)\n inv_transforms, replay_model, has_enumerate_support, model_trace = _get_model_transforms(\n substituted_model, model_args, model_kwargs)\n constrained_values = {k: v['value'] for k, v in model_trace.items()\n if v['type'] == 'sample' and not v['is_observed']\n and not v['fn'].is_discrete}\n\n if has_enumerate_support:\n from numpyro.contrib.funsor import config_enumerate, enum\n\n if not isinstance(model, enum):\n max_plate_nesting = _guess_max_plate_nesting(model_trace)\n model = enum(config_enumerate(model), -max_plate_nesting - 1)\n\n potential_fn, postprocess_fn = get_potential_fn(model,\n inv_transforms,\n replay_model=replay_model,\n enum=has_enumerate_support,\n dynamic_args=dynamic_args,\n model_args=model_args,\n model_kwargs=model_kwargs)\n\n init_strategy = init_strategy if isinstance(init_strategy, partial) else init_strategy()\n if (init_strategy.func is init_to_value) and not replay_model:\n init_values = init_strategy.keywords.get(\"values\")\n unconstrained_values = transform_fn(inv_transforms, init_values, invert=True)\n init_strategy = _init_to_unconstrained_value(values=unconstrained_values)\n prototype_params = transform_fn(inv_transforms, constrained_values, invert=True)\n (init_params, pe, grad), is_valid = find_valid_initial_params(rng_key, model,\n init_strategy=init_strategy,\n enum=has_enumerate_support,\n model_args=model_args,\n model_kwargs=model_kwargs,\n prototype_params=prototype_params)\n\n if not_jax_tracer(is_valid):\n if device_get(~jnp.all(is_valid)):\n with numpyro.validation_enabled(), trace() as tr:\n # validate parameters\n substituted_model(*model_args, **model_kwargs)\n # validate values\n for site in tr.values():\n if site['type'] == 'sample':\n with warnings.catch_warnings(record=True) as ws:\n site['fn']._validate_sample(site['value'])\n if len(ws) > 0:\n for w in ws:\n # at site information to the warning message\n w.message.args = (\"Site {}: {}\".format(site[\"name\"], w.message.args[0]),) \\\n + w.message.args[1:]\n warnings.showwarning(w.message, w.category, w.filename, w.lineno,\n file=w.file, line=w.line)\n raise RuntimeError(\"Cannot find valid initial parameters. Please check your model again.\")\n return ModelInfo(ParamInfo(init_params, pe, grad), potential_fn, postprocess_fn, model_trace)\n\n\ndef _predictive(rng_key, model, posterior_samples, batch_shape, return_sites=None,\n parallel=True, model_args=(), model_kwargs={}):\n\n def single_prediction(val):\n rng_key, samples = val\n model_trace = trace(seed(substitute(model, samples), rng_key)).get_trace(\n *model_args, **model_kwargs)\n if return_sites is not None:\n if return_sites == '':\n sites = {k for k, site in model_trace.items() if site['type'] != 'plate'}\n else:\n sites = return_sites\n else:\n sites = {k for k, site in model_trace.items()\n if (site['type'] == 'sample' and k not in samples) or (site['type'] == 'deterministic')}\n return {name: site['value'] for name, site in model_trace.items() if name in sites}\n\n num_samples = int(np.prod(batch_shape))\n if num_samples > 1:\n rng_key = random.split(rng_key, num_samples)\n rng_key = rng_key.reshape(batch_shape + (2,))\n chunk_size = num_samples if parallel else 1\n return soft_vmap(single_prediction, (rng_key, posterior_samples), len(batch_shape), chunk_size)\n\n\nclass Predictive(object):\n \"\"\"\n This class is used to construct predictive distribution. The predictive distribution is obtained\n by running model conditioned on latent samples from `posterior_samples`.\n\n .. warning::\n The interface for the `Predictive` class is experimental, and\n might change in the future.\n\n :param model: Python callable containing Pyro primitives.\n :param dict posterior_samples: dictionary of samples from the posterior.\n :param callable guide: optional guide to get posterior samples of sites not present\n in `posterior_samples`.\n :param dict params: dictionary of values for param sites of model/guide.\n :param int num_samples: number of samples\n :param list return_sites: sites to return; by default only sample sites not present\n in `posterior_samples` are returned.\n :param bool parallel: whether to predict in parallel using JAX vectorized map :func:`jax.vmap`.\n Defaults to False.\n :param batch_ndims: the number of batch dimensions in posterior samples. Some usages:\n\n + set `batch_ndims=0` to get prediction for 1 single sample\n\n + set `batch_ndims=1` to get prediction for `posterior_samples`\n with shapes `(num_samples x ...)`\n\n + set `batch_ndims=2` to get prediction for `posterior_samples`\n with shapes `(num_chains x N x ...)`. Note that if `num_samples`\n argument is not None, its value should be equal to `num_chains x N`.\n\n :return: dict of samples from the predictive distribution.\n \"\"\"\n\n def __init__(self, model, posterior_samples=None, guide=None, params=None, num_samples=None,\n return_sites=None, parallel=False, batch_ndims=1):\n if posterior_samples is None and num_samples is None:\n raise ValueError(\"Either posterior_samples or num_samples must be specified.\")\n\n posterior_samples = {} if posterior_samples is None else posterior_samples\n\n prototype_site = batch_shape = batch_size = None\n for name, sample in posterior_samples.items():\n if batch_shape is not None and sample.shape[:batch_ndims] != batch_shape:\n raise ValueError(f\"Batch shapes at site {name} and {prototype_site} \"\n f\"should be the same, but got \"\n f\"{sample.shape[:batch_ndims]} and {batch_shape}\")\n else:\n prototype_site = name\n batch_shape = sample.shape[:batch_ndims]\n batch_size = int(np.prod(batch_shape))\n if (num_samples is not None) and (num_samples != batch_size):\n warnings.warn(\"Sample's batch dimension size {} is different from the \"\n \"provided {} num_samples argument. Defaulting to {}.\"\n .format(batch_size, num_samples, batch_size), UserWarning)\n num_samples = batch_size\n\n if num_samples is None:\n raise ValueError(\"No sample sites in posterior samples to infer `num_samples`.\")\n\n if batch_shape is None:\n batch_shape = (1,) * (batch_ndims - 1) + (num_samples,)\n\n if return_sites is not None:\n assert isinstance(return_sites, (list, tuple, set))\n\n self.model = model\n self.posterior_samples = {} if posterior_samples is None else posterior_samples\n self.num_samples = num_samples\n self.guide = guide\n self.params = {} if params is None else params\n self.return_sites = return_sites\n self.parallel = parallel\n self.batch_ndims = batch_ndims\n self._batch_shape = batch_shape\n\n def __call__(self, rng_key, *args, **kwargs):\n \"\"\"\n Returns dict of samples from the predictive distribution. By default, only sample sites not\n contained in `posterior_samples` are returned. This can be modified by changing the\n `return_sites` keyword argument of this :class:`Predictive` instance.\n\n :param jax.random.PRNGKey rng_key: random key to draw samples.\n :param args: model arguments.\n :param kwargs: model kwargs.\n \"\"\"\n posterior_samples = self.posterior_samples\n if self.guide is not None:\n rng_key, guide_rng_key = random.split(rng_key)\n # use return_sites='' as a special signal to return all sites\n guide = substitute(self.guide, self.params)\n posterior_samples = _predictive(guide_rng_key, guide, posterior_samples,\n self._batch_shape, return_sites='', parallel=self.parallel,\n model_args=args, model_kwargs=kwargs)\n model = substitute(self.model, self.params)\n return _predictive(rng_key, model, posterior_samples, self._batch_shape,\n return_sites=self.return_sites, parallel=self.parallel,\n model_args=args, model_kwargs=kwargs)\n\n\ndef log_likelihood(model, posterior_samples, *args, parallel=False, batch_ndims=1, **kwargs):\n \"\"\"\n (EXPERIMENTAL INTERFACE) Returns log likelihood at observation nodes of model,\n given samples of all latent variables.\n\n :param model: Python callable containing Pyro primitives.\n :param dict posterior_samples: dictionary of samples from the posterior.\n :param args: model arguments.\n :param batch_ndims: the number of batch dimensions in posterior samples. Some usages:\n\n + set `batch_ndims=0` to get prediction for 1 single sample\n\n + set `batch_ndims=1` to get prediction for `posterior_samples`\n with shapes `(num_samples x ...)`\n\n + set `batch_ndims=2` to get prediction for `posterior_samples`\n with shapes `(num_chains x N x ...)`\n\n :param kwargs: model kwargs.\n :return: dict of log likelihoods at observation sites.\n \"\"\"\n\n def single_loglik(samples):\n substituted_model = substitute(model, samples) if isinstance(samples, dict) else model\n model_trace = trace(substituted_model).get_trace(*args, **kwargs)\n return {name: site['fn'].log_prob(site['value']) for name, site in model_trace.items()\n if site['type'] == 'sample' and site['is_observed']}\n\n prototype_site = batch_shape = None\n for name, sample in posterior_samples.items():\n if batch_shape is not None and sample.shape[:batch_ndims] != batch_shape:\n raise ValueError(f\"Batch shapes at site {name} and {prototype_site} \"\n f\"should be the same, but got \"\n f\"{sample.shape[:batch_ndims]} and {batch_shape}\")\n else:\n prototype_site = name\n batch_shape = sample.shape[:batch_ndims]\n\n if batch_shape is None: # posterior_samples is an empty dict\n batch_shape = (1,) * batch_ndims\n posterior_samples = np.zeros(batch_shape)\n\n batch_size = int(np.prod(batch_shape))\n chunk_size = batch_size if parallel else 1\n return soft_vmap(single_loglik, posterior_samples, len(batch_shape), chunk_size)\n", "path": "numpyro/infer/util.py" } ]
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)