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 __init__(self, function=None, name=None, description=None): """ Creates an attribute with `function`. Adds a name and a description if it's specified. """ self.name = name self.function = function self.description = description
Creates an attribute with `function`. Adds a name and a description if it's specified.
__init__
python
simpleai-team/simpleai
simpleai/machine_learning/models.py
https://github.com/simpleai-team/simpleai/blob/master/simpleai/machine_learning/models.py
MIT
def is_attribute(method, name=None): """ Decorator for methods that are attributes. """ if name is None: name = method.__name__ method.is_attribute = True method.name = name return method
Decorator for methods that are attributes.
is_attribute
python
simpleai-team/simpleai
simpleai/machine_learning/models.py
https://github.com/simpleai-team/simpleai/blob/master/simpleai/machine_learning/models.py
MIT
def boltzmann_exploration(actions, utilities, temperature, action_counter): '''returns an action with a probability depending on utilities and temperature''' utilities = [utilities[x] for x in actions] temperature = max(temperature, 0.01) _max = max(utilities) _min = min(utilities) if _max == _m...
returns an action with a probability depending on utilities and temperature
boltzmann_exploration
python
simpleai-team/simpleai
simpleai/machine_learning/reinforcement_learning.py
https://github.com/simpleai-team/simpleai/blob/master/simpleai/machine_learning/reinforcement_learning.py
MIT
def make_exponential_temperature(initial_temperature, alpha): '''returns a function like initial / exp(n * alpha)''' def _function(n): try: return initial_temperature / math.exp(n * alpha) except OverflowError: return 0.01 return _function
returns a function like initial / exp(n * alpha)
make_exponential_temperature
python
simpleai-team/simpleai
simpleai/machine_learning/reinforcement_learning.py
https://github.com/simpleai-team/simpleai/blob/master/simpleai/machine_learning/reinforcement_learning.py
MIT
def revise(domains, arc, constraints): """ Given the arc X, Y (variables), removes the values from X's domain that do not meet the constraint between X and Y. That is, given x1 in X's domain, x1 will be removed from the domain, if there is no value y in Y's domain that makes constraint(X,Y) True, f...
Given the arc X, Y (variables), removes the values from X's domain that do not meet the constraint between X and Y. That is, given x1 in X's domain, x1 will be removed from the domain, if there is no value y in Y's domain that makes constraint(X,Y) True, for those constraints affecting X and Y. ...
revise
python
simpleai-team/simpleai
simpleai/search/arc.py
https://github.com/simpleai-team/simpleai/blob/master/simpleai/search/arc.py
MIT
def all_arcs(constraints): """ For each constraint ((X, Y), const) adds: ((X, Y), const) ((Y, X), const) """ arcs = set() for neighbors, constraint in constraints: if len(neighbors) == 2: x, y = neighbors list(map(arcs.add, ((x, y), (y, x)))) ret...
For each constraint ((X, Y), const) adds: ((X, Y), const) ((Y, X), const)
all_arcs
python
simpleai-team/simpleai
simpleai/search/arc.py
https://github.com/simpleai-team/simpleai/blob/master/simpleai/search/arc.py
MIT
def arc_consistency_3(domains, constraints): """ Makes a CSP problem arc consistent. Ignores any constraint that is not binary. """ arcs = list(all_arcs(constraints)) pending_arcs = set(arcs) while pending_arcs: x, y = pending_arcs.pop() if revise(domains, (x, y), constrain...
Makes a CSP problem arc consistent. Ignores any constraint that is not binary.
arc_consistency_3
python
simpleai-team/simpleai
simpleai/search/arc.py
https://github.com/simpleai-team/simpleai/blob/master/simpleai/search/arc.py
MIT
def backtrack(problem, variable_heuristic='', value_heuristic='', inference=True): ''' Backtracking search. variable_heuristic is the heuristic for variable choosing, can be MOST_CONSTRAINED_VARIABLE, HIGHEST_DEGREE_VARIABLE, or blank for simple ordered choosing. value_heuristic is the heuristi...
Backtracking search. variable_heuristic is the heuristic for variable choosing, can be MOST_CONSTRAINED_VARIABLE, HIGHEST_DEGREE_VARIABLE, or blank for simple ordered choosing. value_heuristic is the heuristic for value choosing, can be LEAST_CONSTRAINING_VALUE or blank for simple ordered choo...
backtrack
python
simpleai-team/simpleai
simpleai/search/csp.py
https://github.com/simpleai-team/simpleai/blob/master/simpleai/search/csp.py
MIT
def _most_constrained_variable_chooser(problem, variables, domains): ''' Choose the variable that has less available values. ''' # the variable with fewer values available return sorted(variables, key=lambda v: len(domains[v]))[0]
Choose the variable that has less available values.
_most_constrained_variable_chooser
python
simpleai-team/simpleai
simpleai/search/csp.py
https://github.com/simpleai-team/simpleai/blob/master/simpleai/search/csp.py
MIT
def _highest_degree_variable_chooser(problem, variables, domains): ''' Choose the variable that is involved on more constraints. ''' # the variable involved in more constraints return sorted(variables, key=lambda v: problem.var_degrees[v], reverse=True)[0]
Choose the variable that is involved on more constraints.
_highest_degree_variable_chooser
python
simpleai-team/simpleai
simpleai/search/csp.py
https://github.com/simpleai-team/simpleai/blob/master/simpleai/search/csp.py
MIT
def _find_conflicts(problem, assignment, variable=None, value=None): ''' Find violated constraints on a given assignment, with the possibility of specifying a new variable and value to add to the assignment before checking. ''' if variable is not None and value is not None: assignment = ...
Find violated constraints on a given assignment, with the possibility of specifying a new variable and value to add to the assignment before checking.
_find_conflicts
python
simpleai-team/simpleai
simpleai/search/csp.py
https://github.com/simpleai-team/simpleai/blob/master/simpleai/search/csp.py
MIT
def _least_constraining_values_sorter(problem, assignment, variable, domains): ''' Sort values based on how many conflicts they generate if assigned. ''' # the value that generates less conflicts def update_assignment(value): new_assignment = deepcopy(assignment) new_assignment[varia...
Sort values based on how many conflicts they generate if assigned.
_least_constraining_values_sorter
python
simpleai-team/simpleai
simpleai/search/csp.py
https://github.com/simpleai-team/simpleai/blob/master/simpleai/search/csp.py
MIT
def convert_to_binary(variables, domains, constraints): """ Returns new constraint list, all binary, using hidden variables. You can use it as previous step when creating a problem. """ def wdiff(vars_): def diff(variables, values): hidden, other = variables if hidd...
Returns new constraint list, all binary, using hidden variables. You can use it as previous step when creating a problem.
convert_to_binary
python
simpleai-team/simpleai
simpleai/search/csp.py
https://github.com/simpleai-team/simpleai/blob/master/simpleai/search/csp.py
MIT
def _all_expander(fringe, iteration, viewer): ''' Expander that expands all nodes on the fringe. ''' expanded_neighbors = [node.expand(local_search=True) for node in fringe] if viewer: viewer.event('expanded', list(fringe), expanded_neighbors) list(map(fringe....
Expander that expands all nodes on the fringe.
_all_expander
python
simpleai-team/simpleai
simpleai/search/local.py
https://github.com/simpleai-team/simpleai/blob/master/simpleai/search/local.py
MIT
def _first_expander(fringe, iteration, viewer): ''' Expander that expands only the first node on the fringe. ''' current = fringe[0] neighbors = current.expand(local_search=True) if viewer: viewer.event('expanded', [current], [neighbors]) fringe.extend(neighbors)
Expander that expands only the first node on the fringe.
_first_expander
python
simpleai-team/simpleai
simpleai/search/local.py
https://github.com/simpleai-team/simpleai/blob/master/simpleai/search/local.py
MIT
def _random_best_expander(fringe, iteration, viewer): ''' Expander that expands one randomly chosen nodes on the fringe that is better than the current (first) node. ''' current = fringe[0] neighbors = current.expand(local_search=True) if viewer: viewer.event('expanded', [current], [...
Expander that expands one randomly chosen nodes on the fringe that is better than the current (first) node.
_random_best_expander
python
simpleai-team/simpleai
simpleai/search/local.py
https://github.com/simpleai-team/simpleai/blob/master/simpleai/search/local.py
MIT
def _create_simulated_annealing_expander(schedule): ''' Creates an expander that has a random chance to choose a node that is worse than the current (first) node, but that chance decreases with time. ''' def _expander(fringe, iteration, viewer): T = schedule(iteration) current = frin...
Creates an expander that has a random chance to choose a node that is worse than the current (first) node, but that chance decreases with time.
_create_simulated_annealing_expander
python
simpleai-team/simpleai
simpleai/search/local.py
https://github.com/simpleai-team/simpleai/blob/master/simpleai/search/local.py
MIT
def _create_genetic_expander(problem, mutation_chance): ''' Creates an expander that expands the bests nodes of the population, crossing over them. ''' def _expander(fringe, iteration, viewer): fitness = [x.value for x in fringe] sampler = InverseTransformSampler(fitness, fringe) ...
Creates an expander that expands the bests nodes of the population, crossing over them.
_create_genetic_expander
python
simpleai-team/simpleai
simpleai/search/local.py
https://github.com/simpleai-team/simpleai/blob/master/simpleai/search/local.py
MIT
def _local_search(problem, fringe_expander, iterations_limit=0, fringe_size=1, random_initial_states=False, stop_when_no_better=True, viewer=None): ''' Basic algorithm for all local search algorithms. ''' if viewer: viewer.event('started') fringe = Bounde...
Basic algorithm for all local search algorithms.
_local_search
python
simpleai-team/simpleai
simpleai/search/local.py
https://github.com/simpleai-team/simpleai/blob/master/simpleai/search/local.py
MIT
def path(self): '''Path (list of nodes and actions) from root to this node.''' node = self path = [] while node: path.append((node.action, node.state)) node = node.parent return list(reversed(path))
Path (list of nodes and actions) from root to this node.
path
python
simpleai-team/simpleai
simpleai/search/models.py
https://github.com/simpleai-team/simpleai/blob/master/simpleai/search/models.py
MIT
def breadth_first(problem, graph_search=False, viewer=None): ''' Breadth first search. If graph_search=True, will avoid exploring repeated states. Requires: SearchProblem.actions, SearchProblem.result, and SearchProblem.is_goal. ''' return _search(problem, FifoList(), ...
Breadth first search. If graph_search=True, will avoid exploring repeated states. Requires: SearchProblem.actions, SearchProblem.result, and SearchProblem.is_goal.
breadth_first
python
simpleai-team/simpleai
simpleai/search/traditional.py
https://github.com/simpleai-team/simpleai/blob/master/simpleai/search/traditional.py
MIT
def depth_first(problem, graph_search=False, viewer=None): ''' Depth first search. If graph_search=True, will avoid exploring repeated states. Requires: SearchProblem.actions, SearchProblem.result, and SearchProblem.is_goal. ''' return _search(problem, LifoList(), ...
Depth first search. If graph_search=True, will avoid exploring repeated states. Requires: SearchProblem.actions, SearchProblem.result, and SearchProblem.is_goal.
depth_first
python
simpleai-team/simpleai
simpleai/search/traditional.py
https://github.com/simpleai-team/simpleai/blob/master/simpleai/search/traditional.py
MIT
def uniform_cost(problem, graph_search=False, viewer=None): ''' Uniform cost search. If graph_search=True, will avoid exploring repeated states. Requires: SearchProblem.actions, SearchProblem.result, SearchProblem.is_goal, and SearchProblem.cost. ''' return _search(problem, ...
Uniform cost search. If graph_search=True, will avoid exploring repeated states. Requires: SearchProblem.actions, SearchProblem.result, SearchProblem.is_goal, and SearchProblem.cost.
uniform_cost
python
simpleai-team/simpleai
simpleai/search/traditional.py
https://github.com/simpleai-team/simpleai/blob/master/simpleai/search/traditional.py
MIT
def greedy(problem, graph_search=False, viewer=None): ''' Greedy search. If graph_search=True, will avoid exploring repeated states. Requires: SearchProblem.actions, SearchProblem.result, SearchProblem.is_goal, SearchProblem.cost, and SearchProblem.heuristic. ''' return _search(problem, ...
Greedy search. If graph_search=True, will avoid exploring repeated states. Requires: SearchProblem.actions, SearchProblem.result, SearchProblem.is_goal, SearchProblem.cost, and SearchProblem.heuristic.
greedy
python
simpleai-team/simpleai
simpleai/search/traditional.py
https://github.com/simpleai-team/simpleai/blob/master/simpleai/search/traditional.py
MIT
def astar(problem, graph_search=False, viewer=None): ''' A* search. If graph_search=True, will avoid exploring repeated states. Requires: SearchProblem.actions, SearchProblem.result, SearchProblem.is_goal, SearchProblem.cost, and SearchProblem.heuristic. ''' return _search(problem, ...
A* search. If graph_search=True, will avoid exploring repeated states. Requires: SearchProblem.actions, SearchProblem.result, SearchProblem.is_goal, SearchProblem.cost, and SearchProblem.heuristic.
astar
python
simpleai-team/simpleai
simpleai/search/traditional.py
https://github.com/simpleai-team/simpleai/blob/master/simpleai/search/traditional.py
MIT
def _search(problem, fringe, graph_search=False, depth_limit=None, node_factory=SearchNode, graph_replace_when_better=False, viewer=None): ''' Basic search algorithm, base of all the other search algorithms. ''' if viewer: viewer.event('started') memory = set() i...
Basic search algorithm, base of all the other search algorithms.
_search
python
simpleai-team/simpleai
simpleai/search/traditional.py
https://github.com/simpleai-team/simpleai/blob/master/simpleai/search/traditional.py
MIT
def test_target_in_attributes(self): """ If target in attributes precision is 1.0. """ self.problem.attributes = [self.target] self.this = self.classifier(self.corpus, self.problem) prec = evaluation.precision(self.this, self.test_set) self.assertEqual(prec, 1.0)
If target in attributes precision is 1.0.
test_target_in_attributes
python
simpleai-team/simpleai
tests/machine_learning/test_classifiers.py
https://github.com/simpleai-team/simpleai/blob/master/tests/machine_learning/test_classifiers.py
MIT
def test_equal_classification(self): """ This checks that the three tree learning methods are equal. """ pseudo = DecisionTreeLearner(self.corpus, self.problem) for test in self.test_set: self.assertEqual(pseudo.classify(test), self.this.classify(test))
This checks that the three tree learning methods are equal.
test_equal_classification
python
simpleai-team/simpleai
tests/machine_learning/test_classifiers.py
https://github.com/simpleai-team/simpleai/blob/master/tests/machine_learning/test_classifiers.py
MIT
def setup_dataset(self): """ Creates a corpus with the iris dataset. Returns the dataset, the attributes getter and the target getter. """ dataset = [] with open(self.IRIS_PATH) as filehandler: file_data = filehandler.read() for line in file_data.spl...
Creates a corpus with the iris dataset. Returns the dataset, the attributes getter and the target getter.
setup_dataset
python
simpleai-team/simpleai
tests/machine_learning/test_classifiers.py
https://github.com/simpleai-team/simpleai/blob/master/tests/machine_learning/test_classifiers.py
MIT
def setup_dataset(self): """ Creates a corpus with n k-bit examples of the parity problem: k random bits followed by a 1 if an odd number of bits are 1, else 0 """ k = 2 n = 100 dataset = [] for i in range(n): # Pseudo random generation of bi...
Creates a corpus with n k-bit examples of the parity problem: k random bits followed by a 1 if an odd number of bits are 1, else 0
setup_dataset
python
simpleai-team/simpleai
tests/machine_learning/test_classifiers.py
https://github.com/simpleai-team/simpleai/blob/master/tests/machine_learning/test_classifiers.py
MIT
def setup_dataset(self): """ Creates a corpus of primes. Returns the dataset, the attributes getter and the target getter. """ size = 105 # Magic number, chosen to avoid an "error" that cannot be # patched in Dtree Pseudo (with modifing the pseudocode). ...
Creates a corpus of primes. Returns the dataset, the attributes getter and the target getter.
setup_dataset
python
simpleai-team/simpleai
tests/machine_learning/test_classifiers.py
https://github.com/simpleai-team/simpleai/blob/master/tests/machine_learning/test_classifiers.py
MIT
def isprime(self, number): """ Returns if a number is prime testing if is divisible by any number from 0 to sqrt(number) """ if number < 2: return False if number == 2: return True if not number & 1: return False for i...
Returns if a number is prime testing if is divisible by any number from 0 to sqrt(number)
isprime
python
simpleai-team/simpleai
tests/machine_learning/test_classifiers.py
https://github.com/simpleai-team/simpleai/blob/master/tests/machine_learning/test_classifiers.py
MIT
def get_ray_directions( H: int, W: int, focal: Union[float, Tuple[float, float]], principal: Optional[Tuple[float, float]] = None, use_pixel_centers: bool = True, normalize: bool = True, ) -> torch.FloatTensor: """ Get ray directions for all pixels in camera coordinate. Reference: ht...
Get ray directions for all pixels in camera coordinate. Reference: https://www.scratchapixel.com/lessons/3d-basic-rendering/ ray-tracing-generating-camera-rays/standard-coordinate-systems Inputs: H, W, focal, principal, use_pixel_centers: image height, width, focal length, principal...
get_ray_directions
python
VAST-AI-Research/TripoSR
tsr/utils.py
https://github.com/VAST-AI-Research/TripoSR/blob/master/tsr/utils.py
MIT
def forward( self, hidden_states: torch.FloatTensor, encoder_hidden_states: Optional[torch.FloatTensor] = None, attention_mask: Optional[torch.FloatTensor] = None, **cross_attention_kwargs, ) -> torch.Tensor: r""" The forward method of the `Attention` class. ...
The forward method of the `Attention` class. Args: hidden_states (`torch.Tensor`): The hidden states of the query. encoder_hidden_states (`torch.Tensor`, *optional*): The hidden states of the encoder. attention_mask (`torch.Tensor`, *...
forward
python
VAST-AI-Research/TripoSR
tsr/models/transformer/attention.py
https://github.com/VAST-AI-Research/TripoSR/blob/master/tsr/models/transformer/attention.py
MIT
def batch_to_head_dim(self, tensor: torch.Tensor) -> torch.Tensor: r""" Reshape the tensor from `[batch_size, seq_len, dim]` to `[batch_size // heads, seq_len, dim * heads]`. `heads` is the number of heads initialized while constructing the `Attention` class. Args: tensor (`...
Reshape the tensor from `[batch_size, seq_len, dim]` to `[batch_size // heads, seq_len, dim * heads]`. `heads` is the number of heads initialized while constructing the `Attention` class. Args: tensor (`torch.Tensor`): The tensor to reshape. Returns: `torch.Ten...
batch_to_head_dim
python
VAST-AI-Research/TripoSR
tsr/models/transformer/attention.py
https://github.com/VAST-AI-Research/TripoSR/blob/master/tsr/models/transformer/attention.py
MIT
def head_to_batch_dim(self, tensor: torch.Tensor, out_dim: int = 3) -> torch.Tensor: r""" Reshape the tensor from `[batch_size, seq_len, dim]` to `[batch_size, seq_len, heads, dim // heads]` `heads` is the number of heads initialized while constructing the `Attention` class. Args: ...
Reshape the tensor from `[batch_size, seq_len, dim]` to `[batch_size, seq_len, heads, dim // heads]` `heads` is the number of heads initialized while constructing the `Attention` class. Args: tensor (`torch.Tensor`): The tensor to reshape. out_dim (`int`, *optional*, de...
head_to_batch_dim
python
VAST-AI-Research/TripoSR
tsr/models/transformer/attention.py
https://github.com/VAST-AI-Research/TripoSR/blob/master/tsr/models/transformer/attention.py
MIT
def get_attention_scores( self, query: torch.Tensor, key: torch.Tensor, attention_mask: torch.Tensor = None, ) -> torch.Tensor: r""" Compute the attention scores. Args: query (`torch.Tensor`): The query tensor. key (`torch.Tensor`): Th...
Compute the attention scores. Args: query (`torch.Tensor`): The query tensor. key (`torch.Tensor`): The key tensor. attention_mask (`torch.Tensor`, *optional*): The attention mask to use. If `None`, no mask is applied. Returns: `torch.Tensor`: T...
get_attention_scores
python
VAST-AI-Research/TripoSR
tsr/models/transformer/attention.py
https://github.com/VAST-AI-Research/TripoSR/blob/master/tsr/models/transformer/attention.py
MIT
def prepare_attention_mask( self, attention_mask: torch.Tensor, target_length: int, batch_size: int, out_dim: int = 3, ) -> torch.Tensor: r""" Prepare the attention mask for the attention computation. Args: attention_mask (`torch.Tensor`):...
Prepare the attention mask for the attention computation. Args: attention_mask (`torch.Tensor`): The attention mask to prepare. target_length (`int`): The target length of the attention mask. This is the length of the attention mask after padding...
prepare_attention_mask
python
VAST-AI-Research/TripoSR
tsr/models/transformer/attention.py
https://github.com/VAST-AI-Research/TripoSR/blob/master/tsr/models/transformer/attention.py
MIT
def norm_encoder_hidden_states( self, encoder_hidden_states: torch.Tensor ) -> torch.Tensor: r""" Normalize the encoder hidden states. Requires `self.norm_cross` to be specified when constructing the `Attention` class. Args: encoder_hidden_states (`torch.Tensor`)...
Normalize the encoder hidden states. Requires `self.norm_cross` to be specified when constructing the `Attention` class. Args: encoder_hidden_states (`torch.Tensor`): Hidden states of the encoder. Returns: `torch.Tensor`: The normalized encoder hidden states. ...
norm_encoder_hidden_states
python
VAST-AI-Research/TripoSR
tsr/models/transformer/attention.py
https://github.com/VAST-AI-Research/TripoSR/blob/master/tsr/models/transformer/attention.py
MIT
def forward( self, hidden_states: torch.Tensor, encoder_hidden_states: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, encoder_attention_mask: Optional[torch.Tensor] = None, ): """ The [`Transformer1DModel`] forward method. ...
The [`Transformer1DModel`] forward method. Args: hidden_states (`torch.LongTensor` of shape `(batch size, num latent pixels)` if discrete, `torch.FloatTensor` of shape `(batch size, channel, height, width)` if continuous): Input `hidden_states`. encoder_hidden_s...
forward
python
VAST-AI-Research/TripoSR
tsr/models/transformer/transformer_1d.py
https://github.com/VAST-AI-Research/TripoSR/blob/master/tsr/models/transformer/transformer_1d.py
MIT
def log_metric( accelerator, metrics: Dict, train_time: float, step: int, epoch: int, learning_rate: float = None, prefix: str = "train", ): """Helper function to log all training/evaluation metrics with the correct prefixes and styling.""" log_metrics = {} for k, v in metrics.it...
Helper function to log all training/evaluation metrics with the correct prefixes and styling.
log_metric
python
huggingface/distil-whisper
training/run_distillation.py
https://github.com/huggingface/distil-whisper/blob/master/training/run_distillation.py
MIT
def log_pred( accelerator, pred_str: List[str], label_str: List[str], norm_pred_str: List[str], norm_label_str: List[str], step: int, prefix: str = "eval", num_lines: int = 200000, ): """Helper function to log target/predicted transcriptions to weights and biases (wandb).""" if a...
Helper function to log target/predicted transcriptions to weights and biases (wandb).
log_pred
python
huggingface/distil-whisper
training/run_distillation.py
https://github.com/huggingface/distil-whisper/blob/master/training/run_distillation.py
MIT
def convert_dataset_str_to_list( dataset_names, dataset_config_names, splits=None, text_column_names=None, dataset_samples=None, default_split="train", ) -> List[Dict]: """ Given three lists of dataset names, configs and splits, this function groups the corresponding names/configs/sp...
Given three lists of dataset names, configs and splits, this function groups the corresponding names/configs/splits. Each dataset is assigned a unique dictionary with these metadata values, and the function returns a list of dictionaries, one for each dataset.
convert_dataset_str_to_list
python
huggingface/distil-whisper
training/run_distillation.py
https://github.com/huggingface/distil-whisper/blob/master/training/run_distillation.py
MIT
def sorted_checkpoints(output_dir=None, checkpoint_prefix="checkpoint") -> List[str]: """Helper function to sort saved checkpoints from oldest to newest.""" ordering_and_checkpoint_path = [] glob_checkpoints = [str(x) for x in Path(output_dir).glob(f"{checkpoint_prefix}-*") if os.path.isdir(x)] glob_ch...
Helper function to sort saved checkpoints from oldest to newest.
sorted_checkpoints
python
huggingface/distil-whisper
training/run_distillation.py
https://github.com/huggingface/distil-whisper/blob/master/training/run_distillation.py
MIT
def sorted_best_checkpoints(output_dir=None, checkpoint_prefix="checkpoint"): """Helper function to sort saved best checkpoints.""" ordering_and_checkpoint_path = [] glob_checkpoints = [str(x) for x in Path(output_dir).glob(f"{checkpoint_prefix}-*") if os.path.isdir(x)] for path in glob_checkpoints: ...
Helper function to sort saved best checkpoints.
sorted_best_checkpoints
python
huggingface/distil-whisper
training/run_distillation.py
https://github.com/huggingface/distil-whisper/blob/master/training/run_distillation.py
MIT
def rotate_checkpoints(save_total_limit=None, output_dir=None, checkpoint_prefix="checkpoint", sorting_fn=sorted_checkpoints) -> None: """Helper function to delete old checkpoints.""" if save_total_limit is None or save_total_limit <= 0: return # Check if we should delete older checkpoint(s) che...
Helper function to delete old checkpoints.
rotate_checkpoints
python
huggingface/distil-whisper
training/run_distillation.py
https://github.com/huggingface/distil-whisper/blob/master/training/run_distillation.py
MIT
def get_parameter_names(model, forbidden_layer_types, forbidden_module=None): """ Returns the names of the model parameters that are not inside a forbidden layer or forbidden module. Can be used to get a subset of parameter names for decay masks, or to exclude parameters from an optimiser (e.g. if the m...
Returns the names of the model parameters that are not inside a forbidden layer or forbidden module. Can be used to get a subset of parameter names for decay masks, or to exclude parameters from an optimiser (e.g. if the module is frozen).
get_parameter_names
python
huggingface/distil-whisper
training/run_distillation.py
https://github.com/huggingface/distil-whisper/blob/master/training/run_distillation.py
MIT
def prepare_train_dataset(batch): """ Pre-process the raw dataset in a three stage process: 1. Convert the audio arrays to log-mel spectrogram inputs 2. Possibly filter the timestamp tokens from the token ids (depending on the timestamp probability) 3. Possibly add pr...
Pre-process the raw dataset in a three stage process: 1. Convert the audio arrays to log-mel spectrogram inputs 2. Possibly filter the timestamp tokens from the token ids (depending on the timestamp probability) 3. Possibly add prompt tokens if conditioning on previous text ...
prepare_train_dataset
python
huggingface/distil-whisper
training/run_distillation.py
https://github.com/huggingface/distil-whisper/blob/master/training/run_distillation.py
MIT
def shift_tokens_right(label_ids: np.array, decoder_start_token_id: int) -> np.ndarray: """ Shift label ids one token to the right. """ shifted_label_ids = np.zeros_like(label_ids) shifted_label_ids[:, 1:] = label_ids[:, :-1] shifted_label_ids[:, 0] = decoder_start_token_id return shifted_l...
Shift label ids one token to the right.
shift_tokens_right
python
huggingface/distil-whisper
training/run_pseudo_labelling.py
https://github.com/huggingface/distil-whisper/blob/master/training/run_pseudo_labelling.py
MIT
def log_metric( accelerator, metrics: Dict, train_time: float, prefix: str = "eval", ): """Helper function to log all evaluation metrics with the correct prefixes and styling.""" log_metrics = {} for k, v in metrics.items(): log_metrics[f"{prefix}/{k}"] = v log_metrics[f"{prefix}...
Helper function to log all evaluation metrics with the correct prefixes and styling.
log_metric
python
huggingface/distil-whisper
training/run_pseudo_labelling.py
https://github.com/huggingface/distil-whisper/blob/master/training/run_pseudo_labelling.py
MIT
def log_pred( accelerator, pred_str: List[str], label_str: List[str], norm_pred_str: List[str], norm_label_str: List[str], prefix: str = "eval", num_lines: int = 200000, ): """Helper function to log target/predicted transcriptions to weights and biases (wandb).""" if accelerator.is_m...
Helper function to log target/predicted transcriptions to weights and biases (wandb).
log_pred
python
huggingface/distil-whisper
training/run_pseudo_labelling.py
https://github.com/huggingface/distil-whisper/blob/master/training/run_pseudo_labelling.py
MIT
def create_learning_rate_fn( num_train_steps: int, lr_scheduler_type: str, num_warmup_steps: int, learning_rate: float ) -> Callable[[int], jnp.array]: """Returns a linear warmup, linear_decay learning rate function.""" lr_scheduler_types = ("linear", "constant_with_warmup") if lr_scheduler_type not in...
Returns a linear warmup, linear_decay learning rate function.
create_learning_rate_fn
python
huggingface/distil-whisper
training/flax/convert_train_state_to_hf.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/convert_train_state_to_hf.py
MIT
def apply_gradients(self, *, grads, **kwargs): """Updates `step`, `params`, `opt_state` and `**kwargs` in return value, clipping the gradients by the maximum grad norm. Note that internally this function calls `.tx.update()` followed by a call to `optax.apply_updates()` to update `param...
Updates `step`, `params`, `opt_state` and `**kwargs` in return value, clipping the gradients by the maximum grad norm. Note that internally this function calls `.tx.update()` followed by a call to `optax.apply_updates()` to update `params` and `opt_state`. Args: grads: Gradie...
apply_gradients
python
huggingface/distil-whisper
training/flax/convert_train_state_to_hf.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/convert_train_state_to_hf.py
MIT
def shift_tokens_right(label_ids: np.array, decoder_start_token_id: int) -> np.ndarray: """ Shift label ids one token to the right. """ shifted_label_ids = np.zeros_like(label_ids) shifted_label_ids[:, 1:] = label_ids[:, :-1] shifted_label_ids[:, 0] = decoder_start_token_id return shifted_l...
Shift label ids one token to the right.
shift_tokens_right
python
huggingface/distil-whisper
training/flax/run_distillation.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/run_distillation.py
MIT
def get_data_loader( seed: int, dataset: IterableDataset, batch_size: int, data_collator: FlaxDataCollatorSpeechSeq2SeqWithPadding, shuffle: bool = True, drop_last: bool = True, dataloader_num_workers: int = 0, skip_batches: int = 0, pin_memory: bool = True, prefetch_size: int = ...
Returns batches of size `batch_size` from `dataset`. If `drop_last` is set to `False`, the final batch may be incomplete, and range in size from 1 to `batch_size`. Shuffle batches if `shuffle` is `True`. Args: seed (int): Numpy seed for generating pseudo random numbers. Used if shuffling the datas...
get_data_loader
python
huggingface/distil-whisper
training/flax/run_distillation.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/run_distillation.py
MIT
def apply_gradients(self, *, grads, to_dtype: to_fp32, **kwargs): """Updates `step`, `params`, `opt_state` and `**kwargs` in return value, clipping the gradients by the maximum grad norm. Note that internally this function calls `.tx.update()` followed by a call to `optax.apply_updates(...
Updates `step`, `params`, `opt_state` and `**kwargs` in return value, clipping the gradients by the maximum grad norm. Note that internally this function calls `.tx.update()` followed by a call to `optax.apply_updates()` to update `params` and `opt_state`. Args: grads: Gradie...
apply_gradients
python
huggingface/distil-whisper
training/flax/run_distillation.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/run_distillation.py
MIT
def create(cls, *, apply_fn, params, tx, to_dtype: to_fp32, **kwargs): """Creates a new instance with `step=0` and initialized `opt_state`.""" # downcast optimizer state to bf16 if mixed-precision training opt_state = tx.init(to_dtype(params)) return cls( step=0, ...
Creates a new instance with `step=0` and initialized `opt_state`.
create
python
huggingface/distil-whisper
training/flax/run_distillation.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/run_distillation.py
MIT
def create_learning_rate_fn( num_train_steps: int, lr_scheduler_type: str, num_warmup_steps: int, learning_rate: float ) -> Callable[[int], jnp.array]: """Returns a linear warmup, linear_decay learning rate function.""" lr_scheduler_types = ("linear", "constant_with_warmup") if lr_scheduler_type not in...
Returns a linear warmup, linear_decay learning rate function.
create_learning_rate_fn
python
huggingface/distil-whisper
training/flax/run_distillation.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/run_distillation.py
MIT
def get_layers_to_supervise(student_layers: int, teacher_layers: int) -> dict: """Helper function to map the student layer i to the teacher layer j whose output we'd like them to emulate. Used for MSE loss terms in distillation (hidden-states and activations). Student layers are paired with teacher layers i...
Helper function to map the student layer i to the teacher layer j whose output we'd like them to emulate. Used for MSE loss terms in distillation (hidden-states and activations). Student layers are paired with teacher layers in equal increments, e.g. for a 12-layer model distilled to a 3-layer model, student la...
get_layers_to_supervise
python
huggingface/distil-whisper
training/flax/run_distillation.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/run_distillation.py
MIT
def _np_extract_fbank_features(self, waveform: np.array) -> np.ndarray: """ Compute the log-mel spectrogram of the provided audio using torch filters. Using the torch implementation computes stft filter banks approx 5x faster than its numpy counterpart, which is the native implementation ...
Compute the log-mel spectrogram of the provided audio using torch filters. Using the torch implementation computes stft filter banks approx 5x faster than its numpy counterpart, which is the native implementation in transformers, and matches to within 1e-5 abs tolerance.
_np_extract_fbank_features
python
huggingface/distil-whisper
training/flax/run_distillation.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/run_distillation.py
MIT
def shift_tokens_right(label_ids: np.array, decoder_start_token_id: int) -> np.ndarray: """ Shift label ids one token to the right. """ shifted_label_ids = np.zeros_like(label_ids) shifted_label_ids[:, 1:] = label_ids[:, :-1] shifted_label_ids[:, 0] = decoder_start_token_id return shifted_l...
Shift label ids one token to the right.
shift_tokens_right
python
huggingface/distil-whisper
training/flax/run_eval.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/run_eval.py
MIT
def get_data_loader( dataset: Dataset, batch_size: int, data_collator: FlaxDataCollatorSpeechSeq2SeqWithPadding, dataloader_num_workers: int = 0, pin_memory: bool = True, ) -> DataLoader: """ Returns batches of size `batch_size` from `dataset`. If `drop_last` is set to `False`, the final bat...
Returns batches of size `batch_size` from `dataset`. If `drop_last` is set to `False`, the final batch may be incomplete, and range in size from 1 to `batch_size`. Shuffle batches if `shuffle` is `True`. Args: dataset (Dataset): dataset from which to load the data. batch_size (int): how ma...
get_data_loader
python
huggingface/distil-whisper
training/flax/run_eval.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/run_eval.py
MIT
def _np_extract_fbank_features(self, waveform: np.array) -> np.ndarray: """ Compute the log-mel spectrogram of the provided audio using torch filters. Using the torch implementation computes stft filter banks approx 5x faster than its numpy counterpart, which is the native implementation ...
Compute the log-mel spectrogram of the provided audio using torch filters. Using the torch implementation computes stft filter banks approx 5x faster than its numpy counterpart, which is the native implementation in transformers, and matches to within 1e-5 abs tolerance.
_np_extract_fbank_features
python
huggingface/distil-whisper
training/flax/run_eval.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/run_eval.py
MIT
def loss_fn(logits, labels, label_smoothing_factor=0.0): """ The label smoothing implementation is adapted from Flax's official example: https://github.com/google/flax/blob/87a211135c6a377c8f29048a1cac3840e38b9da4/examples/wmt/train.py#L104 """ vocab_size = logits.shape[-1] ...
The label smoothing implementation is adapted from Flax's official example: https://github.com/google/flax/blob/87a211135c6a377c8f29048a1cac3840e38b9da4/examples/wmt/train.py#L104
loss_fn
python
huggingface/distil-whisper
training/flax/run_eval.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/run_eval.py
MIT
def shift_tokens_right(label_ids: np.array, decoder_start_token_id: int) -> np.ndarray: """ Shift label ids one token to the right. """ shifted_label_ids = np.zeros_like(label_ids) shifted_label_ids[:, 1:] = label_ids[:, :-1] shifted_label_ids[:, 0] = decoder_start_token_id return shifted_l...
Shift label ids one token to the right.
shift_tokens_right
python
huggingface/distil-whisper
training/flax/run_finetuning.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/run_finetuning.py
MIT
def get_data_loader( rng: jax.random.PRNGKey, dataset: Dataset, batch_size: int, data_collator: FlaxDataCollatorSpeechSeq2SeqWithPadding, shuffle: bool = True, drop_last: bool = True, dataloader_num_workers: int = 0, pin_memory: bool = True, ) -> DataLoader: """ Returns batches o...
Returns batches of size `batch_size` from `dataset`. If `drop_last` is set to `False`, the final batch may be incomplete, and range in size from 1 to `batch_size`. Shuffle batches if `shuffle` is `True`. Args: rng (List(int)): JAX rng for generating pseudo random numbers. Used if shuffling the dat...
get_data_loader
python
huggingface/distil-whisper
training/flax/run_finetuning.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/run_finetuning.py
MIT
def create_learning_rate_fn( num_train_steps: int, num_warmup_steps: int, learning_rate: float ) -> Callable[[int], jnp.array]: """Returns a linear warmup, linear_decay learning rate function.""" warmup_fn = optax.linear_schedule(init_value=0.0, end_value=learning_rate, transition_steps=num_warmup_steps) ...
Returns a linear warmup, linear_decay learning rate function.
create_learning_rate_fn
python
huggingface/distil-whisper
training/flax/run_finetuning.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/run_finetuning.py
MIT
def loss_fn(logits, labels, label_smoothing_factor=0.0): """ The label smoothing implementation is adapted from Flax's official example: https://github.com/google/flax/blob/87a211135c6a377c8f29048a1cac3840e38b9da4/examples/wmt/train.py#L104 """ vocab_size = logits.shape[-1] ...
The label smoothing implementation is adapted from Flax's official example: https://github.com/google/flax/blob/87a211135c6a377c8f29048a1cac3840e38b9da4/examples/wmt/train.py#L104
loss_fn
python
huggingface/distil-whisper
training/flax/run_finetuning.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/run_finetuning.py
MIT
def shift_tokens_right(label_ids: np.array, decoder_start_token_id: int) -> np.ndarray: """ Shift label ids one token to the right. """ shifted_label_ids = np.zeros_like(label_ids) shifted_label_ids[:, 1:] = label_ids[:, :-1] shifted_label_ids[:, 0] = decoder_start_token_id return shifted_l...
Shift label ids one token to the right.
shift_tokens_right
python
huggingface/distil-whisper
training/flax/run_pseudo_labelling_pt.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/run_pseudo_labelling_pt.py
MIT
def log_metric( accelerator, metrics: Dict, train_time: float, prefix: str = "eval", ): """Helper function to log all evaluation metrics with the correct prefixes and styling.""" log_metrics = {} for k, v in metrics.items(): log_metrics[f"{prefix}/{k}"] = v log_metrics[f"{prefix}...
Helper function to log all evaluation metrics with the correct prefixes and styling.
log_metric
python
huggingface/distil-whisper
training/flax/run_pseudo_labelling_pt.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/run_pseudo_labelling_pt.py
MIT
def log_pred( accelerator, pred_str: List[str], label_str: List[str], norm_pred_str: List[str], norm_label_str: List[str], prefix: str = "eval", num_lines: int = 200000, ): """Helper function to log target/predicted transcriptions to weights and biases (wandb).""" if accelerator.is_m...
Helper function to log target/predicted transcriptions to weights and biases (wandb).
log_pred
python
huggingface/distil-whisper
training/flax/run_pseudo_labelling_pt.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/run_pseudo_labelling_pt.py
MIT
def nd_dense_init(scale, mode, distribution): """Initializer with in_axis, out_axis set at call time.""" def init_fn(key, shape, dtype, in_axis, out_axis): fn = variance_scaling(scale, mode, distribution, in_axis, out_axis) return fn(key, shape, dtype) return init_fn
Initializer with in_axis, out_axis set at call time.
nd_dense_init
python
huggingface/distil-whisper
training/flax/distil_whisper/layers.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/layers.py
MIT
def __call__( self, inputs_q: Array, inputs_kv: Array, mask: Optional[Array] = None, bias: Optional[Array] = None, *, decode: bool = False, deterministic: bool = False, ) -> Array: """Applies multi-head dot product attention on the input data. ...
Applies multi-head dot product attention on the input data. Projects the inputs into multi-headed query, key, and value vectors, applies dot-product attention and project the results to an output vector. There are two modes: decoding and non-decoding (e.g., training). The mode is deter...
__call__
python
huggingface/distil-whisper
training/flax/distil_whisper/layers.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/layers.py
MIT
def __call__(self, inputs: Array) -> Array: """Applies a linear transformation to the inputs along multiple dimensions. Args: inputs: The nd-array to be transformed. Returns: The transformed input. """ features = _canonicalize_tuple(self.features) ax...
Applies a linear transformation to the inputs along multiple dimensions. Args: inputs: The nd-array to be transformed. Returns: The transformed input.
__call__
python
huggingface/distil-whisper
training/flax/distil_whisper/layers.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/layers.py
MIT
def _convert_to_activation_function(fn_or_string: Union[str, Callable]) -> Callable: """Convert a string to an activation function.""" if fn_or_string == "linear": return lambda x: x elif isinstance(fn_or_string, str): return getattr(nn, fn_or_string) elif callable(fn_or_string): ...
Convert a string to an activation function.
_convert_to_activation_function
python
huggingface/distil-whisper
training/flax/distil_whisper/layers.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/layers.py
MIT
def __call__(self, inputs: Array) -> Array: """Embeds the inputs along the last dimension. Args: inputs: input data, all dimensions are considered batch dimensions. Returns: Output which is embedded input data. The output shape follows the input, with an addition...
Embeds the inputs along the last dimension. Args: inputs: input data, all dimensions are considered batch dimensions. Returns: Output which is embedded input data. The output shape follows the input, with an additional `features` dimension appended.
__call__
python
huggingface/distil-whisper
training/flax/distil_whisper/layers.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/layers.py
MIT
def attend(self, query: Array) -> Array: """Attend over the embedding using a query array. Args: query: array with last dimension equal the feature depth `features` of the embedding. Returns: An array with final dim `num_embeddings` corresponding to the batched ...
Attend over the embedding using a query array. Args: query: array with last dimension equal the feature depth `features` of the embedding. Returns: An array with final dim `num_embeddings` corresponding to the batched inner-product of the array of query vector...
attend
python
huggingface/distil-whisper
training/flax/distil_whisper/layers.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/layers.py
MIT
def _relative_position_bucket(relative_position, bidirectional=True, num_buckets=32, max_distance=128): """Translate relative position to a bucket number for relative attention. The relative position is defined as memory_position - query_position, i.e. the distance in tokens from the attending ...
Translate relative position to a bucket number for relative attention. The relative position is defined as memory_position - query_position, i.e. the distance in tokens from the attending position to the attended-to position. If bidirectional=False, then positive relative positions are ...
_relative_position_bucket
python
huggingface/distil-whisper
training/flax/distil_whisper/layers.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/layers.py
MIT
def __call__(self, qlen, klen, bidirectional=True): """Produce relative position embedding attention biases. Args: qlen: attention query length. klen: attention key length. bidirectional: whether to allow positive memory-query relative position embeddings. ...
Produce relative position embedding attention biases. Args: qlen: attention query length. klen: attention key length. bidirectional: whether to allow positive memory-query relative position embeddings. Returns: output: `(1, len, q_len, k_len)` attent...
__call__
python
huggingface/distil-whisper
training/flax/distil_whisper/layers.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/layers.py
MIT
def __call__(self, x): """Applies layer normalization on the input. Args: x: the inputs Returns: Normalized inputs (the same shape as inputs). """ x = jnp.asarray(x, jnp.float32) features = x.shape[-1] mean = jnp.mean(x, axis=-1, keepdims=True)...
Applies layer normalization on the input. Args: x: the inputs Returns: Normalized inputs (the same shape as inputs).
__call__
python
huggingface/distil-whisper
training/flax/distil_whisper/layers.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/layers.py
MIT
def make_attention_mask( query_input: Array, key_input: Array, pairwise_fn: Callable = jnp.multiply, extra_batch_dims: int = 0, dtype: DType = jnp.float32, ) -> Array: """Mask-making helper for attention weights. In case of 1d inputs (i.e., `[batch, len_q]`, `[batch, len_kv]`, the atten...
Mask-making helper for attention weights. In case of 1d inputs (i.e., `[batch, len_q]`, `[batch, len_kv]`, the attention weights will be `[batch, heads, len_q, len_kv]` and this function will produce `[batch, 1, len_q, len_kv]`. Args: query_input: a batched, flat input of query_length size ...
make_attention_mask
python
huggingface/distil-whisper
training/flax/distil_whisper/layers.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/layers.py
MIT
def make_causal_mask(x: Array, extra_batch_dims: int = 0, dtype: DType = jnp.float32) -> Array: """Make a causal mask for self-attention. In case of 1d inputs (i.e., `[batch, len]`, the self-attention weights will be `[batch, heads, len, len]` and this function will produce a causal mask of shape `[bat...
Make a causal mask for self-attention. In case of 1d inputs (i.e., `[batch, len]`, the self-attention weights will be `[batch, heads, len, len]` and this function will produce a causal mask of shape `[batch, 1, len, len]`. Note that a causal mask does not depend on the values of x; it only depends on ...
make_causal_mask
python
huggingface/distil-whisper
training/flax/distil_whisper/layers.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/layers.py
MIT
def combine_masks(*masks: Optional[Array], dtype: DType = jnp.float32): """Combine attention masks. Args: *masks: set of attention mask arguments to combine, some can be None. dtype: final mask dtype Returns: Combined mask, reduced by logical and, returns None if no masks given. """ ...
Combine attention masks. Args: *masks: set of attention mask arguments to combine, some can be None. dtype: final mask dtype Returns: Combined mask, reduced by logical and, returns None if no masks given.
combine_masks
python
huggingface/distil-whisper
training/flax/distil_whisper/layers.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/layers.py
MIT
def combine_biases(*masks: Optional[Array]): """Combine attention biases. Args: *masks: set of attention bias arguments to combine, some can be None. Returns: Combined mask, reduced by summation, returns None if no masks given. """ masks = [m for m in masks if m is not None] if not...
Combine attention biases. Args: *masks: set of attention bias arguments to combine, some can be None. Returns: Combined mask, reduced by summation, returns None if no masks given.
combine_biases
python
huggingface/distil-whisper
training/flax/distil_whisper/layers.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/layers.py
MIT
def make_decoder_mask( decoder_target_tokens: Array, dtype: DType, decoder_causal_attention: Optional[Array] = None, decoder_segment_ids: Optional[Array] = None, ) -> Array: """Compute the self-attention mask for a decoder. Decoder mask is formed by combining a causal mask, a padding mask and a...
Compute the self-attention mask for a decoder. Decoder mask is formed by combining a causal mask, a padding mask and an optional packing mask. If decoder_causal_attention is passed, it makes the masking non-causal for positions that have value of 1. A prefix LM is applied to a dataset which has a noti...
make_decoder_mask
python
huggingface/distil-whisper
training/flax/distil_whisper/layers.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/layers.py
MIT
def canonicalize_padding(padding: PaddingLike, rank: int) -> LaxPadding: """ "Canonicalizes conv padding to a jax.lax supported format.""" if isinstance(padding, str): return padding if isinstance(padding, int): return [(padding, padding)] * rank if isinstance(padding, Sequence) and len(...
"Canonicalizes conv padding to a jax.lax supported format.
canonicalize_padding
python
huggingface/distil-whisper
training/flax/distil_whisper/layers.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/layers.py
MIT
def _conv_dimension_numbers(input_shape): """Computes the dimension numbers based on the input shape.""" ndim = len(input_shape) lhs_spec = (0, ndim - 1) + tuple(range(1, ndim - 1)) rhs_spec = (ndim - 1, ndim - 2) + tuple(range(0, ndim - 2)) out_spec = lhs_spec return lax.ConvDimensionNumbers(lh...
Computes the dimension numbers based on the input shape.
_conv_dimension_numbers
python
huggingface/distil-whisper
training/flax/distil_whisper/layers.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/layers.py
MIT
def __call__(self, inputs: Array) -> Array: """Applies a (potentially unshared) convolution to the inputs. Args: inputs: input data with dimensions (*batch_dims, spatial_dims..., features). This is the channels-last convention, i.e. NHWC for a 2d convolution and NDHWC ...
Applies a (potentially unshared) convolution to the inputs. Args: inputs: input data with dimensions (*batch_dims, spatial_dims..., features). This is the channels-last convention, i.e. NHWC for a 2d convolution and NDHWC for a 3D convolution. Note: this is different from ...
__call__
python
huggingface/distil-whisper
training/flax/distil_whisper/layers.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/layers.py
MIT
def convert_unroll_to_scan(self, params: Union[Dict, FrozenDict]): r""" Convert a `PyTree` of unrolled model parameters to a scanned block of model parameters. This method can be used to explicitly convert the model parameters to scanned format. This returns a new `params` tree and does not ...
Convert a `PyTree` of unrolled model parameters to a scanned block of model parameters. This method can be used to explicitly convert the model parameters to scanned format. This returns a new `params` tree and does not convert the `params` in place. To illustrate the workings of this ...
convert_unroll_to_scan
python
huggingface/distil-whisper
training/flax/distil_whisper/modeling_flax_whisper.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/modeling_flax_whisper.py
MIT
def convert_scan_to_unroll(self, params: Union[Dict, FrozenDict]): r""" Convert a `PyTree` of scanned model parameters to an unrolled stack of model parameters. This method can be used to explicitly convert the model parameters to unrolled format. This returns a new `params` tree and does ...
Convert a `PyTree` of scanned model parameters to an unrolled stack of model parameters. This method can be used to explicitly convert the model parameters to unrolled format. This returns a new `params` tree and does not convert the `params` in place. To illustrate the workings of thi...
convert_scan_to_unroll
python
huggingface/distil-whisper
training/flax/distil_whisper/modeling_flax_whisper.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/modeling_flax_whisper.py
MIT
def init_cache(self, batch_size, max_length, encoder_outputs): r""" Args: batch_size (`int`): batch_size used for fast auto-regressive decoding. Defines the batch size of the initialized cache. max_length (`int`): maximum possible length for auto-r...
Args: batch_size (`int`): batch_size used for fast auto-regressive decoding. Defines the batch size of the initialized cache. max_length (`int`): maximum possible length for auto-regressive decoding. Defines the sequence length of the initialized ...
init_cache
python
huggingface/distil-whisper
training/flax/distil_whisper/modeling_flax_whisper.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/modeling_flax_whisper.py
MIT
def encode( self, input_features: jnp.ndarray, attention_mask: Optional[jnp.ndarray] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, train: bool = False, params: dict = None...
Returns: Example: ```python >>> from transformers import WhisperProcessor, FlaxWhisperForConditionalGeneration >>> from datasets import load_dataset >>> processor = WhisperProcessor.from_pretrained("openai/whisper-tiny.en") >>> model = FlaxWhisperForConditiona...
encode
python
huggingface/distil-whisper
training/flax/distil_whisper/modeling_flax_whisper.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/modeling_flax_whisper.py
MIT
def decode( self, decoder_input_ids, encoder_outputs, encoder_attention_mask: Optional[jnp.ndarray] = None, decoder_attention_mask: Optional[jnp.ndarray] = None, decoder_position_ids: Optional[jnp.ndarray] = None, past_key_values: dict = None, output_atten...
Returns: Example: ```python >>> from transformers import WhisperProcessor, FlaxWhisperForConditionalGeneration >>> from datasets import load_dataset >>> processor = WhisperProcessor.from_pretrained("openai/whisper-tiny.en") >>> model = FlaxWhisperForConditiona...
decode
python
huggingface/distil-whisper
training/flax/distil_whisper/modeling_flax_whisper.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/modeling_flax_whisper.py
MIT
def decode( self, decoder_input_ids, encoder_outputs, encoder_attention_mask: Optional[jnp.ndarray] = None, decoder_attention_mask: Optional[jnp.ndarray] = None, decoder_position_ids: Optional[jnp.ndarray] = None, past_key_values: dict = None, output_atten...
Returns: Example: ```python >>> from transformers import WhisperProcessor, FlaxWhisperForConditionalGeneration >>> from datasets import load_dataset >>> processor = WhisperProcessor.from_pretrained("openai/whisper-tiny.en") >>> model = FlaxWhisperForConditiona...
decode
python
huggingface/distil-whisper
training/flax/distil_whisper/modeling_flax_whisper.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/modeling_flax_whisper.py
MIT
def pjit_with_cpu_fallback( fun: Callable, # pylint: disable=g-bare-generic in_axis_resources, out_axis_resources, static_argnums: Union[int, Sequence[int]] = (), donate_argnums: Union[int, Sequence[int]] = (), backend: Optional[str] = None, ): """Wrapper for pjit that calls normal jit on c...
Wrapper for pjit that calls normal jit on cpu.
pjit_with_cpu_fallback
python
huggingface/distil-whisper
training/flax/distil_whisper/partitioner.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/partitioner.py
MIT
def with_sharding_constraint(x, axis_resources): """Wrapper for pjit with_sharding_constraint, no-op on cpu or outside pjit.""" if jax.devices()[0].platform == "cpu" or not global_mesh_defined(): return x else: return jax.experimental.pjit.with_sharding_constraint(x, axis_resources)
Wrapper for pjit with_sharding_constraint, no-op on cpu or outside pjit.
with_sharding_constraint
python
huggingface/distil-whisper
training/flax/distil_whisper/partitioner.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/partitioner.py
MIT
def bounds_from_last_device(last_device: JaxDevice) -> HardwareMesh: """Get the bound from the given last device.""" # Must be passed the device at the highest-coordinate corner of the # relevant mesh, which is a requirement we know is satisfied by the last # device in jax.devices(). if hasattr(last...
Get the bound from the given last device.
bounds_from_last_device
python
huggingface/distil-whisper
training/flax/distil_whisper/partitioner.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/partitioner.py
MIT
def get_coords(device: JaxDevice) -> HardwareMesh: """Returns the coordinates of the given device.""" if hasattr(device, "coords"): return (*device.coords, device.core_on_chip) return (device.process_index, device.id % jax.local_device_count())
Returns the coordinates of the given device.
get_coords
python
huggingface/distil-whisper
training/flax/distil_whisper/partitioner.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/partitioner.py
MIT
def global_mesh_defined(): """Checks if global xmap/pjit mesh resource environment is defined.""" maps_env = jax.experimental.maps.thread_resources.env return maps_env.physical_mesh.devices.shape != () # pylint: disable=g-explicit-bool-comparison
Checks if global xmap/pjit mesh resource environment is defined.
global_mesh_defined
python
huggingface/distil-whisper
training/flax/distil_whisper/partitioner.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/partitioner.py
MIT
def get_mesh( model_parallel_submesh: HardwareMesh, input_devices: Sequence[JaxDevice] = (), input_local_devices: Sequence[JaxDevice] = (), tile_by_host_if_needed: bool = True, backend: Optional[str] = None, ) -> Mesh: """Construct an xmap/pjit Mesh for the given model-parallel submesh. The...
Construct an xmap/pjit Mesh for the given model-parallel submesh. The resulting mesh has two resource axes: 'model', with the provided submesh shape, and 'data', which covers the rest of the mesh. Args: model_parallel_submesh: a HardwareMesh spec, namely (x,y,z,core) on TPU for a single mode...
get_mesh
python
huggingface/distil-whisper
training/flax/distil_whisper/partitioner.py
https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/partitioner.py
MIT