text stringlengths 1 1.02k | class_index int64 0 10.8k | source stringlengths 85 188 |
|---|---|---|
>> # render the prompt, ready for user to inspect, or for input into the model:
>> prompt = tokenizer.apply_tool_use_template(conversation, tools=tools, tokenize=False, add_generation_prompt=True)
>> print(prompt)
<BOS_TOKEN><|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|># Safety Preamble
The in... | 3,034 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/tokenization_cohere_fast.py |
# System Preamble
## Basic Rules
You are a powerful conversational AI trained by Cohere to help people. You are augmented by a number of tools, and your job is to use and consume the output of these tools to best help the user. You will see a conversation history between yourself and a user, ending with... | 3,034 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/tokenization_cohere_fast.py |
## Style Guide
Unless the user asks for a different style of answer, you should answer in full sentences, using proper grammar and spelling.
## Available Tools
Here is a list of tools that you have available to you:
\\`\\`\\`python
def internet_search(query: str) -> List[Dict]:... | 3,034 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/tokenization_cohere_fast.py |
\\`\\`\\`python
def directly_answer() -> List[Dict]:
\"\"\"Calls a standard (un-augmented) AI chatbot to generate a response given the conversation history
\"\"\"
pass
\\`\\`\\`<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|USER_TOKEN|>Whats the biggest penguin in the ... | 3,034 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/tokenization_cohere_fast.py |
"parameters": a dict of parameters to input into the tool as they are defined in the specs, or {} if it takes no parameters
}
]\\`\\`\\`<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>
```
>> inputs = tokenizer.encode(prompt, add_special_tokens=False, return_tensors='pt'... | 3,034 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/tokenization_cohere_fast.py |
def apply_grounded_generation_template(
self,
conversation: Union[List[Dict[str, str]]],
documents: List[Dict],
citation_mode: Literal["fast", "accurate"] = "accurate",
**kwargs,
) -> Union[str, List[int]]:
"""Create a Command-R grounded generation (aka RAG) prompt.
... | 3,034 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/tokenization_cohere_fast.py |
Converts a list of dictionaries with `"role"` and `"content"` keys and a list of
documents for the model to ground its response on into a prompt string, or a list of token ids.
This method will use the tokenizer's `grounded_generation_template` template specified at the class level.
You can over... | 3,034 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/tokenization_cohere_fast.py |
Args:
conversation (Union[List[Dict[str, str]]]): A list of dicts
with "role" and "content" keys, representing the chat history so far.
documents (List[Dict[str, str]): A list of dicts, representing documents or tool outputs to ground your
generation on. A documen... | 3,034 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/tokenization_cohere_fast.py |
the start of an assistant message. This is useful when you want to generate a response from the model.
Note that this argument will be passed to the chat template, and so it must be supported in the
template for this argument to have any effect.
tokenize (`bool`, defaults to ... | 3,034 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/tokenization_cohere_fast.py |
return_tensors (`str` or [`~utils.TensorType`], *optional*):
If set, will return tensors of a particular framework. Has no effect if tokenize is `False`. Acceptable
values are:
- `'tf'`: Return TensorFlow `tf.Tensor` objects.
- `'pt'`: Return PyTorch `torc... | 3,034 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/tokenization_cohere_fast.py |
Returns:
`str`: A rendered prompt string.
or if tokenize=True:
`List[int]`: A list of token ids representing the tokenized chat so far, including control tokens. This
output is ready to pass to the model, either directly or via methods like `generate()`.
Examples... | 3,034 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/tokenization_cohere_fast.py |
>> # define documents:
>> documents = [
{ "title": "Tall penguins", "text": "Emperor penguins are the tallest." },
{ "title": "Penguin habitats", "text": "Emperor penguins only live in Antarctica."}
]
>> # define a conversation:
>> conversation = [
{"r... | 3,034 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/tokenization_cohere_fast.py |
## Basic Rules
You are a powerful conversational AI trained by Cohere to help people. You are augmented by a number of tools, and your job is to use and consume the output of these tools to best help the user. You will see a conversation history between yourself and a user, ending with an utterance from the use... | 3,034 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/tokenization_cohere_fast.py |
## Style Guide
Unless the user asks for a different style of answer, you should answer in full sentences, using proper grammar and spelling.<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|USER_TOKEN|>Whats the biggest penguin in the world?<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|><results>
... | 3,034 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/tokenization_cohere_fast.py |
Document: 1
title: Penguin habitats
text: Emperor penguins only live in Antarctica.
</results><|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|>Carefully perform the following instructions, in order, starting each with a new line.
Firstly, Decide which of the retrieved document... | 3,034 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/tokenization_cohere_fast.py |
Finally, Write 'Grounded answer:' followed by a response to the user's last input in high quality natural english. Use the symbols <co: doc> and </co: doc> to indicate when a fact comes from a document in the search result, e.g <co: 0>my fact</co: 0> for a fact from document 0.<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN... | 3,034 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/tokenization_cohere_fast.py |
Grounded answer: The <co: 0>Emperor Penguin</co: 0> is the <co: 0>tallest</co: 0> or biggest penguin in the world. It is a bird that <co: 1>lives only in Antarctica</co: 1> and <co: 0>grows to a height of around 122 centimetres.</co: 0>
"""
return self.apply_chat_template(
conversation,
... | 3,034 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/tokenization_cohere_fast.py |
# TODO ArthurZ let's rely on the template processor instead, refactor all fast tokenizers
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
bos_token_id = [self.bos_token_id] if self.add_bos_token else []
eos_token_id = [self.eos_token_id] if self.add_eos_token else []
... | 3,034 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/tokenization_cohere_fast.py |
class CohereLayerNorm(nn.Module):
def __init__(self, hidden_size=None, eps=1e-5, bias=False):
"""The hidden size can be a tuple or an int. The tuple is used for QKNorm to normalize across head_dim"""
super().__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.variance... | 3,035 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modeling_cohere.py |
class CohereRotaryEmbedding(nn.Module):
def __init__(self, config: CohereConfig, device=None):
super().__init__()
# BC: "rope_type" was originally "type"
if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
self.rope_type = config.rope_scaling.get("rope_type", ... | 3,036 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modeling_cohere.py |
def _dynamic_frequency_update(self, position_ids, device):
"""
dynamic RoPE layers should recompute `inv_freq` in the following situations:
1 - growing beyond the cached sequence length (allow scaling)
2 - the current sequence length is in the original scale (avoid losing precision with ... | 3,036 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modeling_cohere.py |
if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
# This .to() is needed if the model has been moved to a device after being initialized (because
# the buffer is automatically moved, but not the original copy)
self.original_inv_f... | 3,036 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modeling_cohere.py |
# Core RoPE block
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
position_ids_expanded = position_ids[:, None, :].float()
# Force float32 (see https://github.com/huggingface/transformers/pull/29285)
device_type = x.device.type
device... | 3,036 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modeling_cohere.py |
class CohereMLP(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.hidden_size = config.hidden_size
self.intermediate_size = config.intermediate_size
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
sel... | 3,037 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modeling_cohere.py |
class CohereAttention(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(self, config: CohereConfig, layer_idx: Optional[int] = None):
super().__init__()
self.config = config
self.layer_idx = layer_idx
self.head_dim = getattr(config, "he... | 3,038 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modeling_cohere.py |
self.q_proj = nn.Linear(
config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
)
self.k_proj = nn.Linear(
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
)
self.v_proj = nn.Linear(
... | 3,038 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modeling_cohere.py |
hidden_size=(config.num_key_value_heads, self.head_dim), eps=config.layer_norm_eps
) | 3,038 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modeling_cohere.py |
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: Tuple[torch.Tensor, torch.Tensor],
attention_mask: Optional[torch.Tensor],
past_key_value: Optional[Cache] = None,
cache_position: Optional[torch.LongTensor] = None,
**kwargs: Unpack[FlashAttenti... | 3,038 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modeling_cohere.py |
query_states = query_states.transpose(1, 2)
key_states = key_states.transpose(1, 2)
value_states = value_states.transpose(1, 2)
cos, sin = position_embeddings
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
if past_key_value is not None:
... | 3,038 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modeling_cohere.py |
attention_interface: Callable = eager_attention_forward
if self.config._attn_implementation != "eager":
if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):
logger.warning_once(
"`torch.nn.functional.scaled_dot_product_attentio... | 3,038 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modeling_cohere.py |
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
attn_output = self.o_proj(attn_output)
return attn_output, attn_weights | 3,038 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modeling_cohere.py |
class CohereDecoderLayer(nn.Module):
def __init__(self, config: CohereConfig, layer_idx: int):
super().__init__()
self.hidden_size = config.hidden_size
self.self_attn = CohereAttention(config=config, layer_idx=layer_idx)
self.mlp = CohereMLP(config)
self.input_layernorm = Coh... | 3,039 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modeling_cohere.py |
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_value: Optional[Cache] = None,
output_attentions: Optional[bool] = False,
use_cache: Optional[bool] = False,
... | 3,039 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modeling_cohere.py |
query_sequence_length, key_sequence_length)` if default attention is used.
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
output_attentions (`bool`, *optional*):
Whether or not to return the attentions tensors of all attention... | 3,039 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modeling_cohere.py |
with `head_dim` being the embedding dimension of each attention head.
"""
residual = hidden_states | 3,039 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modeling_cohere.py |
hidden_states = self.input_layernorm(hidden_states)
# Self Attention
hidden_states_attention, self_attn_weights = self.self_attn(
hidden_states=hidden_states,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_value=past_key_value,
... | 3,039 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modeling_cohere.py |
class CoherePreTrainedModel(PreTrainedModel):
config_class = CohereConfig
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = ["CohereDecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn_2 = True
_supports_sdpa = True
_s... | 3,040 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modeling_cohere.py |
class CohereModel(CoherePreTrainedModel):
"""
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`CohereDecoderLayer`]
Args:
config: CohereConfig
"""
def __init__(self, config: CohereConfig):
super().__init__(config)
self.padding_idx = con... | 3,041 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modeling_cohere.py |
def set_input_embeddings(self, value):
self.embed_tokens = value | 3,041 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modeling_cohere.py |
@add_start_docstrings_to_model_forward(COHERE_INPUTS_DOCSTRING)
def forward(
self,
input_ids: torch.LongTensor = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
inputs_embed... | 3,041 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modeling_cohere.py |
use_cache = use_cache if use_cache is not None else self.config.use_cache
return_dict = return_dict if return_dict is not None else self.config.use_return_dict | 3,041 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modeling_cohere.py |
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
if self.gradient_checkpointing and self.training and use_cache:
logger.warning_once(
"`use_cache=True` is incompatible with gradient check... | 3,041 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modeling_cohere.py |
causal_mask = self._update_causal_mask(
attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
)
hidden_states = inputs_embeds
# create position embeddings to be shared across the decoder layers
position_embeddings = self.rotary_emb(hidden_states,... | 3,041 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modeling_cohere.py |
if self.gradient_checkpointing and self.training:
layer_outputs = self._gradient_checkpointing_func(
decoder_layer.__call__,
hidden_states,
causal_mask,
position_ids,
past_key_values,
... | 3,041 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modeling_cohere.py |
hidden_states = layer_outputs[0]
if output_attentions:
all_self_attns += (layer_outputs[1],)
hidden_states = self.norm(hidden_states)
# add hidden states from the last decoder layer
if output_hidden_states:
all_hidden_states += (hidden_states,)
... | 3,041 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modeling_cohere.py |
def _update_causal_mask(
self,
attention_mask: torch.Tensor,
input_tensor: torch.Tensor,
cache_position: torch.Tensor,
past_key_values: Cache,
output_attentions: bool,
):
if self.config._attn_implementation == "flash_attention_2":
if attention_mask... | 3,041 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modeling_cohere.py |
# When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
if AttentionMaskConverter._ignore_causal_mask_sdpa(
attention_mask,
... | 3,041 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modeling_cohere.py |
# In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
attention_mask,
sequence_length=sequence_length,
target_length=target_length,
dtype=dtype,
dev... | 3,041 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modeling_cohere.py |
if (
self.config._attn_implementation == "sdpa"
and attention_mask is not None
and attention_mask.device.type == "cuda"
and not output_attentions
):
# Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows whe... | 3,041 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modeling_cohere.py |
@staticmethod
def _prepare_4d_causal_attention_mask_with_cache_position(
attention_mask: torch.Tensor,
sequence_length: int,
target_length: int,
dtype: torch.dtype,
device: torch.device,
cache_position: torch.Tensor,
batch_size: int,
**kwargs,
):
... | 3,041 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modeling_cohere.py |
Args:
attention_mask (`torch.Tensor`):
A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
`(batch_size, 1, query_length, key_value_length)`.
sequence_length (`int`):
The sequence length being processed.
... | 3,041 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modeling_cohere.py |
if attention_mask is not None and attention_mask.dim() == 4:
# In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
causal_mask = attention_mask
else:
min_dtype = torch.finfo(dtype).min
causal_mask = torch.full(... | 3,041 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modeling_cohere.py |
padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
padding_mask = padding_mask == 0
causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
padding_mask, min_dtype
) | 3,041 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modeling_cohere.py |
return causal_mask | 3,041 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modeling_cohere.py |
class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ... | 3,042 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modeling_cohere.py |
class CohereForCausalLM(CoherePreTrainedModel, GenerationMixin):
_tied_weights_keys = ["lm_head.weight"]
_tp_plan = {"lm_head": "colwise_rep"}
def __init__(self, config):
super().__init__(config)
self.model = CohereModel(config)
self.vocab_size = config.vocab_size
self.lm_he... | 3,043 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modeling_cohere.py |
@add_start_docstrings_to_model_forward(COHERE_INPUTS_DOCSTRING)
@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
def forward(
self,
input_ids: torch.LongTensor = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optiona... | 3,043 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modeling_cohere.py |
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
... | 3,043 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modeling_cohere.py |
num_logits_to_keep (`int`, *optional*):
Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
`input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
token can save memory, whic... | 3,043 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modeling_cohere.py |
>> # Generate
>> generate_ids = model.generate(inputs.input_ids, max_length=30)
>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
```"""
... | 3,043 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modeling_cohere.py |
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
outputs = self.model(
input_ids=input_ids,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
inputs_embeds=inputs_embeds,
... | 3,043 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modeling_cohere.py |
if not return_dict:
output = (logits,) + outputs[1:]
return (loss,) + output if loss is not None else output
return CausalLMOutputWithPast(
loss=loss,
logits=logits,
past_key_values=outputs.past_key_values,
hidden_states=outputs.hidden_sta... | 3,043 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modeling_cohere.py |
class CohereConfig(PretrainedConfig):
r"""
This is the configuration class to store the configuration of a [`CohereModel`]. It is used to instantiate an Cohere
model according to the specified arguments, defining the model architecture.
Configuration objects inherit from [`PretrainedConfig`] and can be... | 3,044 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/configuration_cohere.py |
Args:
vocab_size (`int`, *optional*, defaults to 256000):
Vocabulary size of the Cohere model. Defines the number of different tokens that can be represented by the
`inputs_ids` passed when calling [`CohereModel`]
hidden_size (`int`, *optional*, defaults to 8192):
Dim... | 3,044 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/configuration_cohere.py |
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
`num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
... | 3,044 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/configuration_cohere.py |
initializer_range (`float`, *optional*, defaults to 0.02):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
layer_norm_eps (`float`, *optional*, defaults to 1e-05):
The epsilon used by the layer normalization.
use_cache (`bool`, *op... | 3,044 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/configuration_cohere.py |
The base period of the RoPE embeddings.
rope_scaling (`Dict`, *optional*):
Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value... | 3,044 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/configuration_cohere.py |
`original_max_position_embeddings` (`int`, *optional*):
Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
pretraining.
`attention_factor` (`float`, *optional*):
Used with 'yarn' and 'longrope'. The s... | 3,044 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/configuration_cohere.py |
ramp function. If unspecified, it defaults to 1.
`short_factor` (`List[float]`, *optional*):
Only used with 'longrope'. The scaling factor to be applied to short contexts (<
`original_max_position_embeddings`). Must be a list of numbers with the same length as the... | 3,044 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/configuration_cohere.py |
Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
Whether to use a bias in the query, key, value and output projection layers during self-attention.
attention_dropout (`float... | 3,044 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/configuration_cohere.py |
```python
>>> from transformers import CohereModel, CohereConfig
>>> # Initializing a Cohere model configuration
>>> configuration = CohereConfig()
>>> # Initializing a model from the Cohere configuration
>>> model = CohereModel(configuration) # doctest: +SKIP
>>> # Accessing the model config... | 3,044 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/configuration_cohere.py |
def __init__(
self,
vocab_size=256000,
hidden_size=8192,
intermediate_size=22528,
logit_scale=0.0625,
num_hidden_layers=40,
num_attention_heads=64,
num_key_value_heads=None,
hidden_act="silu",
max_position_embeddings=8192,
initializ... | 3,044 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/configuration_cohere.py |
# for backward compatibility
if num_key_value_heads is None:
num_key_value_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads
self.hidden_act = hidden_act
self.initializer_range = initializer_range
self.layer_norm_eps = layer_norm_eps
... | 3,044 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/configuration_cohere.py |
class UdopConfig(PretrainedConfig):
r"""
This is the configuration class to store the configuration of a [`UdopForConditionalGeneration`]. It is used to
instantiate a UDOP model according to the specified arguments, defining the model architecture. Instantiating a
configuration with the defaults will yi... | 3,045 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/udop/configuration_udop.py |
Arguments:
vocab_size (`int`, *optional*, defaults to 33201):
Vocabulary size of the UDOP model. Defines the number of different tokens that can be represented by the
`inputs_ids` passed when calling [`UdopForConditionalGeneration`].
d_model (`int`, *optional*, defaults to 1024):... | 3,045 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/udop/configuration_udop.py |
Number of hidden layers in the Transformer decoder. Will use the same value as `num_layers` if not set.
num_heads (`int`, *optional*, defaults to 16):
Number of attention heads for each attention layer in the Transformer encoder and decoder.
relative_attention_num_buckets (`int`, *optional*,... | 3,045 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/udop/configuration_udop.py |
The epsilon used by the layer normalization layers.
initializer_factor (`float`, *optional*, defaults to 1.0):
A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
testing).
feed_forward_proj (`string`, *optional*, defaults to `"r... | 3,045 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/udop/configuration_udop.py |
The id of the end-of-sequence token in the vocabulary.
max_2d_position_embeddings (`int`, *optional*, defaults to 1024):
The maximum absolute position embeddings for relative position encoding.
image_size (`int`, *optional*, defaults to 224):
The size of the input images.
... | 3,045 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/udop/configuration_udop.py |
model_type = "udop"
keys_to_ignore_at_inference = ["past_key_values"]
attribute_map = {"hidden_size": "d_model", "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers"} | 3,045 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/udop/configuration_udop.py |
def __init__(
self,
vocab_size=33201,
d_model=1024,
d_kv=64,
d_ff=4096,
num_layers=24,
num_decoder_layers=None,
num_heads=16,
relative_attention_num_buckets=32,
relative_attention_max_distance=128,
relative_bias_args=[{"type": "1d"}... | 3,045 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/udop/configuration_udop.py |
) # default = symmetry
self.num_heads = num_heads
self.relative_attention_num_buckets = relative_attention_num_buckets
self.relative_attention_max_distance = relative_attention_max_distance
self.dropout_rate = dropout_rate
self.layer_norm_epsilon = layer_norm_epsilon
sel... | 3,045 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/udop/configuration_udop.py |
# UDOP attributes
self.max_2d_position_embeddings = max_2d_position_embeddings
self.image_size = image_size
self.patch_size = patch_size
self.num_channels = num_channels
if not isinstance(relative_bias_args, list):
raise TypeError("`relative_bias_args` should be a lis... | 3,045 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/udop/configuration_udop.py |
super().__init__(
pad_token_id=pad_token_id,
eos_token_id=eos_token_id,
is_encoder_decoder=is_encoder_decoder,
**kwargs,
) | 3,045 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/udop/configuration_udop.py |
class UdopTokenizerFast(PreTrainedTokenizerFast):
"""
Construct a "fast" UDOP tokenizer (backed by HuggingFace's *tokenizers* library). Adapted from
[`LayoutXLMTokenizer`] and [`T5Tokenizer`]. Based on
[BPE](https://huggingface.co/docs/tokenizers/python/latest/components.html?highlight=BPE#models).
... | 3,046 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/udop/tokenization_udop_fast.py |
sep_token (`str`, *optional*, defaults to `"</s>"`):
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
sequence classification or for a text and a question for question answering. It is also used as the last
token of a sequenc... | 3,046 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/udop/tokenization_udop_fast.py |
pad_token_label (`int`, *optional*, defaults to -100):
The label to use for padding tokens. Defaults to -100, which is the `ignore_index` of PyTorch's
CrossEntropyLoss.
only_label_first_subword (`bool`, *optional*, defaults to `True`):
Whether or not to only label the first s... | 3,046 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/udop/tokenization_udop_fast.py |
vocab_files_names = VOCAB_FILES_NAMES
model_input_names = ["input_ids", "attention_mask"]
slow_tokenizer_class = UdopTokenizer | 3,046 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/udop/tokenization_udop_fast.py |
def __init__(
self,
vocab_file=None,
tokenizer_file=None,
eos_token="</s>",
sep_token="</s>",
unk_token="<unk>",
pad_token="<pad>",
sep_token_box=[1000, 1000, 1000, 1000],
pad_token_box=[0, 0, 0, 0],
pad_token_label=-100,
only_label... | 3,046 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/udop/tokenization_udop_fast.py |
# additional properties
self.sep_token_box = sep_token_box
self.pad_token_box = pad_token_box
self.pad_token_label = pad_token_label
self.only_label_first_subword = only_label_first_subword
@property
def can_save_slow_tokenizer(self) -> bool:
return os.path.isfile(self.v... | 3,046 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/udop/tokenization_udop_fast.py |
@add_end_docstrings(UDOP_ENCODE_KWARGS_DOCSTRING)
def __call__(
self,
text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None,
text_pair: Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None,
boxes: Union[List[List[int]], List[List[Lis... | 3,046 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/udop/tokenization_udop_fast.py |
# input mode in this case.
if not self._in_target_context_manager:
self._switch_to_input_mode()
encodings = self.call_boxes(text=text, text_pair=text_pair, boxes=boxes, word_labels=word_labels, **kwargs)
if text_target is not None:
self._switch_to_target_mode(... | 3,046 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/udop/tokenization_udop_fast.py |
if text_target is None:
return encodings
elif text is None:
return target_encodings
else:
encodings["labels"] = target_encodings["input_ids"]
return encodings | 3,046 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/udop/tokenization_udop_fast.py |
@add_end_docstrings(UDOP_ENCODE_KWARGS_DOCSTRING)
def call_boxes(
self,
text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]],
text_pair: Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None,
boxes: Union[List[List[int]], List[List[List[int... | 3,046 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/udop/tokenization_udop_fast.py |
return_offsets_mapping: bool = False,
return_length: bool = False,
verbose: bool = True,
**kwargs,
) -> BatchEncoding:
"""
Main method to tokenize and prepare for the model one or several sequence(s) or one or several pair(s) of
sequences with word-level normalized bo... | 3,046 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/udop/tokenization_udop_fast.py |
Args:
text (`str`, `List[str]`, `List[List[str]]`):
The sequence or batch of sequences to be encoded. Each sequence can be a string, a list of strings
(words of a single example or questions of a batch of examples) or a list of list of strings (batch of
words)... | 3,046 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/udop/tokenization_udop_fast.py |
# Input type checking for clearer error
def _is_valid_text_input(t):
if isinstance(t, str):
# Strings are fine
return True
elif isinstance(t, (list, tuple)):
# List are fine as long as they are...
if len(t) == 0:
... | 3,046 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/udop/tokenization_udop_fast.py |
if text_pair is not None:
# in case text + text_pair are provided, text = questions, text_pair = words
if not _is_valid_text_input(text):
raise ValueError("text input must of type `str` (single example) or `List[str]` (batch of examples). ")
if not isinstance(text_pai... | 3,046 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/udop/tokenization_udop_fast.py |
if text_pair is not None:
is_batched = isinstance(text, (list, tuple))
else:
is_batched = isinstance(text, (list, tuple)) and text and isinstance(text[0], (list, tuple))
words = text if text_pair is None else text_pair
if boxes is None:
raise ValueError("You ... | 3,046 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/udop/tokenization_udop_fast.py |
if is_batched:
if text_pair is not None and len(text) != len(text_pair):
raise ValueError(
f"batch length of `text`: {len(text)} does not match batch length of `text_pair`:"
f" {len(text_pair)}."
)
batch_text_or_text_pairs =... | 3,046 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/udop/tokenization_udop_fast.py |
return_token_type_ids=return_token_type_ids,
return_attention_mask=return_attention_mask,
return_overflowing_tokens=return_overflowing_tokens,
return_special_tokens_mask=return_special_tokens_mask,
return_offsets_mapping=return_offsets_mapping,
... | 3,046 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/udop/tokenization_udop_fast.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.