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 get_streaming_state(self) -> dict[str, tp.Any]:
"""Return the complete streaming state, including that of sub-modules."""
state: dict[str, tp.Any] = {}
def _add(name: str, module: StreamingModule):
state[name] = module._streaming_state
self._apply_named_streaming(_add)
... | Return the complete streaming state, including that of sub-modules. | get_streaming_state | python | kyutai-labs/moshi | moshi/moshi/modules/streaming.py | https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/modules/streaming.py | Apache-2.0 |
def set_streaming_state(self, state: dict[str, tp.Any]):
"""Set the streaming state, including that of sub-modules."""
state = dict(state)
def _set(name: str, module: StreamingModule):
if name in state:
module._streaming_state = state[name]
state.pop(... | Set the streaming state, including that of sub-modules. | set_streaming_state | python | kyutai-labs/moshi | moshi/moshi/modules/streaming.py | https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/modules/streaming.py | Apache-2.0 |
def set_exec_mask(self, exec_mask: torch.Tensor):
"""Set the execution mask, a tensor of boolean of shape `(B,), indicating
for each batch item whether the internal state should be updated or not as if
real data had been received.
This is useful for running desynchronized streams with b... | Set the execution mask, a tensor of boolean of shape `(B,), indicating
for each batch item whether the internal state should be updated or not as if
real data had been received.
This is useful for running desynchronized streams with batching, e.g. when
the mask is False for an entry, th... | set_exec_mask | python | kyutai-labs/moshi | moshi/moshi/modules/streaming.py | https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/modules/streaming.py | Apache-2.0 |
def create_norm_fn(norm_type: str, dim: int, **kwargs) -> nn.Module:
"""Create normalization module for transformer encoder layer.
Args:
norm_type (str): Normalization method.
dim (int): Dimension of the normalized layer.
**kwargs (dict): Additional parameters for normalization layer.
... | Create normalization module for transformer encoder layer.
Args:
norm_type (str): Normalization method.
dim (int): Dimension of the normalized layer.
**kwargs (dict): Additional parameters for normalization layer.
Returns:
nn.Module: Normalization module.
| create_norm_fn | python | kyutai-labs/moshi | moshi/moshi/modules/transformer.py | https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/modules/transformer.py | Apache-2.0 |
def create_sin_embedding(
positions: torch.Tensor,
dim: int,
max_period: float = 10000,
dtype: torch.dtype = torch.float32,
) -> torch.Tensor:
"""Create sinusoidal positional embedding, with shape `[B, T, C]`.
Args:
positions (torch.Tensor): LongTensor of positions.
dim (int): D... | Create sinusoidal positional embedding, with shape `[B, T, C]`.
Args:
positions (torch.Tensor): LongTensor of positions.
dim (int): Dimension of the embedding.
max_period (float): Maximum period of the cosine/sine functions.
dtype (torch.dtype or str): dtype to use to generate the e... | create_sin_embedding | python | kyutai-labs/moshi | moshi/moshi/modules/transformer.py | https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/modules/transformer.py | Apache-2.0 |
def set_attention_context(model: nn.Module, context: tp.Optional[int] = None) -> None:
"""Deactivates or changes the context span (in time steps) in a model.
Args:
model (nn.Module): model over which to look for attentions.
context (int or None): new temporary context value.
..Note:: this i... | Deactivates or changes the context span (in time steps) in a model.
Args:
model (nn.Module): model over which to look for attentions.
context (int or None): new temporary context value.
..Note:: this is not a context manager but a plain function changing the context forever.
Initially, ... | set_attention_context | python | kyutai-labs/moshi | moshi/moshi/modules/transformer.py | https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/modules/transformer.py | Apache-2.0 |
def apply_weights_per_step(modules: nn.ModuleList, schedule: list[int] | None,
x: torch.Tensor, offset: int | None) -> torch.Tensor:
"""Utility to apply a multi linear layer to the given input. A multi linear layer
applies a different set of weight for each time step.
Args:
... | Utility to apply a multi linear layer to the given input. A multi linear layer
applies a different set of weight for each time step.
Args:
modules (nn.ModuleList): apply weights per step.
schedule (list[int] or None): schedule for weight sharing.
x (torch.Tensor): Input tensor, with sha... | apply_weights_per_step | python | kyutai-labs/moshi | moshi/moshi/modules/transformer.py | https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/modules/transformer.py | Apache-2.0 |
def set_num_codebooks(self, n: int):
"""Set the number of active codebooks."""
raise AttributeError(
"Cannot override the number of codebooks for the dummy quantizer"
) | Set the number of active codebooks. | set_num_codebooks | python | kyutai-labs/moshi | moshi/moshi/quantization/base.py | https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/quantization/base.py | Apache-2.0 |
def initialized(self) -> bool:
"""Cached version of self._initialized,
This assumes that once the module is initialized, it will never go back to the uninitialized state."""
if not self._cached_initialized:
self._cached_initialized = bool(self._initialized.item())
return self... | Cached version of self._initialized,
This assumes that once the module is initialized, it will never go back to the uninitialized state. | initialized | python | kyutai-labs/moshi | moshi/moshi/quantization/core_vq.py | https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/quantization/core_vq.py | Apache-2.0 |
def encode(self, x: torch.Tensor) -> torch.Tensor:
"""Given a tensor `x` of shape `[*, D]`, returns a tensor of integer codes of shape `[*]`.
The codes are defined as the indexes of the centroids nearest to each vector in `x`.
"""
assert x.dtype.is_floating_point, f"Input should be float... | Given a tensor `x` of shape `[*, D]`, returns a tensor of integer codes of shape `[*]`.
The codes are defined as the indexes of the centroids nearest to each vector in `x`.
| encode | python | kyutai-labs/moshi | moshi/moshi/quantization/core_vq.py | https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/quantization/core_vq.py | Apache-2.0 |
def decode(self, codes: torch.Tensor) -> torch.Tensor:
"""Given a tensor of codes of shape `[*]`, returns a tensor of shape `[*, D]`,
corresponding to the centroids associated to each code index.
"""
assert (
not codes.dtype.is_floating_point
), f"Codes should be inte... | Given a tensor of codes of shape `[*]`, returns a tensor of shape `[*, D]`,
corresponding to the centroids associated to each code index.
| decode | python | kyutai-labs/moshi | moshi/moshi/quantization/core_vq.py | https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/quantization/core_vq.py | Apache-2.0 |
def decode(self, codes: torch.Tensor) -> torch.Tensor:
"""Converts integer codes into quantized vectors."""
quantized = self._codebook.decode(codes)
quantized = self.project_out(quantized)
quantized = self._rearrange_output(quantized)
return quantized | Converts integer codes into quantized vectors. | decode | python | kyutai-labs/moshi | moshi/moshi/quantization/core_vq.py | https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/quantization/core_vq.py | Apache-2.0 |
def forward(
self, x: torch.Tensor, n_q: tp.Optional[int] = None
) -> _VQForwardResult:
"""
Args:
x (torch.Tensor): input tensor to quantize, of shape `[B, C, T]`.
n_q (int or None): if provided, number of codebook levels to use in RVQ.
"""
quantized_... |
Args:
x (torch.Tensor): input tensor to quantize, of shape `[B, C, T]`.
n_q (int or None): if provided, number of codebook levels to use in RVQ.
| forward | python | kyutai-labs/moshi | moshi/moshi/quantization/core_vq.py | https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/quantization/core_vq.py | Apache-2.0 |
def encode(self, x: torch.Tensor, n_q: tp.Optional[int] = None) -> torch.Tensor:
"""Encodes `x` into discrete integer codes. If `n_q` is provided, only uses the first `n_q` codebook levels."""
residual = x
all_indices = []
n_q = n_q or len(self.layers)
for layer in self.layers[:n... | Encodes `x` into discrete integer codes. If `n_q` is provided, only uses the first `n_q` codebook levels. | encode | python | kyutai-labs/moshi | moshi/moshi/quantization/core_vq.py | https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/quantization/core_vq.py | Apache-2.0 |
def decode(self, codes: torch.Tensor) -> torch.Tensor:
"""Converts the integer codes into quantized vectors."""
quantized = zero_scalar(codes.device)
for idx, layer_codes in enumerate(codes):
layer = self.layers[idx]
assert isinstance(layer, VectorQuantization)
... | Converts the integer codes into quantized vectors. | decode | python | kyutai-labs/moshi | moshi/moshi/quantization/core_vq.py | https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/quantization/core_vq.py | Apache-2.0 |
def encode(self, x: torch.Tensor) -> torch.Tensor:
"""Encode a given input tensor with the specified frame rate at the given bandwidth.
The RVQ encode method sets the appropriate number of quantizer to use
and returns indices for each quantizer.
"""
n_q = self.n_q
if x.sh... | Encode a given input tensor with the specified frame rate at the given bandwidth.
The RVQ encode method sets the appropriate number of quantizer to use
and returns indices for each quantizer.
| encode | python | kyutai-labs/moshi | moshi/moshi/quantization/vq.py | https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/quantization/vq.py | Apache-2.0 |
def _renorm_and_add(
self,
first_val: torch.Tensor,
rest_val: torch.Tensor,
n_q_semantic: int,
n_q_acoustic: int,
):
"""Renormalizes values from `rvq_first` and `rvq_rest` and adds them.
This allows correcting statistics that are normalized by the number of q... | Renormalizes values from `rvq_first` and `rvq_rest` and adds them.
This allows correcting statistics that are normalized by the number of quantizers. To renormalize, we use the
number of quantizers that are actually used, e.g. taking into account quantizer dropout.
| _renorm_and_add | python | kyutai-labs/moshi | moshi/moshi/quantization/vq.py | https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/quantization/vq.py | Apache-2.0 |
def no_compile():
"""Disable torch.compile locally. Now Pytorch 2.4 provides a function to do that."""
global _compile_disabled
prev_disabled = _compile_disabled
_compile_disabled = True
try:
yield
finally:
_compile_disabled = prev_disabled | Disable torch.compile locally. Now Pytorch 2.4 provides a function to do that. | no_compile | python | kyutai-labs/moshi | moshi/moshi/utils/compile.py | https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/utils/compile.py | Apache-2.0 |
def torch_compile_lazy(fun):
"""torch.compile creates a huge pool of processes, even when not using the function at all,
e.g. with Dora. This can polute stderr when doing CTRL+C. So we do it in a lazy way.
"""
if os.environ.get("NO_TORCH_COMPILE"):
return fun
fun_compiled = None
@wraps(... | torch.compile creates a huge pool of processes, even when not using the function at all,
e.g. with Dora. This can polute stderr when doing CTRL+C. So we do it in a lazy way.
| torch_compile_lazy | python | kyutai-labs/moshi | moshi/moshi/utils/compile.py | https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/utils/compile.py | Apache-2.0 |
def simple_checkpoint(module: torch.nn.Module, *args, **kwargs):
"""Custom implementation of checkpointing in PyTorch as the builtin implementation is broken
when using torch compile. Only supports wrapping a `nn.Module` with a forward with no `*args` or `**kwargs`.
https://github.com/pytorch/pytorch/issue... | Custom implementation of checkpointing in PyTorch as the builtin implementation is broken
when using torch compile. Only supports wrapping a `nn.Module` with a forward with no `*args` or `**kwargs`.
https://github.com/pytorch/pytorch/issues/97436.
Should be resolved in nightlies, but it is quite fun and si... | simple_checkpoint | python | kyutai-labs/moshi | moshi/moshi/utils/compile.py | https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/utils/compile.py | Apache-2.0 |
def no_cuda_graph():
"""Deactivate CUDA Graphing for all the calls in this context manager."""
global _disable_cuda_graph
old_value = _disable_cuda_graph
_disable_cuda_graph = True
try:
yield
finally:
_disable_cuda_graph = old_value | Deactivate CUDA Graphing for all the calls in this context manager. | no_cuda_graph | python | kyutai-labs/moshi | moshi/moshi/utils/compile.py | https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/utils/compile.py | Apache-2.0 |
def reset(self, warmup_steps: int = 0) -> None:
"""Reset the state, meaning the next call we get CUDA Graphed again. Useful if some
shapes have changed, or external state (e.g. KVCache) has changed."""
self.warmup_steps = warmup_steps
self._graph = None
self._output = None
... | Reset the state, meaning the next call we get CUDA Graphed again. Useful if some
shapes have changed, or external state (e.g. KVCache) has changed. | reset | python | kyutai-labs/moshi | moshi/moshi/utils/compile.py | https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/utils/compile.py | Apache-2.0 |
def cuda_graph(func: tp.Callable, warmup_steps: int = 1):
"""Just calls `CUDAGraphed` on the given function."""
if not _is_cuda_graph_enabled():
return func
return CUDAGraphed(func, warmup_steps) | Just calls `CUDAGraphed` on the given function. | cuda_graph | python | kyutai-labs/moshi | moshi/moshi/utils/compile.py | https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/utils/compile.py | Apache-2.0 |
def replace_linear_with_qlinear(module):
"""Recursively replace all Linear layers with QLinear layers."""
for name, child in module.named_children():
if isinstance(child, nn.Linear):
setattr(module, name, QLinear(child))
elif isinstance(child, QLinear):
# Slight issue wit... | Recursively replace all Linear layers with QLinear layers. | replace_linear_with_qlinear | python | kyutai-labs/moshi | moshi/moshi/utils/quantize.py | https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/utils/quantize.py | Apache-2.0 |
def sample_token(
logits: torch.Tensor,
use_sampling: bool = False,
temp: float = 1.0,
top_k: int = 0,
top_p: float = 0.0,
) -> torch.Tensor:
"""Given logits of shape [*, Card], returns a LongTensor of shape [*]."""
# Apply softmax for sampling if temp > 0. Else, do greedy sampling to avoid ... | Given logits of shape [*, Card], returns a LongTensor of shape [*]. | sample_token | python | kyutai-labs/moshi | moshi/moshi/utils/sampling.py | https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/utils/sampling.py | Apache-2.0 |
def cross_entropy(
logits: torch.Tensor, targets: torch.Tensor, mask: torch.Tensor, dtype=torch.float32,
logits_soft_clip: float | None = None) -> torch.Tensor:
"""Compute cross entropy between multi-codebook targets and model's logits.
The cross entropy is computed per codebook to provide codeb... | Compute cross entropy between multi-codebook targets and model's logits.
The cross entropy is computed per codebook to provide codebook-level cross entropy.
Valid timesteps for each of the codebook are pulled from the mask, where invalid
timesteps are set to 0.
Args:
logits (torch.Tensor): Mode... | cross_entropy | python | kyutai-labs/moshi | moshi/moshi/utils/utils.py | https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/utils/utils.py | Apache-2.0 |
def min_p_sampling(
logits: mx.array,
min_p: float,
min_tokens_to_keep: int = 1,
temperature=1.0,
) -> mx.array:
"""
Apply min-p sampling to the logits.
Min-p keeps all tokens that are above a minimum probability, scaled by the
probability of the most likely token. As a result, the filt... |
Apply min-p sampling to the logits.
Min-p keeps all tokens that are above a minimum probability, scaled by the
probability of the most likely token. As a result, the filter is more
aggressive given a very high-probability token.
Args:
logits: The logits from the model's output.
mi... | min_p_sampling | python | kyutai-labs/moshi | moshi_mlx/moshi_mlx/utils/sampling.py | https://github.com/kyutai-labs/moshi/blob/master/moshi_mlx/moshi_mlx/utils/sampling.py | Apache-2.0 |
def top_k_sampling(
logprobs: mx.array,
top_k: int,
temperature=1.0,
) -> mx.array:
"""
Sample from only the top K tokens ranked by probability.
Args:
logprobs: A vector of log probabilities.
top_k (int): Top k tokens to sample from.
"""
vocab_size = logprobs.shape[-1]
... |
Sample from only the top K tokens ranked by probability.
Args:
logprobs: A vector of log probabilities.
top_k (int): Top k tokens to sample from.
| top_k_sampling | python | kyutai-labs/moshi | moshi_mlx/moshi_mlx/utils/sampling.py | https://github.com/kyutai-labs/moshi/blob/master/moshi_mlx/moshi_mlx/utils/sampling.py | Apache-2.0 |
def top_p_sampling(logits: mx.array, top_p: float, temperature: float) -> mx.array:
"""
Apply top-p (nucleus) sampling to logits.
Args:
logits: The logits from the model's output.
top_p: The cumulative probability threshold for top-p filtering.
temperature: Temperature parameter for... |
Apply top-p (nucleus) sampling to logits.
Args:
logits: The logits from the model's output.
top_p: The cumulative probability threshold for top-p filtering.
temperature: Temperature parameter for softmax distribution reshaping.
Returns:
token selected based on the top-p cri... | top_p_sampling | python | kyutai-labs/moshi | moshi_mlx/moshi_mlx/utils/sampling.py | https://github.com/kyutai-labs/moshi/blob/master/moshi_mlx/moshi_mlx/utils/sampling.py | Apache-2.0 |
def normalize_loudness(wav: torch.Tensor, sample_rate: int, loudness_headroom_db: float = 22,
energy_floor: float = 2e-3):
"""Normalize an input signal to a user loudness in dB LKFS.
Audio loudness is defined according to the ITU-R BS.1770-4 recommendation.
Args:
wav (torch.T... | Normalize an input signal to a user loudness in dB LKFS.
Audio loudness is defined according to the ITU-R BS.1770-4 recommendation.
Args:
wav (torch.Tensor): Input multichannel audio data.
sample_rate (int): Sample rate.
loudness_headroom_db (float): Target loudness of the output in dB ... | normalize_loudness | python | kyutai-labs/moshi | rust/moshi-server/voice.py | https://github.com/kyutai-labs/moshi/blob/master/rust/moshi-server/voice.py | Apache-2.0 |
def flush(self):
"""
Flush remaining audio by padding it with zero and initialize the previous
status. Call this when you have no more input and want to get back the last
chunk of audio.
"""
self.lstm_state = None
self.conv_state = None
pending_length = se... |
Flush remaining audio by padding it with zero and initialize the previous
status. Call this when you have no more input and want to get back the last
chunk of audio.
| flush | python | kyutai-labs/moshi | rust/moshi-server/voice.py | https://github.com/kyutai-labs/moshi/blob/master/rust/moshi-server/voice.py | Apache-2.0 |
def __init__(self, config: Config, block_idx: int) -> None:
"""Causal self-attention with calculating qkv matrices with a single matrix* and Low Ranking Adaptation for
parameter-efficient fine-tuning.
*Instead of creating multiple heads and concatenating the result (in addition to creating sepa... | Causal self-attention with calculating qkv matrices with a single matrix* and Low Ranking Adaptation for
parameter-efficient fine-tuning.
*Instead of creating multiple heads and concatenating the result (in addition to creating separate matrices for
query, key and value for each head) we can do... | __init__ | python | jzhang38/TinyLlama | lit_gpt/adapter_v2.py | https://github.com/jzhang38/TinyLlama/blob/master/lit_gpt/adapter_v2.py | Apache-2.0 |
def forward(
ctx,
logits,
labels,
smoothing=0.0,
ignored_index=-100,
inplace_backward=False,
process_group=None,
):
"""
logits: (batch, vocab_size)
labels: (batch,)
If process_group is not None, we're doing Tensor Parallel: each... |
logits: (batch, vocab_size)
labels: (batch,)
If process_group is not None, we're doing Tensor Parallel: each process is responsible for
one part of the vocab. The loss needs to be aggregated across processes.
| forward | python | jzhang38/TinyLlama | lit_gpt/fused_cross_entropy.py | https://github.com/jzhang38/TinyLlama/blob/master/lit_gpt/fused_cross_entropy.py | Apache-2.0 |
def forward(ctx, x, cos, sin, interleaved=False, inplace=False):
"""
x: (batch_size, seqlen, nheads, headdim)
cos, sin: (seqlen, rotary_dim / 2)
interleaved: if True, rotate pairs of even and odd dimensions (GPT-J style) instead
of 1st half and 2nd half (GPT-N... |
x: (batch_size, seqlen, nheads, headdim)
cos, sin: (seqlen, rotary_dim / 2)
interleaved: if True, rotate pairs of even and odd dimensions (GPT-J style) instead
of 1st half and 2nd half (GPT-NeoX style).
rotary_dim must be <= headdim
Apply rotary embed... | forward | python | jzhang38/TinyLlama | lit_gpt/fused_rotary_embedding.py | https://github.com/jzhang38/TinyLlama/blob/master/lit_gpt/fused_rotary_embedding.py | Apache-2.0 |
def save(self) -> None:
"""Overridden to merge CSV by the step number."""
import csv
if not self.metrics:
return
metrics = merge_by(self.metrics, "step")
keys = sorted({k for m in metrics for k in m})
with self._fs.open(self.metrics_file_path, "w", newline=""... | Overridden to merge CSV by the step number. | save | python | jzhang38/TinyLlama | lit_gpt/utils.py | https://github.com/jzhang38/TinyLlama/blob/master/lit_gpt/utils.py | Apache-2.0 |
def get_default_supported_precision(training: bool, tpu: bool = False) -> str:
"""Return default precision that is supported by the hardware.
Args:
training: `-mixed` or `-true` version of the precision to use
tpu: whether TPU device is used
Returns:
default precision that is suita... | Return default precision that is supported by the hardware.
Args:
training: `-mixed` or `-true` version of the precision to use
tpu: whether TPU device is used
Returns:
default precision that is suitable for the task and is supported by the hardware
| get_default_supported_precision | python | jzhang38/TinyLlama | lit_gpt/utils.py | https://github.com/jzhang38/TinyLlama/blob/master/lit_gpt/utils.py | Apache-2.0 |
def prepare_sample(
source_path: Path, checkpoint_dir: Path, destination_path: Path, chunk_size: int, match: str = ""
) -> None:
"""Prepare the "Red Pajama" dataset using the original tokenizer."""
destination_path.mkdir(parents=True, exist_ok=True)
tokenizer = Tokenizer(checkpoint_dir)
for name i... | Prepare the "Red Pajama" dataset using the original tokenizer. | prepare_sample | python | jzhang38/TinyLlama | scripts/prepare_redpajama.py | https://github.com/jzhang38/TinyLlama/blob/master/scripts/prepare_redpajama.py | Apache-2.0 |
def prepare(
source_path: Path = Path("data/RedPajama-Data-1T-Sample"),
checkpoint_dir: Path = Path("checkpoints/stabilityai/stablelm-base-alpha-3b"),
destination_path: Path = Path("data/redpajama_sample"),
sample: bool = True,
match: str = "",
) -> None:
"""Prepare the "Red Pajama" dataset. We ... | Prepare the "Red Pajama" dataset. We assume tokenizer has been trained. | prepare | python | jzhang38/TinyLlama | scripts/prepare_redpajama.py | https://github.com/jzhang38/TinyLlama/blob/master/scripts/prepare_redpajama.py | Apache-2.0 |
def make_data_module(tokenizer: transformers.PreTrainedTokenizer, args) -> Dict:
"""
Make dataset and collator for supervised fine-tuning.
Datasets are expected to have the following columns: { `input`, `output` }
Available datasets to be selected with `dataset` argument:
- alpaca, 52002 exampl... |
Make dataset and collator for supervised fine-tuning.
Datasets are expected to have the following columns: { `input`, `output` }
Available datasets to be selected with `dataset` argument:
- alpaca, 52002 examples
- alpaca cleaned, 51942 examples
- chip2 (OIG), 210289 examples
... | make_data_module | python | jzhang38/TinyLlama | sft/finetune.py | https://github.com/jzhang38/TinyLlama/blob/master/sft/finetune.py | Apache-2.0 |
def eval_exec_match(db, p_str, g_str, pred, gold):
"""
return 1 if the values between prediction and gold are matching
in the corresponding index. Currently not support multiple col_unit(pairs).
"""
conn = sqlite3.connect(db)
cursor = conn.cursor()
try:
cursor.execute(p_str)
... |
return 1 if the values between prediction and gold are matching
in the corresponding index. Currently not support multiple col_unit(pairs).
| eval_exec_match | python | taoyds/spider | evaluation.py | https://github.com/taoyds/spider/blob/master/evaluation.py | Apache-2.0 |
def nodes(self):
"""a generator that returns all the nodes"""
yield self
for child in self.children:
for child_n in child.nodes:
yield child_n | a generator that returns all the nodes | nodes | python | taoyds/spider | baselines/nl2code/astnode.py | https://github.com/taoyds/spider/blob/master/baselines/nl2code/astnode.py | Apache-2.0 |
def to_rule(self, include_value=False):
"""
transform the current AST node to a production rule
"""
rule = Rule(self.type)
for c in self.children:
val = c.value if include_value else None
child = ASTNode(c.type, c.label, val)
rule.add_child(chi... |
transform the current AST node to a production rule
| to_rule | python | taoyds/spider | baselines/nl2code/astnode.py | https://github.com/taoyds/spider/blob/master/baselines/nl2code/astnode.py | Apache-2.0 |
def get_productions(self, include_value_node=False):
"""
get the depth-first, left-to-right sequence of rule applications
returns a list of production rules and a map to their parent rules
attention: node value is not included in child nodes
"""
rule_list = list()
... |
get the depth-first, left-to-right sequence of rule applications
returns a list of production rules and a map to their parent rules
attention: node value is not included in child nodes
| get_productions | python | taoyds/spider | baselines/nl2code/astnode.py | https://github.com/taoyds/spider/blob/master/baselines/nl2code/astnode.py | Apache-2.0 |
def get_action_parent_t(self):
"""
get the time step when the parent of the current
action was generated
WARNING: 0 will be returned if parent if None
"""
nt = self.frontier_nt()
# if nt is a non-finishing leaf
# if nt.holds_value:
# return nt... |
get the time step when the parent of the current
action was generated
WARNING: 0 will be returned if parent if None
| get_action_parent_t | python | taoyds/spider | baselines/nl2code/components.py | https://github.com/taoyds/spider/blob/master/baselines/nl2code/components.py | Apache-2.0 |
def canonicalize_query(query):
"""
canonicalize the query, replace strings to a special place holder
"""
str_count = 0
str_map = dict()
matches = QUOTED_STRING_RE.findall(query)
# de-duplicate
cur_replaced_strs = set()
for match in matches:
# If one or more groups are presen... |
canonicalize the query, replace strings to a special place holder
| canonicalize_query | python | taoyds/spider | baselines/nl2code/dataset.py | https://github.com/taoyds/spider/blob/master/baselines/nl2code/dataset.py | Apache-2.0 |
def decode_query(query):
"""decode a given natural language query, return a list of generated candidates"""
query, str_map = canonicalize_query(query)
vocab = train_data.annot_vocab
query_tokens = query.split(' ')
query_tokens_data = [query_to_data(query, vocab)]
example = namedtuple('example', ... | decode a given natural language query, return a list of generated candidates | decode_query | python | taoyds/spider | baselines/nl2code/interactive_mode.py | https://github.com/taoyds/spider/blob/master/baselines/nl2code/interactive_mode.py | Apache-2.0 |
def __init__(self, rules):
"""
instantiate a grammar with a set of production rules of type Rule
"""
self.rules = rules
self.rule_index = defaultdict(list)
self.rule_to_id = OrderedDict()
node_types = set()
lhs_nodes = set()
rhs_nodes = set()
... |
instantiate a grammar with a set of production rules of type Rule
| __init__ | python | taoyds/spider | baselines/nl2code/lang/grammar.py | https://github.com/taoyds/spider/blob/master/baselines/nl2code/lang/grammar.py | Apache-2.0 |
def parse(code):
"""
parse a python code into a tree structure
code -> AST tree -> AST tree to internal tree structure
"""
code = canonicalize_code(code)
py_ast = ast.parse(code)
tree = python_ast_to_parse_tree(py_ast.body[0])
tree = add_root(tree)
return tree |
parse a python code into a tree structure
code -> AST tree -> AST tree to internal tree structure
| parse | python | taoyds/spider | baselines/nl2code/lang/py/parse.py | https://github.com/taoyds/spider/blob/master/baselines/nl2code/lang/py/parse.py | Apache-2.0 |
def get_terminal_tokens(_terminal_str):
"""
get terminal tokens
break words like MinionCards into [Minion, Cards]
"""
tmp_terminal_tokens = [t for t in _terminal_str.split(' ') if len(t) > 0]
_terminal_tokens = []
for token in tmp_terminal_tokens:
sub_... |
get terminal tokens
break words like MinionCards into [Minion, Cards]
| get_terminal_tokens | python | taoyds/spider | baselines/nl2code/lang/py/py_dataset.py | https://github.com/taoyds/spider/blob/master/baselines/nl2code/lang/py/py_dataset.py | Apache-2.0 |
def break_value_nodes(tree, hs=False):
"""inplace break value nodes with a string separaed by spaces"""
if tree.type == str and tree.value is not None:
assert tree.is_leaf
if hs:
tokens = re.sub(r'([a-z])([A-Z])', r'\1 #MERGE# \2', tree.value).split(' ')
else:
to... | inplace break value nodes with a string separaed by spaces | break_value_nodes | python | taoyds/spider | baselines/nl2code/lang/py/seq2tree_exp.py | https://github.com/taoyds/spider/blob/master/baselines/nl2code/lang/py/seq2tree_exp.py | Apache-2.0 |
def get_terminal_tokens(_terminal_str):
"""
get terminal tokens
break words like MinionCards into [Minion, Cards]
"""
tmp_terminal_tokens = [t for t in _terminal_str.split(' ') if len(t) > 0]
_terminal_tokens = []
for token in tmp_terminal_tokens:
sub_tokens = re.sub(r'([a-z])([A-Z])... |
get terminal tokens
break words like MinionCards into [Minion, Cards]
| get_terminal_tokens | python | taoyds/spider | baselines/nl2code/lang/sql/sql_dataset.py | https://github.com/taoyds/spider/blob/master/baselines/nl2code/lang/sql/sql_dataset.py | Apache-2.0 |
def lecun_uniform(shape):
''' Reference: LeCun 98, Efficient Backprop
http://yann.lecun.com/exdb/publis/pdf/lecun-98b.pdf
'''
fan_in, fan_out = get_fans(shape)
scale = np.sqrt(3. / fan_in)
return uniform(shape, scale) | Reference: LeCun 98, Efficient Backprop
http://yann.lecun.com/exdb/publis/pdf/lecun-98b.pdf
| lecun_uniform | python | taoyds/spider | baselines/nl2code/nn/initializations.py | https://github.com/taoyds/spider/blob/master/baselines/nl2code/nn/initializations.py | Apache-2.0 |
def he_normal(shape):
''' Reference: He et al., http://arxiv.org/abs/1502.01852
'''
fan_in, fan_out = get_fans(shape)
s = np.sqrt(2. / fan_in)
return normal(shape, s) | Reference: He et al., http://arxiv.org/abs/1502.01852
| he_normal | python | taoyds/spider | baselines/nl2code/nn/initializations.py | https://github.com/taoyds/spider/blob/master/baselines/nl2code/nn/initializations.py | Apache-2.0 |
def categorical_crossentropy(y_true, y_pred):
'''Expects a binary class matrix instead of a vector of scalar classes
'''
y_pred = T.clip(y_pred, epsilon, 1.0 - epsilon)
# scale preds so that the class probas of each sample sum to 1
y_pred /= y_pred.sum(axis=-1, keepdims=True)
cce = T.nnet.catego... | Expects a binary class matrix instead of a vector of scalar classes
| categorical_crossentropy | python | taoyds/spider | baselines/nl2code/nn/objectives.py | https://github.com/taoyds/spider/blob/master/baselines/nl2code/nn/objectives.py | Apache-2.0 |
def pad_sequences(sequences, maxlen=None, dtype='int32',
padding='pre', truncating='pre', value=0.):
'''Pads each sequence to the same length:
the length of the longest sequence.
If maxlen is provided, any sequence longer
than maxlen is truncated to maxlen.
Truncation happens off ... | Pads each sequence to the same length:
the length of the longest sequence.
If maxlen is provided, any sequence longer
than maxlen is truncated to maxlen.
Truncation happens off either the beginning (default) or
the end of the sequence.
Supports post-padding and pre-padding (default).
# Ar... | pad_sequences | python | taoyds/spider | baselines/nl2code/nn/utils/generic_utils.py | https://github.com/taoyds/spider/blob/master/baselines/nl2code/nn/utils/generic_utils.py | Apache-2.0 |
def __init__(self, target, width=30, verbose=1):
'''
@param target: total number of steps expected
'''
self.width = width
self.target = target
self.sum_values = {}
self.unique_values = []
self.start = time.time()
self.total_width = 0
se... |
@param target: total number of steps expected
| __init__ | python | taoyds/spider | baselines/nl2code/nn/utils/generic_utils.py | https://github.com/taoyds/spider/blob/master/baselines/nl2code/nn/utils/generic_utils.py | Apache-2.0 |
def update(self, current, values=[]):
'''
@param current: index of current step
@param values: list of tuples (name, value_for_last_step).
The progress bar will display averages for these values.
'''
for k, v in values:
if k not in self.sum_values:... |
@param current: index of current step
@param values: list of tuples (name, value_for_last_step).
The progress bar will display averages for these values.
| update | python | taoyds/spider | baselines/nl2code/nn/utils/generic_utils.py | https://github.com/taoyds/spider/blob/master/baselines/nl2code/nn/utils/generic_utils.py | Apache-2.0 |
def to_categorical(y, nb_classes=None):
'''Convert class vector (integers from 0 to nb_classes)
to binary class matrix, for use with categorical_crossentropy
'''
y = np.asarray(y, dtype='int32')
if not nb_classes:
nb_classes = np.max(y)+1
Y = np.zeros((len(y), nb_classes))
for i in r... | Convert class vector (integers from 0 to nb_classes)
to binary class matrix, for use with categorical_crossentropy
| to_categorical | python | taoyds/spider | baselines/nl2code/nn/utils/np_utils.py | https://github.com/taoyds/spider/blob/master/baselines/nl2code/nn/utils/np_utils.py | Apache-2.0 |
def get_test_data(nb_train=1000, nb_test=500, input_shape=(10,), output_shape=(2,),
classification=True, nb_class=2):
'''
classification=True overrides output_shape
(i.e. output_shape is set to (1,)) and the output
consists in integers in [0, nb_class-1].
Otherwise... |
classification=True overrides output_shape
(i.e. output_shape is set to (1,)) and the output
consists in integers in [0, nb_class-1].
Otherwise: float output with shape output_shape.
| get_test_data | python | taoyds/spider | baselines/nl2code/nn/utils/test_utils.py | https://github.com/taoyds/spider/blob/master/baselines/nl2code/nn/utils/test_utils.py | Apache-2.0 |
def ensure_in_spec(spec, key):
"""
If key is not in spec, requests a value from the user and modifies
spec to include that key:value pair.
Args:
spec: A dictionary specifying the experiment.
key: A string that may or may not be in the dictionary.
Modifies:
spec
"""
if not k... |
If key is not in spec, requests a value from the user and modifies
spec to include that key:value pair.
Args:
spec: A dictionary specifying the experiment.
key: A string that may or may not be in the dictionary.
Modifies:
spec
| ensure_in_spec | python | taoyds/spider | baselines/seq2seq_attention_copy/config_builder.py | https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/config_builder.py | Apache-2.0 |
def expand_data_dirs(spec):
"""
Makes sure all data directories exist and contain required
files. Then adds the locations of train_encode, train_decode,
train_schema_locations, dev_encode, dev_decode,
dev_schema_locations, and tentative locations of vocabulary to
spec.
Args:
spec: a sp... |
Makes sure all data directories exist and contain required
files. Then adds the locations of train_encode, train_decode,
train_schema_locations, dev_encode, dev_decode,
dev_schema_locations, and tentative locations of vocabulary to
spec.
Args:
spec: a specification that contains "data_dir... | expand_data_dirs | python | taoyds/spider | baselines/seq2seq_attention_copy/config_builder.py | https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/config_builder.py | Apache-2.0 |
def single_vocab_file(spec, required_files_dict, vocab_fname):
"""
Given a list of vocabulary file paths, return a path to a single
vocabulary file that incorporates all of the vocabularies. If the
list is a single path, this simply returns that path. Otherwise,
we build a combined vocabulary file i... |
Given a list of vocabulary file paths, return a path to a single
vocabulary file that incorporates all of the vocabularies. If the
list is a single path, this simply returns that path. Otherwise,
we build a combined vocabulary file in the model_dir from spec
and return the path to that file.
| single_vocab_file | python | taoyds/spider | baselines/seq2seq_attention_copy/config_builder.py | https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/config_builder.py | Apache-2.0 |
def create_experiment(output_dir):
"""
Creates a new Experiment instance.
Args:
output_dir: Output directory for model checkpoints and summaries.
"""
config = run_config.RunConfig(
tf_random_seed=FLAGS.tf_random_seed,
save_checkpoints_secs=FLAGS.save_checkpoints_secs,
save_checkpoints_... |
Creates a new Experiment instance.
Args:
output_dir: Output directory for model checkpoints and summaries.
| create_experiment | python | taoyds/spider | baselines/seq2seq_attention_copy/bin/train.py | https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/bin/train.py | Apache-2.0 |
def process_story(text):
"""Processed a story text into an (article, summary) tuple.
"""
# Split by highlights
elements = text.split("@highlight")
elements = [_.strip() for _ in elements]
story_text = elements[0]
highlights = elements[1:]
# Join all highlights into a single blob
highlights_joined = ... | Processed a story text into an (article, summary) tuple.
| process_story | python | taoyds/spider | baselines/seq2seq_attention_copy/bin/data/cnn_daily_mail_summarization/process_story.py | https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/bin/data/cnn_daily_mail_summarization/process_story.py | Apache-2.0 |
def make_copy(num_examples, min_len, max_len):
"""
Generates a dataset where the target is equal to the source.
Sequence lengths are chosen randomly from [min_len, max_len].
Args:
num_examples: Number of examples to generate
min_len: Minimum sequence length
max_len: Maximum sequence length
Retur... |
Generates a dataset where the target is equal to the source.
Sequence lengths are chosen randomly from [min_len, max_len].
Args:
num_examples: Number of examples to generate
min_len: Minimum sequence length
max_len: Maximum sequence length
Returns:
An iterator of (source, target) string tuple... | make_copy | python | taoyds/spider | baselines/seq2seq_attention_copy/bin/tools/generate_toy_data.py | https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/bin/tools/generate_toy_data.py | Apache-2.0 |
def make_reverse(num_examples, min_len, max_len):
"""
Generates a dataset where the target is equal to the source reversed.
Sequence lengths are chosen randomly from [min_len, max_len].
Args:
num_examples: Number of examples to generate
min_len: Minimum sequence length
max_len: Maximum sequence len... |
Generates a dataset where the target is equal to the source reversed.
Sequence lengths are chosen randomly from [min_len, max_len].
Args:
num_examples: Number of examples to generate
min_len: Minimum sequence length
max_len: Maximum sequence length
Returns:
An iterator of (source, target) str... | make_reverse | python | taoyds/spider | baselines/seq2seq_attention_copy/bin/tools/generate_toy_data.py | https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/bin/tools/generate_toy_data.py | Apache-2.0 |
def write_parallel_text(sources, targets, output_prefix):
"""
Writes two files where each line corresponds to one example
- [output_prefix].sources.txt
- [output_prefix].targets.txt
Args:
sources: Iterator of source strings
targets: Iterator of target strings
output_prefix: Prefix for the out... |
Writes two files where each line corresponds to one example
- [output_prefix].sources.txt
- [output_prefix].targets.txt
Args:
sources: Iterator of source strings
targets: Iterator of target strings
output_prefix: Prefix for the output file
| write_parallel_text | python | taoyds/spider | baselines/seq2seq_attention_copy/bin/tools/generate_toy_data.py | https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/bin/tools/generate_toy_data.py | Apache-2.0 |
def _register_function_ops(func_list):
"""Registers custom ops in the default graph. This is needed
Because our checkpoint is saved with ops that are not part of Tensorflow."""
op_dict = op_def_registry.get_registered_ops()
for func in func_list:
#pylint: disable=W0212
func._create_definition_if_needed(... | Registers custom ops in the default graph. This is needed
Because our checkpoint is saved with ops that are not part of Tensorflow. | _register_function_ops | python | taoyds/spider | baselines/seq2seq_attention_copy/bin/tools/profile.py | https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/bin/tools/profile.py | Apache-2.0 |
def load_metadata(model_dir):
"""Loads RunMetadata, Graph and OpLog from files
"""
# Import RunMetadata
run_meta_path = os.path.join(model_dir, "metadata/run_meta")
run_meta = tf.RunMetadata()
if gfile.Exists(run_meta_path):
with gfile.GFile(run_meta_path, "rb") as file:
run_meta.MergeFromString(f... | Loads RunMetadata, Graph and OpLog from files
| load_metadata | python | taoyds/spider | baselines/seq2seq_attention_copy/bin/tools/profile.py | https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/bin/tools/profile.py | Apache-2.0 |
def merge_default_with_oplog(graph, op_log=None, run_meta=None):
"""Monkeypatch. There currently is a bug in tfprof_logger that
prevents it from being used with Python 3. So we override the method
manually until the fix comes in.
"""
tmp_op_log = tfprof_log_pb2.OpLog()
# pylint: disable=W0212
logged_o... | Monkeypatch. There currently is a bug in tfprof_logger that
prevents it from being used with Python 3. So we override the method
manually until the fix comes in.
| merge_default_with_oplog | python | taoyds/spider | baselines/seq2seq_attention_copy/bin/tools/profile.py | https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/bin/tools/profile.py | Apache-2.0 |
def _create_from_dict(dict_, default_module, *args, **kwargs):
"""Creates a configurable class from a dictionary. The dictionary must have
"class" and "params" properties. The class can be either fully qualified, or
it is looked up in the modules passed via `default_module`.
"""
class_ = locate(dict_["class"]... | Creates a configurable class from a dictionary. The dictionary must have
"class" and "params" properties. The class can be either fully qualified, or
it is looked up in the modules passed via `default_module`.
| _create_from_dict | python | taoyds/spider | baselines/seq2seq_attention_copy/seq2seq/configurable.py | https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/configurable.py | Apache-2.0 |
def _maybe_load_yaml(item):
"""Parses `item` only if it is a string. If `item` is a dictionary
it is returned as-is.
"""
if isinstance(item, six.string_types):
return yaml.load(item)
elif isinstance(item, dict):
return item
else:
raise ValueError("Got {}, expected YAML string or dict", type(item... | Parses `item` only if it is a string. If `item` is a dictionary
it is returned as-is.
| _maybe_load_yaml | python | taoyds/spider | baselines/seq2seq_attention_copy/seq2seq/configurable.py | https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/configurable.py | Apache-2.0 |
def _parse_params(params, default_params):
"""Parses parameter values to the types defined by the default parameters.
Default parameters are used for missing values.
"""
# Cast parameters to correct types
if params is None:
params = {}
result = copy.deepcopy(default_params)
for key, value in params.it... | Parses parameter values to the types defined by the default parameters.
Default parameters are used for missing values.
| _parse_params | python | taoyds/spider | baselines/seq2seq_attention_copy/seq2seq/configurable.py | https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/configurable.py | Apache-2.0 |
def __init__(self, name):
"""
Initialize the module. Each subclass must call this constructor with a name.
Args:
name: Name of this module. Used for `tf.make_template`.
"""
self.name = name
self._template = tf.make_template(name, self._build, create_scope_now_=True)
# Docstrings for t... |
Initialize the module. Each subclass must call this constructor with a name.
Args:
name: Name of this module. Used for `tf.make_template`.
| __init__ | python | taoyds/spider | baselines/seq2seq_attention_copy/seq2seq/graph_module.py | https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/graph_module.py | Apache-2.0 |
def templatemethod(name_):
"""This decorator wraps a method with `tf.make_template`. For example,
@templatemethod
def my_method():
# Create variables
"""
def template_decorator(func):
"""Inner decorator function"""
def func_wrapper(*args, **kwargs):
"""Inner wrapper function"""
temp... | This decorator wraps a method with `tf.make_template`. For example,
@templatemethod
def my_method():
# Create variables
| templatemethod | python | taoyds/spider | baselines/seq2seq_attention_copy/seq2seq/graph_utils.py | https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/graph_utils.py | Apache-2.0 |
def add_dict_to_collection(dict_, collection_name):
"""Adds a dictionary to a graph collection.
Args:
dict_: A dictionary of string keys to tensor values
collection_name: The name of the collection to add the dictionary to
"""
key_collection = collection_name + "_keys"
value_collection = collection_n... | Adds a dictionary to a graph collection.
Args:
dict_: A dictionary of string keys to tensor values
collection_name: The name of the collection to add the dictionary to
| add_dict_to_collection | python | taoyds/spider | baselines/seq2seq_attention_copy/seq2seq/graph_utils.py | https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/graph_utils.py | Apache-2.0 |
def get_dict_from_collection(collection_name):
"""Gets a dictionary from a graph collection.
Args:
collection_name: A collection name to read a dictionary from
Returns:
A dictionary with string keys and tensor values
"""
key_collection = collection_name + "_keys"
value_collection = collection_name... | Gets a dictionary from a graph collection.
Args:
collection_name: A collection name to read a dictionary from
Returns:
A dictionary with string keys and tensor values
| get_dict_from_collection | python | taoyds/spider | baselines/seq2seq_attention_copy/seq2seq/graph_utils.py | https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/graph_utils.py | Apache-2.0 |
def cross_entropy_sequence_loss(logits, targets, sequence_length):
"""Calculates the per-example cross-entropy loss for a sequence of logits and
masks out all losses passed the sequence length.
Args:
logits: Logits of shape `[T, B, vocab_size]`
targets: Target classes of shape `[T, B]`
sequence_len... | Calculates the per-example cross-entropy loss for a sequence of logits and
masks out all losses passed the sequence length.
Args:
logits: Logits of shape `[T, B, vocab_size]`
targets: Target classes of shape `[T, B]`
sequence_length: An int32 tensor of shape `[B]` corresponding
to the length of... | cross_entropy_sequence_loss | python | taoyds/spider | baselines/seq2seq_attention_copy/seq2seq/losses.py | https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/losses.py | Apache-2.0 |
def _has_training_stopped(self, eval_result):
"""Determines whether the training has stopped."""
if not eval_result:
return False
global_step = eval_result.get(tf.GraphKeys.GLOBAL_STEP)
return global_step and self._train_steps and (
global_step >= self._train_steps) | Determines whether the training has stopped. | _has_training_stopped | python | taoyds/spider | baselines/seq2seq_attention_copy/seq2seq/contrib/experiment.py | https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/contrib/experiment.py | Apache-2.0 |
def continuous_train_and_eval(self,
continuous_eval_predicate_fn=None):
"""Interleaves training and evaluation.
The frequency of evaluation is controlled by the `train_steps_per_iteration`
(via constructor). The model will be first trained for
`train_steps_per_iteration`... | Interleaves training and evaluation.
The frequency of evaluation is controlled by the `train_steps_per_iteration`
(via constructor). The model will be first trained for
`train_steps_per_iteration`, and then be evaluated in turns.
This differs from `train_and_evaluate` as follows:
1. The procedur... | continuous_train_and_eval | python | taoyds/spider | baselines/seq2seq_attention_copy/seq2seq/contrib/experiment.py | https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/contrib/experiment.py | Apache-2.0 |
def __init__(self,
cells,
residual_connections=False,
residual_combiner="add",
residual_dense=False):
"""Create a RNN cell composed sequentially of a number of RNNCells.
Args:
cells: list of RNNCells that will be composed in this order.
st... | Create a RNN cell composed sequentially of a number of RNNCells.
Args:
cells: list of RNNCells that will be composed in this order.
state_is_tuple: If True, accepted and returned states are n-tuples, where
`n = len(cells)`. If False, the states are all
concatenated along the column axi... | __init__ | python | taoyds/spider | baselines/seq2seq_attention_copy/seq2seq/contrib/rnn_cell.py | https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/contrib/rnn_cell.py | Apache-2.0 |
def __call__(self, inputs, state, scope=None):
"""Run this multi-layer cell on inputs, starting from state."""
if not self._residual_connections:
return super(ExtendedMultiRNNCell, self).__call__(
inputs, state, (scope or "extended_multi_rnn_cell"))
with tf.variable_scope(scope or "extended... | Run this multi-layer cell on inputs, starting from state. | __call__ | python | taoyds/spider | baselines/seq2seq_attention_copy/seq2seq/contrib/rnn_cell.py | https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/contrib/rnn_cell.py | Apache-2.0 |
def _transpose_batch_time(x):
"""Transpose the batch and time dimensions of a Tensor.
Retains as much of the static shape information as possible.
Args:
x: A tensor of rank 2 or higher.
Returns:
x transposed along the first two dimensions.
Raises:
ValueError: if `x` is rank 1 or lower.
"""
... | Transpose the batch and time dimensions of a Tensor.
Retains as much of the static shape information as possible.
Args:
x: A tensor of rank 2 or higher.
Returns:
x transposed along the first two dimensions.
Raises:
ValueError: if `x` is rank 1 or lower.
| _transpose_batch_time | python | taoyds/spider | baselines/seq2seq_attention_copy/seq2seq/contrib/seq2seq/decoder.py | https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/contrib/seq2seq/decoder.py | Apache-2.0 |
def dynamic_decode(decoder,
output_time_major=False,
impute_finished=False,
maximum_iterations=None,
parallel_iterations=32,
swap_memory=False,
scope=None):
"""Perform dynamic decoding with `decoder`.
... | Perform dynamic decoding with `decoder`.
Args:
decoder: A `Decoder` instance.
output_time_major: Python boolean. Default: `False` (batch major). If
`True`, outputs are returned as time major tensors (this mode is faster).
Otherwise, outputs are returned as batch major tensors (this adds extra
... | dynamic_decode | python | taoyds/spider | baselines/seq2seq_attention_copy/seq2seq/contrib/seq2seq/decoder.py | https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/contrib/seq2seq/decoder.py | Apache-2.0 |
def body(time, outputs_ta, state, inputs, finished):
"""Internal while_loop body.
Args:
time: scalar int32 tensor.
outputs_ta: structure of TensorArray.
state: (structure of) state tensors and TensorArrays.
inputs: (structure of) input tensors.
finished: 1-D bool ten... | Internal while_loop body.
Args:
time: scalar int32 tensor.
outputs_ta: structure of TensorArray.
state: (structure of) state tensors and TensorArrays.
inputs: (structure of) input tensors.
finished: 1-D bool tensor.
Returns:
`(time + 1, outputs_ta, next_stat... | body | python | taoyds/spider | baselines/seq2seq_attention_copy/seq2seq/contrib/seq2seq/decoder.py | https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/contrib/seq2seq/decoder.py | Apache-2.0 |
def __init__(self, inputs, sequence_length, embedding, sampling_probability,
time_major=False, seed=None, scheduling_seed=None, name=None):
"""Initializer.
Args:
inputs: A (structure of) input tensors.
sequence_length: An int32 vector tensor.
embedding: A callable that takes a ... | Initializer.
Args:
inputs: A (structure of) input tensors.
sequence_length: An int32 vector tensor.
embedding: A callable that takes a vector tensor of `ids` (argmax ids),
or the `params` argument for `embedding_lookup`.
sampling_probability: A 0D `float32` tensor: the probability o... | __init__ | python | taoyds/spider | baselines/seq2seq_attention_copy/seq2seq/contrib/seq2seq/helper.py | https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/contrib/seq2seq/helper.py | Apache-2.0 |
def __init__(self, inputs, sequence_length, sampling_probability,
time_major=False, seed=None, next_input_layer=None,
auxiliary_inputs=None, name=None):
"""Initializer.
Args:
inputs: A (structure) of input tensors.
sequence_length: An int32 vector tensor.
samplin... | Initializer.
Args:
inputs: A (structure) of input tensors.
sequence_length: An int32 vector tensor.
sampling_probability: A 0D `float32` tensor: the probability of sampling
from the outputs instead of reading directly from the inputs.
time_major: Python bool. Whether the tensors in... | __init__ | python | taoyds/spider | baselines/seq2seq_attention_copy/seq2seq/contrib/seq2seq/helper.py | https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/contrib/seq2seq/helper.py | Apache-2.0 |
def __init__(self, embedding, start_tokens, end_token):
"""Initializer.
Args:
embedding: A callable that takes a vector tensor of `ids` (argmax ids),
or the `params` argument for `embedding_lookup`.
start_tokens: `int32` vector shaped `[batch_size]`, the start tokens.
end_token: `int3... | Initializer.
Args:
embedding: A callable that takes a vector tensor of `ids` (argmax ids),
or the `params` argument for `embedding_lookup`.
start_tokens: `int32` vector shaped `[batch_size]`, the start tokens.
end_token: `int32` scalar, the token that marks end of decoding.
Raises:
... | __init__ | python | taoyds/spider | baselines/seq2seq_attention_copy/seq2seq/contrib/seq2seq/helper.py | https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/contrib/seq2seq/helper.py | Apache-2.0 |
def decode(self, data, items):
"""
Args:
data: List of [target_string, source_tokens_list, schema_location].
items: A list of strings, each of which indicate a particular data
type.
Returns: A dictionary with a tensor for each item in items.
"""
i... |
Args:
data: List of [target_string, source_tokens_list, schema_location].
items: A list of strings, each of which indicate a particular data
type.
Returns: A dictionary with a tensor for each item in items.
| decode | python | taoyds/spider | baselines/seq2seq_attention_copy/seq2seq/data/copying_decoder.py | https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/data/copying_decoder.py | Apache-2.0 |
def _mark_copies(self, tokenized, copy_source, copy_token):
"""Replace any token in tokenized that can be copied from copy_source
with the copy_token, and build a tensor with the indices of the copied
item in the source.
For instance, could be used with the query
SELECT NUM_CRE... | Replace any token in tokenized that can be copied from copy_source
with the copy_token, and build a tensor with the indices of the copied
item in the source.
For instance, could be used with the query
SELECT NUM_CREDITS FROM COURSE WHERE
DEPARTMENT = " EECS " AND NUMBER = 280... | _mark_copies | python | taoyds/spider | baselines/seq2seq_attention_copy/seq2seq/data/copying_decoder.py | https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/data/copying_decoder.py | Apache-2.0 |
def decode(self, data, items):
"""
Args:
data: List of [target_string, source_tokens_list, schema_tokens_list].
items: A list of strings, each of which indicate a particular data type.
Returns: A tensor for each item in items.
"""
decoded_items = super(SchemaA... |
Args:
data: List of [target_string, source_tokens_list, schema_tokens_list].
items: A list of strings, each of which indicate a particular data type.
Returns: A tensor for each item in items.
| decode | python | taoyds/spider | baselines/seq2seq_attention_copy/seq2seq/data/copying_decoder.py | https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/data/copying_decoder.py | Apache-2.0 |
def decode(self, data, items):
"""
Args:
data: List of [target_string, None, schema_tokens_list].
items: A list of strings, each of which indicate a particular data type.
Returns: A tensor for each item in items.
"""
decoded_items = super(SchemaCopyingDecoder,... |
Args:
data: List of [target_string, None, schema_tokens_list].
items: A list of strings, each of which indicate a particular data type.
Returns: A tensor for each item in items.
| decode | python | taoyds/spider | baselines/seq2seq_attention_copy/seq2seq/data/copying_decoder.py | https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/data/copying_decoder.py | Apache-2.0 |
def decode(self, data, items):
"""
Args:
data: List of [target_string, source_tokens_list, None].
items: A list of strings, each of which indicate a particular data type.
Returns: A tensor for each item in items.
"""
decoded_items = super(WordCopyingDecoder, s... |
Args:
data: List of [target_string, source_tokens_list, None].
items: A list of strings, each of which indicate a particular data type.
Returns: A tensor for each item in items.
| decode | python | taoyds/spider | baselines/seq2seq_attention_copy/seq2seq/data/copying_decoder.py | https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/data/copying_decoder.py | Apache-2.0 |
def get_word_vector(input_string, model, column_map, table_map, separate_word_dict):
'''
Given an input string and a gensim Word2Vec model, return a vector
representation of the string.
'''
if len(input_string) == 0:
return np.zeros(len(model['the']))
# Split on underscores and whi... |
Given an input string and a gensim Word2Vec model, return a vector
representation of the string.
| get_word_vector | python | taoyds/spider | baselines/seq2seq_attention_copy/seq2seq/data/embeddings.py | https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/data/embeddings.py | Apache-2.0 |
def make_input_pipeline_from_def(def_dict, mode, **kwargs):
"""Creates an InputPipeline object from a dictionary definition.
Args:
def_dict: A dictionary defining the input pipeline.
It must have "class" and "params" that correspond to the class
name and constructor parameters of an InputPipeline, ... | Creates an InputPipeline object from a dictionary definition.
Args:
def_dict: A dictionary defining the input pipeline.
It must have "class" and "params" that correspond to the class
name and constructor parameters of an InputPipeline, respectively.
mode: A value in tf.contrib.learn.ModeKeys
R... | make_input_pipeline_from_def | python | taoyds/spider | baselines/seq2seq_attention_copy/seq2seq/data/input_pipeline.py | https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/data/input_pipeline.py | Apache-2.0 |
def read_from_data_provider(data_provider):
"""Utility function to read all available items from a DataProvider.
"""
item_values = data_provider.get(list(data_provider.list_items()))
items_dict = dict(zip(data_provider.list_items(), item_values))
return items_dict | Utility function to read all available items from a DataProvider.
| read_from_data_provider | python | taoyds/spider | baselines/seq2seq_attention_copy/seq2seq/data/input_pipeline.py | https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/data/input_pipeline.py | Apache-2.0 |
def slice_text(text,
eos_token="SEQUENCE_END",
sos_token="SEQUENCE_START"):
"""Slices text from SEQUENCE_START to SEQUENCE_END, not including
these special tokens.
"""
eos_index = text.find(eos_token)
text = text[:eos_index] if eos_index > -1 else text
sos_index = text.find(sos... | Slices text from SEQUENCE_START to SEQUENCE_END, not including
these special tokens.
| slice_text | python | taoyds/spider | baselines/seq2seq_attention_copy/seq2seq/data/postproc.py | https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/data/postproc.py | Apache-2.0 |
def __init__(self, context_keys_to_features, sequence_keys_to_features,
items_to_handlers):
"""Constructs the decoder.
Args:
keys_to_features: a dictionary from TF-Example keys to either
tf.VarLenFeature or tf.FixedLenFeature instances. See tensorflow's
parsing_ops.py.
... | Constructs the decoder.
Args:
keys_to_features: a dictionary from TF-Example keys to either
tf.VarLenFeature or tf.FixedLenFeature instances. See tensorflow's
parsing_ops.py.
items_to_handlers: a dictionary from items (strings) to ItemHandler
instances. Note that the ItemHandler'... | __init__ | python | taoyds/spider | baselines/seq2seq_attention_copy/seq2seq/data/sequence_example_decoder.py | https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/data/sequence_example_decoder.py | Apache-2.0 |
def decode(self, serialized_example, items=None):
"""Decodes the given serialized TF-example.
Args:
serialized_example: a serialized TF-example tensor.
items: the list of items to decode. These must be a subset of the item
keys in self._items_to_handlers. If `items` is left as None, then all... | Decodes the given serialized TF-example.
Args:
serialized_example: a serialized TF-example tensor.
items: the list of items to decode. These must be a subset of the item
keys in self._items_to_handlers. If `items` is left as None, then all
of the items in self._items_to_handlers are deco... | decode | python | taoyds/spider | baselines/seq2seq_attention_copy/seq2seq/data/sequence_example_decoder.py | https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/data/sequence_example_decoder.py | Apache-2.0 |
def get_vocab_info(vocab_path):
"""Creates a `VocabInfo` instance that contains the vocabulary size and
the special vocabulary for the given file.
Args:
vocab_path: Path to a vocabulary file with one word per line.
Returns:
A VocabInfo tuple.
"""
with gfile.GFile(vocab_path) as file:
vocab_s... | Creates a `VocabInfo` instance that contains the vocabulary size and
the special vocabulary for the given file.
Args:
vocab_path: Path to a vocabulary file with one word per line.
Returns:
A VocabInfo tuple.
| get_vocab_info | python | taoyds/spider | baselines/seq2seq_attention_copy/seq2seq/data/vocab.py | https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/data/vocab.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.