code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def extract_function_from_file(content: str, function_name: str) -> Tuple[Callable]: """Extract a function object from a downloaded file.""" spec = importlib.util.spec_from_loader( "outlines_function", loader=None, origin="github" ) if spec is not None: module = importlib.util.module_fr...
Extract a function object from a downloaded file.
extract_function_from_file
python
dottxt-ai/outlines
outlines/function.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/function.py
Apache-2.0
def read_grammar(grammar_file_name, base_grammar_path=GRAMMAR_PATH): """Read grammar file from default grammar path""" full_path = base_grammar_path / grammar_file_name with open(full_path) as file: return file.read()
Read grammar file from default grammar path
read_grammar
python
dottxt-ai/outlines
outlines/grammars.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/grammars.py
Apache-2.0
def __call__( self, next_token_logits: "torch.DoubleTensor", sequence_weights: "torch.DoubleTensor", _, ) -> "torch.DoubleTensor": """Call the greedy sampler. Parameters ---------- next_token_logits A tensor of shape ``(n_seqs, vocab_size,...
Call the greedy sampler. Parameters ---------- next_token_logits A tensor of shape ``(n_seqs, vocab_size,)`` that represents the probability distribution of the next token over the vocabulary. sequence_weights A tensor of shape ``(n_seqs,)`` that repr...
__call__
python
dottxt-ai/outlines
outlines/samplers.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/samplers.py
Apache-2.0
def __call__( self, next_token_logits: "torch.DoubleTensor", sequence_weights: "torch.DoubleTensor", rng: "torch.Generator", ) -> Tuple["torch.DoubleTensor", "torch.DoubleTensor", "torch.DoubleTensor"]: """Call the multinomial sampler. Parameters ---------- ...
Call the multinomial sampler. Parameters ---------- next_token_logits A tensor of shape ``(n_seqs, vocab_size,)`` that represents the probability distribution of the next token over the vocabulary. sequence_weights A tensor of shape ``(n_seqs,)`` that...
__call__
python
dottxt-ai/outlines
outlines/samplers.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/samplers.py
Apache-2.0
def keep_top_k_logits(k: int) -> Callable[["torch.Tensor"], "torch.Tensor"]: """Build a function that masks logits values smaller than the top `k` ones. Parameters ---------- k The ranking below which logit values are replaced by `-math.inf`. """ import torch if not isinstance(k, ...
Build a function that masks logits values smaller than the top `k` ones. Parameters ---------- k The ranking below which logit values are replaced by `-math.inf`.
keep_top_k_logits
python
dottxt-ai/outlines
outlines/samplers.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/samplers.py
Apache-2.0
def keep_top_p_logits(p: float) -> Callable[["torch.Tensor"], "torch.Tensor"]: """Build a function that masks the lowest probability tokens whose cumulative probability is below a certain threshold. Parameters ---------- p The value of the threshold. We keep the highest probability tokens w...
Build a function that masks the lowest probability tokens whose cumulative probability is below a certain threshold. Parameters ---------- p The value of the threshold. We keep the highest probability tokens whose cumulative distribution is greater than or equal to `p` and mask the ...
keep_top_p_logits
python
dottxt-ai/outlines
outlines/samplers.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/samplers.py
Apache-2.0
def rescale_logits(temperature: float) -> Callable[["torch.Tensor"], "torch.Tensor"]: """Build a function that rescales the token probabilities exponentially. Parameters ---------- temperature The value by which we rescale the logits. """ if not isinstance(temperature, float) or tempe...
Build a function that rescales the token probabilities exponentially. Parameters ---------- temperature The value by which we rescale the logits.
rescale_logits
python
dottxt-ai/outlines
outlines/samplers.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/samplers.py
Apache-2.0
def __call__( self, next_token_logits: "torch.DoubleTensor", sequence_weights: "torch.DoubleTensor", _, ) -> Tuple["torch.DoubleTensor", "torch.DoubleTensor", "torch.DoubleTensor"]: """Call the beam search sampler. Parameters ---------- next_token_log...
Call the beam search sampler. Parameters ---------- next_token_logits A tensor of shape ``(n_seqs, vocab_size,)`` that represents the probability distribution of the next token over the vocabulary. sequence_weights A tensor of shape ``(n_seqs,)`` that...
__call__
python
dottxt-ai/outlines
outlines/samplers.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/samplers.py
Apache-2.0
def __call__(self, *args, **kwargs) -> str: """Render and return the template. Returns ------- The rendered template as a Python ``str``. """ if self.signature is not None: bound_arguments = self.signature.bind(*args, **kwargs) bound_arguments.ap...
Render and return the template. Returns ------- The rendered template as a Python ``str``.
__call__
python
dottxt-ai/outlines
outlines/templates.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/templates.py
Apache-2.0
def from_file(cls, path: Path, filters: Dict[str, Callable] = {}): """Create a `Template` instance from a file containing a Jinja template. Note: This method does not allow to include and inheritance to reference files that are outside the folder or subfolders of the file given to `from_file`. ...
Create a `Template` instance from a file containing a Jinja template. Note: This method does not allow to include and inheritance to reference files that are outside the folder or subfolders of the file given to `from_file`. Parameters ---------- path : Path The pat...
from_file
python
dottxt-ai/outlines
outlines/templates.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/templates.py
Apache-2.0
def prompt( fn: Optional[Callable] = None, filters: Dict[str, Callable] = {}, ) -> Callable: """Decorate a function that contains a prompt template. This allows to define prompts in the docstring of a function and simplify their manipulation by providing some degree of encapsulation. It uses the `r...
Decorate a function that contains a prompt template. This allows to define prompts in the docstring of a function and simplify their manipulation by providing some degree of encapsulation. It uses the `render` function internally to render templates. ```pycon >>> import outlines >>> >>> @o...
prompt
python
dottxt-ai/outlines
outlines/templates.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/templates.py
Apache-2.0
def create_jinja_env( loader: Optional[jinja2.BaseLoader], filters: Dict[str, Callable] ) -> jinja2.Environment: """Create a new Jinja environment. The Jinja environment is loaded with a set of pre-defined filters: - `name`: get the name of a function - `description`: get a function's docstring ...
Create a new Jinja environment. The Jinja environment is loaded with a set of pre-defined filters: - `name`: get the name of a function - `description`: get a function's docstring - `source`: get a function's source code - `signature`: get a function's signature - `args`: get a function's argum...
create_jinja_env
python
dottxt-ai/outlines
outlines/templates.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/templates.py
Apache-2.0
def get_fn_args(fn: Callable): """Returns the arguments of a function with annotations and default values if provided.""" if not callable(fn): raise TypeError("The `args` filter only applies to callables.") arg_str_list = [] signature = inspect.signature(fn) arg_str_list = [str(param) for p...
Returns the arguments of a function with annotations and default values if provided.
get_fn_args
python
dottxt-ai/outlines
outlines/templates.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/templates.py
Apache-2.0
def get_fn_description(fn: Callable): """Returns the first line of a callable's docstring.""" if not callable(fn): raise TypeError("The `description` filter only applies to callables.") docstring = inspect.getdoc(fn) if docstring is None: description = "" else: description =...
Returns the first line of a callable's docstring.
get_fn_description
python
dottxt-ai/outlines
outlines/templates.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/templates.py
Apache-2.0
def get_fn_source(fn: Callable): """Return the source code of a callable.""" if not callable(fn): raise TypeError("The `source` filter only applies to callables.") source = textwrap.dedent(inspect.getsource(fn)) re_search = re.search(re.compile(r"(\bdef\b.*)", re.DOTALL), source) if re_sear...
Return the source code of a callable.
get_fn_source
python
dottxt-ai/outlines
outlines/templates.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/templates.py
Apache-2.0
def get_schema_pydantic(model: Type[pydantic.BaseModel]): """Return the schema of a Pydantic model.""" if not isinstance(model, type(pydantic.BaseModel)): raise TypeError("The `schema` filter only applies to Pydantic models.") if hasattr(model, "model_json_schema"): def_key = "$defs" ...
Return the schema of a Pydantic model.
get_schema_pydantic
python
dottxt-ai/outlines
outlines/templates.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/templates.py
Apache-2.0
def parse_pydantic_schema(raw_schema, definitions): """Parse the output of `Basemodel.[schema|model_json_schema]()`. This recursively follows the references to other schemas in case of nested models. Other schemas are stored under the "definitions" key in the schema of the top-level model. """ ...
Parse the output of `Basemodel.[schema|model_json_schema]()`. This recursively follows the references to other schemas in case of nested models. Other schemas are stored under the "definitions" key in the schema of the top-level model.
parse_pydantic_schema
python
dottxt-ai/outlines
outlines/templates.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/templates.py
Apache-2.0
def __init__(self, tokenizer: "Tokenizer"): """Initialize the generation guide. model The logit generator used to generate the next token. """ self.eos_token_id = tokenizer.eos_token_id self.vocabulary = tokenizer.vocabulary.values()
Initialize the generation guide. model The logit generator used to generate the next token.
__init__
python
dottxt-ai/outlines
outlines/fsm/guide.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/fsm/guide.py
Apache-2.0
def __init__(self, cfg_string: str, tokenizer): """ Construct the PartialLark parser and set the empty initial_state (PartialParserState) """ warnings.warn( "Outlines' public *community-contributed* CFG structured generation is experimental. " "Please review https...
Construct the PartialLark parser and set the empty initial_state (PartialParserState)
__init__
python
dottxt-ai/outlines
outlines/fsm/guide.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/fsm/guide.py
Apache-2.0
def get_next_instruction(self, state: CFGState) -> Instruction: """Return the next instruction for guided generation. Current lazy approach: - For each token in the vocabulary - create a copy of the parsers state - add the tokens to the parsers input text - if vali...
Return the next instruction for guided generation. Current lazy approach: - For each token in the vocabulary - create a copy of the parsers state - add the tokens to the parsers input text - if valid, add token to returned tokens Further refinements are necessary ...
get_next_instruction
python
dottxt-ai/outlines
outlines/fsm/guide.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/fsm/guide.py
Apache-2.0
def iter_valid_token_ids( self, state: CFGState, candidate_token_ids: list ) -> Generator[int, None, None]: """ Iterate over the given token_ids and yield those that are valid for the current parser state. Parameters ---------- parser_state The current st...
Iterate over the given token_ids and yield those that are valid for the current parser state. Parameters ---------- parser_state The current state of the parser, or None if complete. token_ids The list of token ids to check for validity. Yields ...
iter_valid_token_ids
python
dottxt-ai/outlines
outlines/fsm/guide.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/fsm/guide.py
Apache-2.0
def get_next_state(self, state: CFGState, token_id: int) -> CFGState: """ Update the state of the guide. Decode the token_id, and calculate the new parser_state with the token applied. Parameters ---------- state The guides current PartialParserState, or None...
Update the state of the guide. Decode the token_id, and calculate the new parser_state with the token applied. Parameters ---------- state The guides current PartialParserState, or None if complete token_id The id of the token that was just gener...
get_next_state
python
dottxt-ai/outlines
outlines/fsm/guide.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/fsm/guide.py
Apache-2.0
def _get_parser_state_token_applied( self, state: CFGState, token_id: int ) -> PartialParserState: """ Don't mutate `parser_state`, copy to protect Get the token string - if first token in generation: tokenizer.decode (no leading whitespace) - else: normalized (w...
Don't mutate `parser_state`, copy to protect Get the token string - if first token in generation: tokenizer.decode (no leading whitespace) - else: normalized (with possibly leading whitespace) Don't allow empty ("") tokens, raise ValueError
_get_parser_state_token_applied
python
dottxt-ai/outlines
outlines/fsm/guide.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/fsm/guide.py
Apache-2.0
def convert_json_schema_to_str(json_schema: Union[dict, str, Type[BaseModel]]) -> str: """Convert a JSON schema to a string. Parameters ---------- json_schema The JSON schema. Returns ------- str The JSON schema converted to a string. Raises ------ ValueError ...
Convert a JSON schema to a string. Parameters ---------- json_schema The JSON schema. Returns ------- str The JSON schema converted to a string. Raises ------ ValueError If the schema is not a dictionary, a string or a Pydantic class.
convert_json_schema_to_str
python
dottxt-ai/outlines
outlines/fsm/json_schema.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/fsm/json_schema.py
Apache-2.0
def get_schema_from_signature(fn: Callable) -> dict: """Turn a function signature into a JSON schema. Every JSON object valid to the output JSON Schema can be passed to `fn` using the ** unpacking syntax. """ signature = inspect.signature(fn) arguments = {} for name, arg in signature.param...
Turn a function signature into a JSON schema. Every JSON object valid to the output JSON Schema can be passed to `fn` using the ** unpacking syntax.
get_schema_from_signature
python
dottxt-ai/outlines
outlines/fsm/json_schema.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/fsm/json_schema.py
Apache-2.0
def _compute_maps( self, ): """Compute state transition and symbols-to-states maps.""" self._reverse_shifts = {} self._symbols_to_states = {} parse_table = self.parser.parser.parse_table for from_state, symbols_to_ops in parse_table.states.items(): for s...
Compute state transition and symbols-to-states maps.
_compute_maps
python
dottxt-ai/outlines
outlines/fsm/parsing.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/fsm/parsing.py
Apache-2.0
def _compute_termset_fsm_info(self): """Collect and return information about terminal symbol sets and their FSMs. Terminal symbol sets (or "termsets") are ordered sequences of terminal symbols that are used by each parser state. Associated with each is a collection of FSMs for each ter...
Collect and return information about terminal symbol sets and their FSMs. Terminal symbol sets (or "termsets") are ordered sequences of terminal symbols that are used by each parser state. Associated with each is a collection of FSMs for each terminal and a single parse state FSM that is ...
_compute_termset_fsm_info
python
dottxt-ai/outlines
outlines/fsm/parsing.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/fsm/parsing.py
Apache-2.0
def feed_token_no_stack(self, token, is_end=False): """ This is a copy of `ParserState.feed_token` with all the value stack steps removed. Since we're not exactly parsing in order to obtain a CST or anything similar, we can avoid the growing expense of tracking the parse tree. ...
This is a copy of `ParserState.feed_token` with all the value stack steps removed. Since we're not exactly parsing in order to obtain a CST or anything similar, we can avoid the growing expense of tracking the parse tree.
feed_token_no_stack
python
dottxt-ai/outlines
outlines/fsm/parsing.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/fsm/parsing.py
Apache-2.0
def accepts(self): """ Adapted from https://github.com/lark-parser/lark/blob/be542c2ff6d968817df019b8bf03f37b3111c08c/lark/parsers/lalr_interactive_parser.py#L95 Returns the set of possible tokens that will advance the parser into a new valid state. """ accepts = set() co...
Adapted from https://github.com/lark-parser/lark/blob/be542c2ff6d968817df019b8bf03f37b3111c08c/lark/parsers/lalr_interactive_parser.py#L95 Returns the set of possible tokens that will advance the parser into a new valid state.
accepts
python
dottxt-ai/outlines
outlines/fsm/parsing.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/fsm/parsing.py
Apache-2.0
def get_terminals_info( self, fsm_state_seq ) -> Tuple[Tuple[PartialTerminalInfo, ...], Tuple[PartialTerminalInfo, ...]]: """Get the possible terminal symbols for an FSM state sequence.""" terminals_and_info: Tuple[PartialTerminalInfo, ...] = () final_terminals_and_info: Tuple[Partia...
Get the possible terminal symbols for an FSM state sequence.
get_terminals_info
python
dottxt-ai/outlines
outlines/fsm/parsing.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/fsm/parsing.py
Apache-2.0
def match(self, text, pos, last_fsm_state_seq: Optional[Tuple[int, ...]] = None): """Determine an FSM match over `text` starting at `pos` and continuing `last_fsm_state_seq`.""" start_pos = pos if last_fsm_state_seq: assert len(last_fsm_state_seq) > 1 start_pos += len(l...
Determine an FSM match over `text` starting at `pos` and continuing `last_fsm_state_seq`.
match
python
dottxt-ai/outlines
outlines/fsm/parsing.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/fsm/parsing.py
Apache-2.0
def terminals_to_fsms(lp: PartialLark) -> Dict[str, FSM]: """Construct a ``dict`` mapping terminal symbol names to their finite state machines.""" symbol_names_and_fsms = {} for terminal in lp.terminals: pattern = interegular.parse_pattern(terminal.pattern.to_regexp()) # TODO: Use `pyparser...
Construct a ``dict`` mapping terminal symbol names to their finite state machines.
terminals_to_fsms
python
dottxt-ai/outlines
outlines/fsm/parsing.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/fsm/parsing.py
Apache-2.0
def fsm_union( fsms: Sequence[FSM], ) -> Tuple[FSM, Dict[int, Tuple[Set[Tuple[int, int]], Set[int], Dict[int, Set[int]]]]]: """Construct an FSM representing the union of the FSMs in `fsms`. This is an updated version of `interegular.fsm.FSM.union` made to return an extra map of component FSMs to the se...
Construct an FSM representing the union of the FSMs in `fsms`. This is an updated version of `interegular.fsm.FSM.union` made to return an extra map of component FSMs to the sets of state transitions that correspond to them in the new FSM.
fsm_union
python
dottxt-ai/outlines
outlines/fsm/parsing.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/fsm/parsing.py
Apache-2.0
def get_sub_fsms_from_seq( state_seq: Sequence[int], fsms_to_trans_finals: Dict[ int, Tuple[Set[Tuple[int, int]], Set[int], Dict[int, Set[int]]] ], ) -> Generator[Tuple[int, bool, bool], None, None]: """Get the indices of the sub-FSMs in `fsm` that could have matched the state sequence `state_se...
Get the indices of the sub-FSMs in `fsm` that could have matched the state sequence `state_seq`. Parameters ---------- state_seq A state sequence. fsms_to_trans_finals A map from FSM indices to tuples containing sets of their state transitions and sets of the final/accept states...
get_sub_fsms_from_seq
python
dottxt-ai/outlines
outlines/fsm/parsing.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/fsm/parsing.py
Apache-2.0
def get_generated_token_ids( self, prompt_token_ids: "torch.Tensor", token_ids: "torch.Tensor", ) -> List["torch.Tensor"]: """Get the tokens generated so far. Parameters ---------- prompt_token_ids Tensor that contains the token ids of the sequenc...
Get the tokens generated so far. Parameters ---------- prompt_token_ids Tensor that contains the token ids of the sequences' prompts. token_ids The generated token ids. Returns ------- A tensor that contains the token ids that have been g...
get_generated_token_ids
python
dottxt-ai/outlines
outlines/generate/api.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/generate/api.py
Apache-2.0
def is_stop_sequence_found( self, generated_sequences: List[str], stop_sequences: List[str] ) -> bool: """Determine whether one of the stop sequences has been generated. Parameters ---------- generated_sequences The list of sequences generated so far. sto...
Determine whether one of the stop sequences has been generated. Parameters ---------- generated_sequences The list of sequences generated so far. stop_sequences The list that contains the sequence which stop the generation when found. Returns...
is_stop_sequence_found
python
dottxt-ai/outlines
outlines/generate/api.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/generate/api.py
Apache-2.0
def strip_stop_sequences( self, sequence: str, stop_sequences: Optional[List[str]] ) -> str: """Remove the stop sequences from the generated sequences. Parameters ---------- sequence One of the generated sequences. stop_sequences The list that...
Remove the stop sequences from the generated sequences. Parameters ---------- sequence One of the generated sequences. stop_sequences The list that contains the sequence which stop the generation when found.
strip_stop_sequences
python
dottxt-ai/outlines
outlines/generate/api.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/generate/api.py
Apache-2.0
def __call__( self, prompts: Union[str, List[str]], max_tokens: Optional[int] = None, stop_at: Optional[Union[str, List[str]]] = None, rng: Optional["torch.Generator"] = None, ) -> Union[FormattedOutput, List[FormattedOutput], List[List[FormattedOutput]]]: """Generate...
Generate the full text sequence. Since `SequenceGenerator.stream` calls the tokenizer at every step this method loops over the generator returned by `sequence_generator` itself so the tokenizer is called only once after all token ids have been generated. Parameters ----...
__call__
python
dottxt-ai/outlines
outlines/generate/api.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/generate/api.py
Apache-2.0
def stream( self, prompts: Union[str, List[str]], max_tokens: Optional[int] = None, stop_at: Optional[Union[str, List[str]]] = None, rng: Optional["torch.Generator"] = None, ) -> Iterator[Union[List[str], str, List[List[str]]]]: """Generate the text sequence one token...
Generate the text sequence one token at a time. Since `Tokenizer.decode` strips the whitespaces from the tokens we have no choice but to decode the generated token ids at each step and compare the current decoded strings to the previously decoded strings. Parameters ---------- ...
stream
python
dottxt-ai/outlines
outlines/generate/api.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/generate/api.py
Apache-2.0
def _format(self, sequences): """Apply formatting to every string in a completion.""" if isinstance(sequences, list): return [self._format(sequence) for sequence in sequences] else: return self.format_sequence(sequences)
Apply formatting to every string in a completion.
_format
python
dottxt-ai/outlines
outlines/generate/api.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/generate/api.py
Apache-2.0
def __call__( self, prompts: Union[str, List[str]], max_tokens: Optional[int] = None, stop_at: Optional[Union[str, List[str]]] = None, seed: Optional[int] = None, **model_specific_params, ): """Generate text from a prompt of list of prompts.""" genera...
Generate text from a prompt of list of prompts.
__call__
python
dottxt-ai/outlines
outlines/generate/api.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/generate/api.py
Apache-2.0
def stream( self, prompts: Union[str, List[str]], max_tokens: Optional[int] = None, stop_at: Optional[Union[str, List[str]]] = None, seed: Optional[int] = None, **model_specific_params, ): """Return a text generator from a prompt or a list of prompts.""" ...
Return a text generator from a prompt or a list of prompts.
stream
python
dottxt-ai/outlines
outlines/generate/api.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/generate/api.py
Apache-2.0
def __call__( # type: ignore self, prompts: Union[str, List[str]], media: Union[str, Any], max_tokens: Optional[int] = None, stop_at: Optional[Union[str, List[str]]] = None, seed: Optional[int] = None, **model_specific_params, ): """ Generate ...
Generate text from a prompt of list of prompts. Media: A URI to construct media or media object itself. Used as AutoProcessor argument.
__call__
python
dottxt-ai/outlines
outlines/generate/api.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/generate/api.py
Apache-2.0
def _validate_prompt_media_types( cls, prompts: Union[str, List[str]], media: Union[str, Any, List[Union[str, Any]]], ) -> Union[Any, List[Any]]: """ Prepare media as PIL.Image and ensure for every prompt str there is one List[PIL.Image] """ def valid_types(p...
Prepare media as PIL.Image and ensure for every prompt str there is one List[PIL.Image]
_validate_prompt_media_types
python
dottxt-ai/outlines
outlines/generate/api.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/generate/api.py
Apache-2.0
def cfg( model, cfg_str: str, sampler: Sampler = multinomial() ) -> SequenceGeneratorAdapter: """Generate text in the language of a Context-Free Grammar Arguments --------- model: An `outlines.model` instance. sampler: The sampling algorithm to use to generate token ids from the...
Generate text in the language of a Context-Free Grammar Arguments --------- model: An `outlines.model` instance. sampler: The sampling algorithm to use to generate token ids from the logits distribution. Returns ------- A `SequenceGeneratorAdapter` instance that gen...
cfg
python
dottxt-ai/outlines
outlines/generate/cfg.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/generate/cfg.py
Apache-2.0
def choice_openai( model: OpenAI, choices: List[str], sampler: Sampler = multinomial() ) -> Callable: """ Call OpenAI API with response_format of a dict: {"result": <one of choices>} """ choices_schema = pyjson.dumps( { "type": "object", "properties": {"result": ...
Call OpenAI API with response_format of a dict: {"result": <one of choices>}
choice_openai
python
dottxt-ai/outlines
outlines/generate/choice.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/generate/choice.py
Apache-2.0
def format( model, python_type, sampler: Sampler = multinomial() ) -> SequenceGeneratorAdapter: """Generate structured data that can be parsed as a Python type. Parameters ---------- model: An instance of `Transformer` that represents a model from the `transformers` library. pyt...
Generate structured data that can be parsed as a Python type. Parameters ---------- model: An instance of `Transformer` that represents a model from the `transformers` library. python_type: A Python type. The output of the generator must be parseable into this type. ...
format
python
dottxt-ai/outlines
outlines/generate/format.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/generate/format.py
Apache-2.0
def sequence_generator( model: Callable, sampler: Callable, fsms: List["Guide"], token_ids: "torch.Tensor", sequence_weights: "torch.Tensor", attention_masks: "torch.Tensor", fsm_states: List[int], rng: "torch.Generator", ) -> Iterator[GenerationState]: """Generates sequences of toke...
Generates sequences of tokens. Parameters ---------- model A callable that generates a probability distribution over the vocabulary when passed a tensor of token ids. sampler A callable that returns the next token ids, their ancestor sequence and the updated sequence wei...
sequence_generator
python
dottxt-ai/outlines
outlines/generate/generator.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/generate/generator.py
Apache-2.0
def get_next_fsm_states( fsms: List["Guide"], fsm_states: List[int], next_token_ids: "torch.Tensor" ) -> List[int]: """ Parameters ---------- fsm The finite-state machine used to monitor this batch. next_token_ids The tokens that were just generated. Returns ------- ...
Parameters ---------- fsm The finite-state machine used to monitor this batch. next_token_ids The tokens that were just generated. Returns ------- A `torch.Tensor` object that represents the next logit mask.
get_next_fsm_states
python
dottxt-ai/outlines
outlines/generate/generator.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/generate/generator.py
Apache-2.0
def get_allowed_tokens( fsms: List["Guide"], fsm_states: List[int] ) -> List[Optional[Iterable[int]]]: """Get the new instructions for each sequence from the finite-state machine. Parameters ---------- fsm The finite-state machine used to monitor this batch. fsm_states The FSM s...
Get the new instructions for each sequence from the finite-state machine. Parameters ---------- fsm The finite-state machine used to monitor this batch. fsm_states The FSM states corresponding to each sequence in the batch. Returns ------- A nested list that contains the id...
get_allowed_tokens
python
dottxt-ai/outlines
outlines/generate/generator.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/generate/generator.py
Apache-2.0
def update_token_ids( token_ids: "torch.Tensor", next_token_ids: "torch.Tensor", ancestors: "torch.Tensor" ) -> "torch.Tensor": """Append the sampled tokens to the running sequence of tokens. Parameters ---------- token_ids The current token sequences next_token_ids The tokens t...
Append the sampled tokens to the running sequence of tokens. Parameters ---------- token_ids The current token sequences next_token_ids The tokens that were just generated and that we need to append to the existing sequences. ancestors The sequences to which the toke...
update_token_ids
python
dottxt-ai/outlines
outlines/generate/generator.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/generate/generator.py
Apache-2.0
def update_attention_masks( attention_masks: "torch.Tensor", ancestors: "torch.Tensor" ) -> "torch.Tensor": """Expand the attention masks. Parameters ---------- attention_masks The attention masks for each sequence in the batch. ancestors The sequences to which the token ids nee...
Expand the attention masks. Parameters ---------- attention_masks The attention masks for each sequence in the batch. ancestors The sequences to which the token ids need to be added. Returns ------- The attention masks padded with 1s.
update_attention_masks
python
dottxt-ai/outlines
outlines/generate/generator.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/generate/generator.py
Apache-2.0
def reorder_kv_cache( kv_cache: Optional[Tuple], ancestors: "torch.Tensor" ) -> Optional[Tuple]: """Re-order the KV-cache based on the ancestors. In transformers, the object that stores the KV-cache is a tuple who elements are the key cache and the value cache. Each of these caches are tuples where ...
Re-order the KV-cache based on the ancestors. In transformers, the object that stores the KV-cache is a tuple who elements are the key cache and the value cache. Each of these caches are tuples where each element correpond to a layer. To each layer corresponds a tensor whose first dimension is the batc...
reorder_kv_cache
python
dottxt-ai/outlines
outlines/generate/generator.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/generate/generator.py
Apache-2.0
def bias_logits(logits: "torch.Tensor", allowed_token_ids: List) -> "torch.Tensor": """Mask the logits. The function iterates over a nested list where each list corresponds to the indices that need to be masked for each row in the array. Parameters ---------- logits Two dimensional ten...
Mask the logits. The function iterates over a nested list where each list corresponds to the indices that need to be masked for each row in the array. Parameters ---------- logits Two dimensional tensor that contains the next-token probability distribution. allowed_token_ids ...
bias_logits
python
dottxt-ai/outlines
outlines/generate/generator.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/generate/generator.py
Apache-2.0
def json( model, schema_object: Union[str, object, Callable], sampler: Sampler = multinomial(), whitespace_pattern: Optional[str] = None, ) -> SequenceGeneratorAdapter: """ Generate structured JSON data with a `Transformer` model based on a specified JSON Schema. Parameters ---------- ...
Generate structured JSON data with a `Transformer` model based on a specified JSON Schema. Parameters ---------- model: An instance of `Transformer` that represents a model from the `transformers` library. schema_object: The JSON Schema to generate data for. Can be a JSON s...
json
python
dottxt-ai/outlines
outlines/generate/json.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/generate/json.py
Apache-2.0
def regex(model, regex_str: str | Regex, sampler: Sampler = multinomial()): """Generate structured text in the language of a regular expression. Parameters ---------- model: An instance of `Transformer` that represents a model from the `transformers` library. regex_str: The ...
Generate structured text in the language of a regular expression. Parameters ---------- model: An instance of `Transformer` that represents a model from the `transformers` library. regex_str: The regular expression that the output must follow. sampler: The sampling a...
regex
python
dottxt-ai/outlines
outlines/generate/regex.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/generate/regex.py
Apache-2.0
def prepare_generation_parameters( self, prompts: Union[str, List[str]], generation_parameters: GenerationParameters, sampling_parameters: SamplingParameters, structure_logits_processor, **exllamav2_params: Unpack[ExllamaV2Params], ) -> Tuple[ExllamaV2Params, Union[st...
Prepare the generation parameters. `exllamav2` uses different default values
prepare_generation_parameters
python
dottxt-ai/outlines
outlines/models/exllamav2.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/models/exllamav2.py
Apache-2.0
def reformat_output( self, output: Union[str, List[str]], sampling_parameters: SamplingParameters ): """ The purpose of this function is to reformat the output from exllamav2's output format to outline's output format. For exllamav2, it mainly accepts only a list or a string(they al...
The purpose of this function is to reformat the output from exllamav2's output format to outline's output format. For exllamav2, it mainly accepts only a list or a string(they also do cfg sampling with tuples but we will ignore this for now). The exllamav2's logic is: 1. If the prompt...
reformat_output
python
dottxt-ai/outlines
outlines/models/exllamav2.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/models/exllamav2.py
Apache-2.0
def exl2( model_path: str, draft_model_path: Optional[str] = None, max_seq_len: Optional[int] = None, cache_q4: bool = False, paged: bool = True, max_chunk_size: Optional[int] = None, ) -> ExLlamaV2Model: """ Load an ExLlamaV2 model. Parameters ---------- model_path (str) ...
Load an ExLlamaV2 model. Parameters ---------- model_path (str) Path to the model directory. device (str) Device to load the model on. Pass in 'cuda' for GPU or 'cpu' for CPU max_seq_len (Optional[int], optional) Maximum sequence length. Defaults to None. scale_pos_...
exl2
python
dottxt-ai/outlines
outlines/models/exllamav2.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/models/exllamav2.py
Apache-2.0
def __getstate__(self): """Create a stable representation for outlines.caching""" return ( self.vocabulary, self.eos_token_id, self.eos_token, self.pad_token_id, sorted(self.special_tokens), )
Create a stable representation for outlines.caching
__getstate__
python
dottxt-ai/outlines
outlines/models/llamacpp.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/models/llamacpp.py
Apache-2.0
def prepare_generation_parameters( self, generation_parameters: GenerationParameters, sampling_parameters: SamplingParameters, structure_logits_processor, **llama_cpp_params: Unpack[LlamaCppParams], ): """Prepare the generation parameters. `llama-cpp-python` ...
Prepare the generation parameters. `llama-cpp-python` uses different default values
prepare_generation_parameters
python
dottxt-ai/outlines
outlines/models/llamacpp.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/models/llamacpp.py
Apache-2.0
def generate( self, prompts: Union[str, List[str]], generation_parameters: GenerationParameters, structure_logits_processor, sampling_parameters: SamplingParameters, **llama_cpp_params: Unpack[LlamaCppParams], ) -> str: """Generate text using `llama-cpp-python...
Generate text using `llama-cpp-python`. Parameters ---------- prompts A prompt or list of prompts. generation_parameters An instance of `GenerationParameters` that contains the prompt, the maximum number of tokens, stop sequences and seed. All the ...
generate
python
dottxt-ai/outlines
outlines/models/llamacpp.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/models/llamacpp.py
Apache-2.0
def stream( self, prompts: Union[str, List[str]], generation_parameters: GenerationParameters, structure_logits_processor, sampling_parameters: SamplingParameters, **llama_cpp_params: Unpack[LlamaCppParams], ) -> Iterator[str]: """Stream text using `llama-cpp-...
Stream text using `llama-cpp-python`. Parameters ---------- prompts A prompt or list of prompts. generation_parameters An instance of `GenerationParameters` that contains the prompt, the maximum number of tokens, stop sequences and seed. All the ...
stream
python
dottxt-ai/outlines
outlines/models/llamacpp.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/models/llamacpp.py
Apache-2.0
def llamacpp( repo_id: str, filename: Optional[str] = None, **llamacpp_model_params ) -> LlamaCpp: """Load a model from the `llama-cpp-python` library. We use the `Llama.from_pretrained` classmethod that downloads models directly from the HuggingFace hub, instead of asking users to specify a path t...
Load a model from the `llama-cpp-python` library. We use the `Llama.from_pretrained` classmethod that downloads models directly from the HuggingFace hub, instead of asking users to specify a path to the downloaded model. One can still load a local model by initializing `llama_cpp.Llama` directly. ...
llamacpp
python
dottxt-ai/outlines
outlines/models/llamacpp.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/models/llamacpp.py
Apache-2.0
def stream( self, prompts: Union[str, List[str]], generation_parameters: "GenerationParameters", logits_processor, sampling_parameters: "SamplingParameters", ) -> Iterator[str]: """Generate text using `mlx_lm`. Parameters ---------- prompts ...
Generate text using `mlx_lm`. Parameters ---------- prompts A prompt or list of prompts. generation_parameters An instance of `GenerationParameters` that contains the prompt, the maximum number of tokens, stop sequences and seed. All the a...
stream
python
dottxt-ai/outlines
outlines/models/mlxlm.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/models/mlxlm.py
Apache-2.0
def generate_step( self, prompt: "mx.array", temp: Optional[float], top_p: Optional[float], sampler: str, logits_processor: "OutlinesLogitsProcessor", ) -> Generator[Tuple[int, float], None, None]: """ Adapted from https://github.com/ml-explore...
Adapted from https://github.com/ml-explore/mlx-examples/blob/4872727/llms/mlx_lm/utils.py#L129 A generator producing token ids based on the given prompt from the model. Parameters ---------- prompt The input prompt. temp The temperature ...
generate_step
python
dottxt-ai/outlines
outlines/models/mlxlm.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/models/mlxlm.py
Apache-2.0
def mlxlm( model_name: str, tokenizer_config: dict = {}, model_config: dict = {}, adapter_path: Optional[str] = None, lazy: bool = False, ): """Instantiate a model from the `mlx_lm` library and its tokenizer. Signature adapted from https://github.com/ml-explore/mlx-examples/blob/4872727...
Instantiate a model from the `mlx_lm` library and its tokenizer. Signature adapted from https://github.com/ml-explore/mlx-examples/blob/4872727/llms/mlx_lm/utils.py#L422 Parameters ---------- Args: path_or_hf_repo (Path): The path or the huggingface repository to load the model from. ...
mlxlm
python
dottxt-ai/outlines
outlines/models/mlxlm.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/models/mlxlm.py
Apache-2.0
def __init__( self, client, config, system_prompt: Optional[str] = None, ): """Create an `OpenAI` instance. This class supports the standard OpenAI API, the Azure OpeanAI API as well as compatible APIs that rely on the OpenAI client. Parameters ...
Create an `OpenAI` instance. This class supports the standard OpenAI API, the Azure OpeanAI API as well as compatible APIs that rely on the OpenAI client. Parameters ---------- client An instance of the API's async client. config An instance of `...
__init__
python
dottxt-ai/outlines
outlines/models/openai.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/models/openai.py
Apache-2.0
def __call__( self, prompt: Union[str, List[str]], max_tokens: Optional[int] = None, stop_at: Optional[Union[List[str], str]] = None, *, system_prompt: Optional[str] = None, temperature: Optional[float] = None, samples: Optional[int] = None, ) -> np.nd...
Call the OpenAI API to generate text. Parameters ---------- prompt A string or list of strings that will be used to prompt the model max_tokens The maximum number of tokens to generate stop_at A string or array of strings which, such that the ...
__call__
python
dottxt-ai/outlines
outlines/models/openai.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/models/openai.py
Apache-2.0
async def generate_chat( prompt: str, system_prompt: Union[str, None], client, config: OpenAIConfig, ) -> Tuple[np.ndarray, int, int]: """Call OpenAI's Chat Completion API. Parameters ---------- prompt The prompt we use to start the generation. Passed to the model with t...
Call OpenAI's Chat Completion API. Parameters ---------- prompt The prompt we use to start the generation. Passed to the model with the "user" role. system_prompt The system prompt, passed to the model with the "system" role before the prompt. client The API ...
generate_chat
python
dottxt-ai/outlines
outlines/models/openai.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/models/openai.py
Apache-2.0
def error_handler(api_call_fn: Callable) -> Callable: """Handle OpenAI API errors and missing API key.""" def call(*args, **kwargs): import openai try: return api_call_fn(*args, **kwargs) except ( openai.APITimeoutError, openai.InternalServerError, ...
Handle OpenAI API errors and missing API key.
error_handler
python
dottxt-ai/outlines
outlines/models/openai.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/models/openai.py
Apache-2.0
def encode( self, prompt: Union[str, List[str]] ) -> Tuple[NDArray[np.int64], NDArray[np.int64]]: """Translate the input prompts into arrays of token ids and attention mask.""" ...
Translate the input prompts into arrays of token ids and attention mask.
encode
python
dottxt-ai/outlines
outlines/models/tokenizer.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/models/tokenizer.py
Apache-2.0
def get_llama_tokenizer_types(): """Get all the Llama tokenizer types/classes that need work-arounds. When they can't be imported, a dummy class is created. """ try: from transformers.models.llama import LlamaTokenizer except ImportError: class LlamaTokenizer: # type: ignore ...
Get all the Llama tokenizer types/classes that need work-arounds. When they can't be imported, a dummy class is created.
get_llama_tokenizer_types
python
dottxt-ai/outlines
outlines/models/transformers.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/models/transformers.py
Apache-2.0
def forward( self, input_ids: "torch.LongTensor", attention_mask: "torch.LongTensor", past_key_values: Optional[Tuple] = None, ) -> Tuple["torch.FloatTensor", Optional[KVCacheType]]: """Compute a forward pass through the transformer model. Parameters --------...
Compute a forward pass through the transformer model. Parameters ---------- input_ids The input token ids. Must be one or two dimensional. attention_mask The attention mask. Must be one or two dimensional. past_key_values A tuple of tuples c...
forward
python
dottxt-ai/outlines
outlines/models/transformers.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/models/transformers.py
Apache-2.0
def generate( self, prompts: Union[str, List[str]], generation_parameters: GenerationParameters, logits_processor: Optional["OutlinesLogitsProcessor"], sampling_parameters: SamplingParameters, ) -> Union[str, List[str], List[List[str]]]: """Generate text using `transf...
Generate text using `transformers`. Parameters ---------- prompts A prompt or list of prompts. generation_parameters An instance of `GenerationParameters` that contains the prompt, the maximum number of tokens, stop sequences and seed. All the ...
generate
python
dottxt-ai/outlines
outlines/models/transformers.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/models/transformers.py
Apache-2.0
def stream( self, prompts: Union[str, List[str]], generation_parameters: GenerationParameters, logits_processor: Optional["OutlinesLogitsProcessor"], sampling_parameters: SamplingParameters, ) -> Iterator[Union[str, List[str]]]: """ Temporary stream stand-in w...
Temporary stream stand-in which implements stream() signature and equivalent behaviour but isn't yielded until generation completes. TODO: implement following completion of https://github.com/huggingface/transformers/issues/30810
stream
python
dottxt-ai/outlines
outlines/models/transformers.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/models/transformers.py
Apache-2.0
def _get_generation_kwargs( self, prompts: Union[str, List[str]], generation_parameters: GenerationParameters, logits_processor: Optional["OutlinesLogitsProcessor"], sampling_parameters: SamplingParameters, ) -> dict: """ Convert outlines generation parameters...
Convert outlines generation parameters into model.generate kwargs
_get_generation_kwargs
python
dottxt-ai/outlines
outlines/models/transformers.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/models/transformers.py
Apache-2.0
def transformers( model_name: str, device: Optional[str] = None, model_kwargs: dict = {}, tokenizer_kwargs: dict = {}, model_class=None, tokenizer_class=None, ): """Instantiate a model from the `transformers` library and its tokenizer. Parameters ---------- model_name Th...
Instantiate a model from the `transformers` library and its tokenizer. Parameters ---------- model_name The name of the model as listed on Hugging Face's model page. device The device(s) on which the model should be loaded. This overrides the `device_map` entry in `model_kwargs`...
transformers
python
dottxt-ai/outlines
outlines/models/transformers.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/models/transformers.py
Apache-2.0
def generate( # type: ignore self, prompts: Union[str, List[str]], media: Union[List[Any], List[List[Any]]], generation_parameters: GenerationParameters, logits_processor: Optional["OutlinesLogitsProcessor"], sampling_parameters: SamplingParameters, ) -> Union[str, L...
Generate text using `transformers`. Parameters ---------- prompts A prompt or list of prompts. media A List[PIL.Image] or List[List[PIL.Image]] generation_parameters An instance of `GenerationParameters` that contains the prompt, t...
generate
python
dottxt-ai/outlines
outlines/models/transformers_vision.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/models/transformers_vision.py
Apache-2.0
def transformers_vision( model_name: str, model_class, device: Optional[str] = None, model_kwargs: dict = {}, processor_kwargs: dict = {}, tokenizer_class=None, processor_class=None, ): """Instantiate a model from the `transformers` library and its tokenizer. Parameters --------...
Instantiate a model from the `transformers` library and its tokenizer. Parameters ---------- model_name The name of the model as listed on Hugging Face's model page. model_class The `PreTrainedModel` class from transformers to use in initializing the vision model from `model_name`. ...
transformers_vision
python
dottxt-ai/outlines
outlines/models/transformers_vision.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/models/transformers_vision.py
Apache-2.0
def generate( self, prompts: Union[str, List[str]], generation_parameters: GenerationParameters, logits_processor, sampling_parameters: SamplingParameters, *, sampling_params: Optional["SamplingParams"] = None, use_tqdm: bool = True, ): """Gene...
Generate text using vLLM. Parameters ---------- prompts A prompt or list of prompts. generation_parameters An instance of `GenerationParameters` that contains the prompt, the maximum number of tokens, stop sequences and seed. All the argum...
generate
python
dottxt-ai/outlines
outlines/models/vllm.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/models/vllm.py
Apache-2.0
def stream(self, *args, **kwargs): """Return a text generator. Streaming is not yet available for `vllm.LLM`. TODO: Implement the streaming functionality ourselves. """ raise NotImplementedError( "Streaming is not available for the vLLM integration." )
Return a text generator. Streaming is not yet available for `vllm.LLM`. TODO: Implement the streaming functionality ourselves.
stream
python
dottxt-ai/outlines
outlines/models/vllm.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/models/vllm.py
Apache-2.0
def vllm(model_name: str, **vllm_model_params): """Load a vLLM model. Parameters --------- model_name The name of the model to load from the HuggingFace hub. vllm_model_params vLLM-specific model parameters. See the vLLM code for the full list: https://github.com/vllm-projec...
Load a vLLM model. Parameters --------- model_name The name of the model to load from the HuggingFace hub. vllm_model_params vLLM-specific model parameters. See the vLLM code for the full list: https://github.com/vllm-project/vllm/blob/main/vllm/entrypoints/llm.py
vllm
python
dottxt-ai/outlines
outlines/models/vllm.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/models/vllm.py
Apache-2.0
def adapt_tokenizer(tokenizer: "PreTrainedTokenizerBase") -> "PreTrainedTokenizerBase": """Adapt a 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 com...
Adapt a 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. Parameters ---------- tokenizer The tokenizer of...
adapt_tokenizer
python
dottxt-ai/outlines
outlines/models/vllm.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/models/vllm.py
Apache-2.0
def process_logits( self, input_ids: List[List[int]], logits: torch.Tensor ) -> torch.Tensor: """ input_ids and logits are always 2D tensors for handling a batch of sequences. - input_ids -> List[List[tokens]] - logits -> 2D_Tensor[logit floats] Important to keep in...
input_ids and logits are always 2D tensors for handling a batch of sequences. - input_ids -> List[List[tokens]] - logits -> 2D_Tensor[logit floats] Important to keep in mind when designing universal logits processors - logits processors are only used once and never re-applied ...
process_logits
python
dottxt-ai/outlines
outlines/processors/base_logits_processor.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/processors/base_logits_processor.py
Apache-2.0
def __call__( self, input_ids: Array, logits: Array, ) -> Array: """ Apply logits processor 1) Unify type - convert input_ids: either ndarray, mlx array, List[int], or Tensor -> List[List[int]] - convert logits: either ndarray, mlx array, or Tensor ->...
Apply logits processor 1) Unify type - convert input_ids: either ndarray, mlx array, List[int], or Tensor -> List[List[int]] - convert logits: either ndarray, mlx array, or Tensor -> 2D float Tensor 2) Unify shape, ensure logits and input_ids are 2D 3) Call self.process...
__call__
python
dottxt-ai/outlines
outlines/processors/base_logits_processor.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/processors/base_logits_processor.py
Apache-2.0
def _to_torch(tensor_like: Array) -> torch.Tensor: """Convert various types to torch.Tensor.""" if isinstance(tensor_like, torch.Tensor): return tensor_like elif isinstance(tensor_like, np.ndarray): return torch.from_numpy(tensor_like) elif isinstance(tensor_lik...
Convert various types to torch.Tensor.
_to_torch
python
dottxt-ai/outlines
outlines/processors/base_logits_processor.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/processors/base_logits_processor.py
Apache-2.0
def _from_torch(tensor: torch.Tensor, target_type: Type) -> Array: """Convert torch.Tensor to the specified target type.""" if target_type == torch.Tensor: return tensor elif target_type == np.ndarray: return tensor.detach().numpy() elif target_type is list: ...
Convert torch.Tensor to the specified target type.
_from_torch
python
dottxt-ai/outlines
outlines/processors/base_logits_processor.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/processors/base_logits_processor.py
Apache-2.0
def __init__(self, tokenizer: "Tokenizer", guide: Guide): """A Guide-based logits processor. Parameters ---------- tokenizer The tokenizer used to convert tokens to ids. guide The `outlines.fsm.Guide. which is used to bias the logits. """ ...
A Guide-based logits processor. Parameters ---------- tokenizer The tokenizer used to convert tokens to ids. guide The `outlines.fsm.Guide. which is used to bias the logits.
__init__
python
dottxt-ai/outlines
outlines/processors/structured.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/processors/structured.py
Apache-2.0
def process_logits( self, input_ids: torch.LongTensor, logits: torch.FloatTensor ) -> torch.Tensor: """Use the Guide to bias the logits before sampling the next token. Parameters ---------- input_ids The input token ids. logits The logits. ...
Use the Guide to bias the logits before sampling the next token. Parameters ---------- input_ids The input token ids. logits The logits. Returns ------- torch.Tensor The biased logits.
process_logits
python
dottxt-ai/outlines
outlines/processors/structured.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/processors/structured.py
Apache-2.0
def __init__( self, schema: Union[dict, Type[BaseModel], str], tokenizer: "Tokenizer", whitespace_pattern: Optional[str] = None, ): """Compile the Guide that drives the JSON-guided generation. Parameters ---------- schema A JSON schema tha...
Compile the Guide that drives the JSON-guided generation. Parameters ---------- schema A JSON schema that encodes the structure we want the model to generate. tokenizer The tokenizer used to convert tokens to ids. whitespace_pattern Pattern to...
__init__
python
dottxt-ai/outlines
outlines/processors/structured.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/processors/structured.py
Apache-2.0
def process_logits( self, input_ids: torch.LongTensor, logits: torch.Tensor ) -> torch.Tensor: """Same behavior as GuideLogitsProcessor, but uses rejection sampling""" if self._seq_start_idx is None: self._seq_start_idx = len(input_ids[0]) sequence_states: List = [] # v...
Same behavior as GuideLogitsProcessor, but uses rejection sampling
process_logits
python
dottxt-ai/outlines
outlines/processors/structured.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/processors/structured.py
Apache-2.0
async def generate(request: Request) -> Response: """Generate completion for the request. The request should be a JSON object with the following fields: - prompt: the prompt to use for the generation. - schema: the JSON schema to use for the generation (if regex is not provided). - regex: the regex...
Generate completion for the request. The request should be a JSON object with the following fields: - prompt: the prompt to use for the generation. - schema: the JSON schema to use for the generation (if regex is not provided). - regex: the regex to use for the generation (if schema is not provided). ...
generate
python
dottxt-ai/outlines
outlines/serve/serve.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/serve/serve.py
Apache-2.0
def matches(self, value: str) -> bool: """Check that a given value is in the language defined by the Term. We make the assumption that the language defined by the term can be defined with a regular expression. """ pattern = to_regex(self) compiled = re.compile(pattern) ...
Check that a given value is in the language defined by the Term. We make the assumption that the language defined by the term can be defined with a regular expression.
matches
python
dottxt-ai/outlines
outlines/types/dsl.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/types/dsl.py
Apache-2.0
def exactly(count: int, term: Union[Term, str]) -> QuantifyExact: """Repeat the term exactly `count` times.""" term = String(term) if isinstance(term, str) else term return QuantifyExact(term, count)
Repeat the term exactly `count` times.
exactly
python
dottxt-ai/outlines
outlines/types/dsl.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/types/dsl.py
Apache-2.0
def at_least(count: int, term: Union[Term, str]) -> QuantifyMinimum: """Repeat the term at least `count` times.""" term = String(term) if isinstance(term, str) else term return QuantifyMinimum(term, count)
Repeat the term at least `count` times.
at_least
python
dottxt-ai/outlines
outlines/types/dsl.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/types/dsl.py
Apache-2.0
def to_regex(term: Term) -> str: """Convert a term to a regular expression. We only consider self-contained terms that do not refer to another rule. """ match term: case String(): return re.escape(term.value) case Regex(): return f"({term.pattern})" case...
Convert a term to a regular expression. We only consider self-contained terms that do not refer to another rule.
to_regex
python
dottxt-ai/outlines
outlines/types/dsl.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/types/dsl.py
Apache-2.0
def refresh_environment(): """Refresh the test environment. This deletes any reference to `outlines` in the modules dictionary and unsets the `OUTLINES_CACHE_DIR` environment variable if set. This is necessary because we are using a module variable to hold the cache. """ import sys for ke...
Refresh the test environment. This deletes any reference to `outlines` in the modules dictionary and unsets the `OUTLINES_CACHE_DIR` environment variable if set. This is necessary because we are using a module variable to hold the cache.
refresh_environment
python
dottxt-ai/outlines
tests/test_cache.py
https://github.com/dottxt-ai/outlines/blob/master/tests/test_cache.py
Apache-2.0
def test_cache(refresh_environment): """Initialize a temporary cache and delete it after the test has run.""" with tempfile.TemporaryDirectory() as tempdir: os.environ["OUTLINES_CACHE_DIR"] = tempdir import outlines memory = outlines.get_cache() assert memory.directory == tempdi...
Initialize a temporary cache and delete it after the test has run.
test_cache
python
dottxt-ai/outlines
tests/test_cache.py
https://github.com/dottxt-ai/outlines/blob/master/tests/test_cache.py
Apache-2.0
def test_disable_cache(test_cache): """Make sure that we can disable the cache.""" import outlines outlines.disable_cache() # If the cache is disabled then the size # of `store` should increase every time # `f` is called. store = list() @test_cache def f(x): store.append(1...
Make sure that we can disable the cache.
test_disable_cache
python
dottxt-ai/outlines
tests/test_cache.py
https://github.com/dottxt-ai/outlines/blob/master/tests/test_cache.py
Apache-2.0