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, batch_size, max_time_step, library, candidate_wrapper=None, n_realizations=None):
"""
Parameters
----------
batch_size : int
Number of programs in batch.
max_time_step : int
Max number of tokens programs can contain.
library : li... |
Parameters
----------
batch_size : int
Number of programs in batch.
max_time_step : int
Max number of tokens programs can contain.
library : library.Library
Library of tokens that can appear in programs.
candidate_wrapper : callable or... | __init__ | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def lib (self, attr):
"""
Gives access to vectorized properties of tokens in library without having to use [0, :] (as batch_size = 1 in
vectorized properties of library).
Parameters
----------
attr : str
Attribute of library vectorized properties to access.
... |
Gives access to vectorized properties of tokens in library without having to use [0, :] (as batch_size = 1 in
vectorized properties of library).
Parameters
----------
attr : str
Attribute of library vectorized properties to access.
Returns
-------
... | lib | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def append (self, new_tokens_idx, forbid_inconsistent_units = False):
"""
Appends new tokens to batch.
New tokens appended to already complete programs (ie. out of tree tokens) are ignored.
Note that units requirements and update is not done in append (as it is computationally costly and... |
Appends new tokens to batch.
New tokens appended to already complete programs (ie. out of tree tokens) are ignored.
Note that units requirements and update is not done in append (as it is computationally costly and unnecessary
if units are not used). Use the assign_required_units method... | append | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def set_programs (self, tokens_idx, forbid_inconsistent_units = False):
"""
Sets all programs in batch by appending tokens_idx step by step.
Parameters
----------
tokens_idx : numpy.array of shape (batch_size, int <= max_time_step) of int
Index of tokens making up pro... |
Sets all programs in batch by appending tokens_idx step by step.
Parameters
----------
tokens_idx : numpy.array of shape (batch_size, int <= max_time_step) of int
Index of tokens making up programs in the library.
If programs have different shapes, tokens_idx mus... | set_programs | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def assign_required_units (self, step = None, ignore_unphysical = True,):
"""
Runs required units assignment routine (assign_required_units) on programs at step.
Parameters
----------
step : int or None
Required units assignment routine is run on tokens at step. By de... |
Runs required units assignment routine (assign_required_units) on programs at step.
Parameters
----------
step : int or None
Required units assignment routine is run on tokens at step. By default, step = current step.
ignore_unphysical : bool
Should routi... | assign_required_units | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def mask_to_coords (self, mask):
"""
Helper function returning coordinates where mask is True.
Parameters
----------
mask : numpy.array of shape (batch_size, max_time_step) of bool
Mask.
Returns
-------
mask_sum, coordinates : int, numpy.array ... |
Helper function returning coordinates where mask is True.
Parameters
----------
mask : numpy.array of shape (batch_size, max_time_step) of bool
Mask.
Returns
-------
mask_sum, coordinates : int, numpy.array of shape (2, mask_sum) of int
Nu... | mask_to_coords | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def coords_to_mask (self, coords):
"""
Helper function returning mask of batch shape (batch_size, max_time_step,) containing True at coords.
Parameters
----------
coords : numpy.array of shape (2, ?) of int
Coordinates where mask should be True
Returns
... |
Helper function returning mask of batch shape (batch_size, max_time_step,) containing True at coords.
Parameters
----------
coords : numpy.array of shape (2, ?) of int
Coordinates where mask should be True
Returns
-------
mask : numpy.array of shape (... | coords_to_mask | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def coords_of_step (self, step):
"""
Helper method returning the tuple of coordinates corresponding to a step.
Parameters
----------
step : int
Step.
Returns
-------
coords : numpy.array of shape (2, batch_size,) of int
Coordinates,... |
Helper method returning the tuple of coordinates corresponding to a step.
Parameters
----------
step : int
Step.
Returns
-------
coords : numpy.array of shape (2, batch_size,) of int
Coordinates, 0th array in batch dim and 1th array in tim... | coords_of_step | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def get_parent (self, coords):
"""
Get parent's coordinates of tokens at coords.
Parameters
----------
coords : numpy.array of shape (2, ?) of int
Coords of tokens, 0th array in batch dim and 1th array in time dim.
Returns
-------
parent_coords... |
Get parent's coordinates of tokens at coords.
Parameters
----------
coords : numpy.array of shape (2, ?) of int
Coords of tokens, 0th array in batch dim and 1th array in time dim.
Returns
-------
parent_coords : numpy.array of shape (2, ?) of int
... | get_parent | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def get_siblings (self, coords):
"""
Get siblings' coordinates of tokens at coords.
Parameters
----------
coords : numpy.array of shape (2, ?) of int
Coords of tokens, 0th array in batch dim and 1th array in time dim.
Returns
-------
siblings_c... |
Get siblings' coordinates of tokens at coords.
Parameters
----------
coords : numpy.array of shape (2, ?) of int
Coords of tokens, 0th array in batch dim and 1th array in time dim.
Returns
-------
siblings_coords : numpy.array of shape (1 + Tok.MAX_NB... | get_siblings | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def get_children (self, coords):
"""
Get children's coordinates of tokens at coords.
Parameters
----------
coords : numpy.array of shape (2, ?) of int
Coords of tokens, 0th array in batch dim and 1th array in time dim.
Returns
-------
children_... |
Get children's coordinates of tokens at coords.
Parameters
----------
coords : numpy.array of shape (2, ?) of int
Coords of tokens, 0th array in batch dim and 1th array in time dim.
Returns
-------
children_coords : numpy.array of shape (1 + Tok.MAX_N... | get_children | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def get_ancestors (self, coords):
"""
Get ancestors' coordinates of tokens at coords.
Parameters
----------
coords : numpy.array of shape (2, ?) of int
Coords of tokens, 0th array in batch dim and 1th array in time dim.
Returns
-------
ancestor... |
Get ancestors' coordinates of tokens at coords.
Parameters
----------
coords : numpy.array of shape (2, ?) of int
Coords of tokens, 0th array in batch dim and 1th array in time dim.
Returns
-------
ancestors_coords : numpy.array of shape (1 + max_time... | get_ancestors | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def get_parent_idx(self, coords, no_parent_idx_filler=None):
"""
Get parents idx of tokens at coords.
Parameters
----------
coords : numpy.array of shape (2, ?,) of int
Coords of tokens, 0th array in batch dim and 1th array in time dim.
no_parent_idx_filler : ... |
Get parents idx of tokens at coords.
Parameters
----------
coords : numpy.array of shape (2, ?,) of int
Coords of tokens, 0th array in batch dim and 1th array in time dim.
no_parent_idx_filler : int
Fill value to return where tokens have no parent.
... | get_parent_idx | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def get_sibling_idx(self, coords, no_sibling_idx_filler=None):
"""
Get siblings idx of tokens at coords.
Parameters
----------
coords : numpy.array of shape (2, ?,) of int
Coords of tokens, 0th array in batch dim and 1th array in time dim.
no_sibling_idx_fille... |
Get siblings idx of tokens at coords.
Parameters
----------
coords : numpy.array of shape (2, ?,) of int
Coords of tokens, 0th array in batch dim and 1th array in time dim.
no_sibling_idx_filler : int
Fill value to return where tokens have no sibling.
... | get_sibling_idx | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def get_ancestors_idx(self, coords, no_ancestor_idx_filler=None):
"""
Get ancestors idx of tokens at step.
Parameters
----------
coords : numpy.array of shape (2, ?,) of int
Coords of tokens, 0th array in batch dim and 1th array in time dim.
no_ancestor_idx_fi... |
Get ancestors idx of tokens at step.
Parameters
----------
coords : numpy.array of shape (2, ?,) of int
Coords of tokens, 0th array in batch dim and 1th array in time dim.
no_ancestor_idx_filler : int
Fill value to return where tokens have no ancestors an... | get_ancestors_idx | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def get_parent_idx_of_step(self, step=None, no_parent_idx_filler=None):
"""
Get parents idx of tokens at step.
Parameters
----------
step : int
Step of token from which parent idx should be returned.
By default, step = current step
no_parent_idx_fi... |
Get parents idx of tokens at step.
Parameters
----------
step : int
Step of token from which parent idx should be returned.
By default, step = current step
no_parent_idx_filler : int
Fill value to return where tokens have no parent.
Re... | get_parent_idx_of_step | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def get_sibling_idx_of_step(self, step=None, no_sibling_idx_filler=None):
"""
Get siblings idx of tokens at step.
Parameters
----------
step : int
Step of token from which sibling idx should be returned.
By default, step = current step
no_sibling_i... |
Get siblings idx of tokens at step.
Parameters
----------
step : int
Step of token from which sibling idx should be returned.
By default, step = current step
no_sibling_idx_filler : int
Fill value to return where tokens have no sibling.
... | get_sibling_idx_of_step | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def get_ancestors_idx_of_step(self, step=None, no_ancestor_idx_filler=None):
"""
Get ancestors idx of tokens at step.
Parameters
----------
step : int
Step of token from which ancestors idx should be returned.
By default, step = current step
no_anc... |
Get ancestors idx of tokens at step.
Parameters
----------
step : int
Step of token from which ancestors idx should be returned.
By default, step = current step
no_ancestor_idx_filler : int
Fill value to return where tokens have no ancestors a... | get_ancestors_idx_of_step | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def count_tokens_idx (self, tokens_idx):
"""
Creates a library size vector containing count of token idx (along ?1 dim) in tokens_idx for each line of
tokens_idx. Eg: [ [2, 2, 1, 2, 5], [1, 1, 1, 0, 4] ] -> [0,1,3,0,0,1] [1,3,0,0,1,0] assuming n_library = 5.
Parameters
----------... |
Creates a library size vector containing count of token idx (along ?1 dim) in tokens_idx for each line of
tokens_idx. Eg: [ [2, 2, 1, 2, 5], [1, 1, 1, 0, 4] ] -> [0,1,3,0,0,1] [1,3,0,0,1,0] assuming n_library = 5.
Parameters
----------
tokens_idx : numpy.array of shape (?, ?1) o... | count_tokens_idx | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def get_property_of_relative(self, coords, relative, attr):
"""
Returns the attribute (eg. phy_units, arity etc.) of the [relative] of tokens at coords. Fills with default
value of attribute in VectTokens where tokens at coords do not have [relative].
Parameters
----------
... |
Returns the attribute (eg. phy_units, arity etc.) of the [relative] of tokens at coords. Fills with default
value of attribute in VectTokens where tokens at coords do not have [relative].
Parameters
----------
coords : numpy.array of shape (2, ?,) of int
Coords of to... | get_property_of_relative | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def set_parent(self, coords_dest, has_mask, pos_val):
"""
Sets parent properties of tokens of coordinates coords_dest with new values given in args.
Parameters
----------
coords_dest : numpy.array of shape (2, ?) of int
Coords where to set property, 0th array in batch... |
Sets parent properties of tokens of coordinates coords_dest with new values given in args.
Parameters
----------
coords_dest : numpy.array of shape (2, ?) of int
Coords where to set property, 0th array in batch dim and 1th array in time dim.
has_mask : numpy.array of... | set_parent | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def set_children(self, coords_dest, has_mask, pos_val, nb):
"""
Sets children properties of tokens of coordinates coords_dest with new values given in args.
Parameters
----------
coords_dest : numpy.array of shape (2, ?) of int
Coords where to set property, 0th array ... |
Sets children properties of tokens of coordinates coords_dest with new values given in args.
Parameters
----------
coords_dest : numpy.array of shape (2, ?) of int
Coords where to set property, 0th array in batch dim and 1th array in time dim.
has_mask : numpy.array ... | set_children | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def set_siblings(self, coords_dest, has_mask, pos_val, nb):
"""
Sets siblings properties of tokens of coordinates coords_dest with new values given in args.
Parameters
----------
coords_dest : numpy.array of shape (2, ?) of int
Coords where to set property, 0th array ... |
Sets siblings properties of tokens of coordinates coords_dest with new values given in args.
Parameters
----------
coords_dest : numpy.array of shape (2, ?) of int
Coords where to set property, 0th array in batch dim and 1th array in time dim.
has_mask : numpy.array ... | set_siblings | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def set_ancestors(self, coords_dest, has_mask, pos_val, nb):
"""
Sets ancestors properties of tokens of coordinates coords_dest with new values given in args.
Parameters
----------
coords_dest : numpy.array of shape (2, ?) of int
Coords where to set property, 0th arra... |
Sets ancestors properties of tokens of coordinates coords_dest with new values given in args.
Parameters
----------
coords_dest : numpy.array of shape (2, ?) of int
Coords where to set property, 0th array in batch dim and 1th array in time dim.
has_mask : numpy.array... | set_ancestors | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def register_ancestor(self, coords_dest, ):
"""
Registers tokens located at coords_dest in their own ancestor records (as a token counts as its own ancestor)
and updates the number of ancestors. Depths must be up-to-date for this function to perform correctly.
Parameters
--------... |
Registers tokens located at coords_dest in their own ancestor records (as a token counts as its own ancestor)
and updates the number of ancestors. Depths must be up-to-date for this function to perform correctly.
Parameters
----------
coords_dest : numpy.array of shape (2, ?) of... | register_ancestor | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def set_units (self, coords_dest, new_is_constraining_phy_units, new_phy_units):
"""
Sets units properties of tokens of coordinates coords_dest with new values given in args.
Parameters
----------
coords_dest : numpy.array of shape (2, ?) of int
Coords where to set ne... |
Sets units properties of tokens of coordinates coords_dest with new values given in args.
Parameters
----------
coords_dest : numpy.array of shape (2, ?) of int
Coords where to set new tokens, 0th array in batch dim and 1th array in time dim.
new_is_constraining_phy_... | set_units | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def set_static_units_from_idx (self, coords_dest, tokens_idx_src):
"""
Sets units properties of tokens at coords_dest from units of tokens tokens_idx_src as given in the library.
Parameters
----------
coords_dest : numpy.array of shape (2, ?) of int
Coords where to se... |
Sets units properties of tokens at coords_dest from units of tokens tokens_idx_src as given in the library.
Parameters
----------
coords_dest : numpy.array of shape (2, ?) of int
Coords where to set new tokens, 0th array in batch dim and 1th array in time dim.
tokens... | set_static_units_from_idx | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def set_non_positional_from_idx (self, coords_dest, tokens_idx_src):
"""
Sets non_positional properties and index of new tokens as given in the library.
Parameters
----------
coords_dest : numpy.array of shape (2, ?) of int
Coords where to set new tokens, 0th array in... |
Sets non_positional properties and index of new tokens as given in the library.
Parameters
----------
coords_dest : numpy.array of shape (2, ?) of int
Coords where to set new tokens, 0th array in batch dim and 1th array in time dim.
tokens_idx_src : numpy.array of sh... | set_non_positional_from_idx | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def move_dummies (self, coords_src, coords_dest, do_update_relationships_pos = True, do_fill_with_void = True):
"""
Moves dummies from coords_src to coords_dest.
! This function only works for dummies placed as placeholders that are completing programs. !
-> Does not work for moved ... |
Moves dummies from coords_src to coords_dest.
! This function only works for dummies placed as placeholders that are completing programs. !
-> Does not work for moved tokens that have sibling relationships to each others
and does not update dummies' children nor their ances... | move_dummies | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def update_relationships_pos_of_moved_tokens (coords_b_move, coords_a_move):
"""
Updates position of dummy tokens that were moved in other tokens corresponding to family relationships
(parent, siblings).
! This function only works for dummies placed as placeholders that a... |
Updates position of dummy tokens that were moved in other tokens corresponding to family relationships
(parent, siblings).
! This function only works for dummies placed as placeholders that are completing programs. !
-> Does not work for moved tokens that have sibli... | update_relationships_pos_of_moved_tokens | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def fill_with_void(self, coords_dest):
"""
Helper function that fills coords_dest with void invalid token.
Parameters
----------
coords_dest : numpy.array of shape (2, ?) of int
Coords where to fill with void, 0th array in batch dim and 1th array in time dim.
... |
Helper function that fills coords_dest with void invalid token.
Parameters
----------
coords_dest : numpy.array of shape (2, ?) of int
Coords where to fill with void, 0th array in batch dim and 1th array in time dim.
| fill_with_void | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def compute_sum_arities(self, step=0):
"""
Computes total arities of programs along time dim from step = 0 to step = step.
Parameters
----------
step : int
Step where to end summation.
Returns
-------
sum : numpy.array of shape (batch_size,) of... |
Computes total arities of programs along time dim from step = 0 to step = step.
Parameters
----------
step : int
Step where to end summation.
Returns
-------
sum : numpy.array of shape (batch_size,) of int
Sum along time dim of size (batch... | compute_sum_arities | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def n_completed(self):
"""
Lengths of programs when completed by dummies.
Returns
-------
completed_lengths : numpy.array of shape (batch_size,) of int
"""
# Computes length when completed by dummies.
return self.n_lengths + self.n_dummies # (batch_size,)... |
Lengths of programs when completed by dummies.
Returns
-------
completed_lengths : numpy.array of shape (batch_size,) of int
| n_completed | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def n_complexity(self):
"""
Complexities of programs.
Returns
-------
complexity : numpy.array of shape (batch_size,) of int
"""
# Summing over time dim
return self.tokens.complexity.sum(axis=1) # (batch_size,) of int |
Complexities of programs.
Returns
-------
complexity : numpy.array of shape (batch_size,) of int
| n_complexity | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def n_free_const_occurrences(self):
"""
Number of occurrences of free const in programs.
This is to know if we should bother running the optimization process.
Returns
-------
occurrences : numpy.array of shape (batch_size,) of int
"""
is_free_const = ((sel... |
Number of occurrences of free const in programs.
This is to know if we should bother running the optimization process.
Returns
-------
occurrences : numpy.array of shape (batch_size,) of int
| n_free_const_occurrences | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def get_prog_tokens(self, prog_idx=0):
"""
Returns a list of tokens representing a single program of idx = prog_idx.
Discards void tokens beyond program length.
Parameters
----------
prog_idx : int
Index of program in batch.
Returns
-------
... |
Returns a list of tokens representing a single program of idx = prog_idx.
Discards void tokens beyond program length.
Parameters
----------
prog_idx : int
Index of program in batch.
Returns
-------
tokens : numpy.array of token.Token
... | get_prog_tokens | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def get_prog(self, prog_idx=0, skeleton = False, detach = False):
"""
Returns a Program object of program of idx = prog_idx in batch.
Discards void tokens beyond program length.
Parameters
----------
prog_idx : int
Index of program in batch.
skeleton :... |
Returns a Program object of program of idx = prog_idx in batch.
Discards void tokens beyond program length.
Parameters
----------
prog_idx : int
Index of program in batch.
skeleton : bool
Only exports the bare minimum pickable version of the progr... | get_prog | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def batch_exe_reduce_gather (self, X, reduce_wrapper,
# Realization related
i_realization = 0,
n_samples_per_dataset = None,
# Mask
mask = None,
... |
Executes prog(X) for each prog in progs and gathers reduce_wrapper(prog(X)) as a result.
NB: Parallel execution is typically slower because of communication time (even just gathering a float).
Parameters
----------
X : torch.tensor of shape (n_dim, n_samples,) of float
... | batch_exe_reduce_gather | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def batch_exe_reward (self, X, y_target, reward_function, y_weights = 1.,
# Realization related
i_realization = 0,
n_samples_per_dataset = None,
# Mask
... |
Executes prog(X) for each prog in progs and gathers reward_function(y_target, prog(X), y_weights) as a result.
NB: Parallel execution is typically slower because of communication time (even just gathering a float).
Parameters
----------
X : torch.tensor of shape (n_dim, n_sample... | batch_exe_reward | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def batch_optimize_constants (self, X, y_target, free_const_opti_args=None, y_weights = 1.,
# Realization related
i_realization = 0,
n_samples_per_dataset = None,
# Mask
... |
Optimizes the free constants of each program in progs.
NB: Parallel execution is typically faster.
Parameters
----------
X : torch.tensor of shape (n_dim, n_samples,) of float
Values of the input variables of the problem with n_dim = nb of input variables.
y_... | batch_optimize_constants | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def get_infix_str (self, prog_idx = 0):
"""
Computes infix str representation of a program.
(which is the usual way to note symbolic function: +34 (in polish notation) = 3+4 (in infix notation))
Parameters
----------
prog_idx : int
Index of program in VectProg... |
Computes infix str representation of a program.
(which is the usual way to note symbolic function: +34 (in polish notation) = 3+4 (in infix notation))
Parameters
----------
prog_idx : int
Index of program in VectPrograms.
Returns
-------
progr... | get_infix_str | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def get_infix_sympy (self, prog_idx = 0, do_simplify = True):
"""
Returns sympy symbolic representation of a program.
Parameters
----------
prog_idx : int
Index of program in VectPrograms.
do_simplify : bool
If True performs a symbolic simplificati... |
Returns sympy symbolic representation of a program.
Parameters
----------
prog_idx : int
Index of program in VectPrograms.
do_simplify : bool
If True performs a symbolic simplification of program.
Returns
-------
program_sympy : sy... | get_infix_sympy | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def get_infix_pretty (self, prog_idx = 0, do_simplify = True):
"""
Returns a printable ASCII sympy.pretty representation of a program.
Parameters
----------
prog_idx : int
Index of program in VectPrograms.
do_simplify : bool
If True performs a symb... |
Returns a printable ASCII sympy.pretty representation of a program.
Parameters
----------
prog_idx : int
Index of program in VectPrograms.
do_simplify : bool
If True performs a symbolic simplification of program.
Returns
-------
pr... | get_infix_pretty | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def get_infix_latex (self, prog_idx = 0, replace_dummy_symbol = True, new_dummy_symbol = "?", do_simplify = True):
"""
Returns an str latex representation of a program.
Parameters
----------
prog_idx : int
Index of program in VectPrograms.
replace_dummy_symbol... |
Returns an str latex representation of a program.
Parameters
----------
prog_idx : int
Index of program in VectPrograms.
replace_dummy_symbol : bool
If True, dummy symbol is replaced by new_dummy_symbol.
new_dummy_symbol : str or None
... | get_infix_latex | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def get_infix_fig (self,
prog_idx = 0,
replace_dummy_symbol = True,
new_dummy_symbol = "?",
do_simplify = True,
show_superparent_at_beginning = True,
text_size = 16,
... |
Returns pyplot (figure, axis) containing analytic symbolic function program.
Parameters
----------
prog_idx : int
Index of program in VectPrograms.
replace_dummy_symbol : bool
If True, dummy symbol is replaced by new_dummy_symbol.
new_dummy_symbol... | get_infix_fig | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def get_infix_image(self,
prog_idx = 0,
replace_dummy_symbol = True,
new_dummy_symbol = "?",
do_simplify = True,
text_size = 16,
text_pos = (0.0, 0.5),
... |
Returns image containing analytic symbolic function program.
Parameters
----------
prog_idx : int
Index of program in VectPrograms.
replace_dummy_symbol : bool
If True, dummy symbol is replaced by new_dummy_symbol.
new_dummy_symbol : str or None
... | get_infix_image | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def show_infix(self,
prog_idx=0,
replace_dummy_symbol = True,
new_dummy_symbol = "?",
do_simplify = True,
text_size=16,
text_pos=(0.0, 0.5),
figsize=(10, 2),
):
... |
Shows pyplot (figure, axis) containing analytic symbolic function program.
Parameters
----------
prog_idx : int
Index of program in VectPrograms.
replace_dummy_symbol : bool
If True, dummy symbol is replaced by new_dummy_symbol.
new_dummy_symbol :... | show_infix | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def get_tree_graph (self, prog_idx = 0,
n_dim_units = 3,
shape = "circle",
constraint_color = AGRAPH_BLUE,
vanilla_color = AGRAPH_BLACK,
dummy_color = AGRAPH_RED,
special_color = AGRAPH_RED,
special_color_pos = None,
edge_c... |
Returns a graph representation of a program tree encoding parent, children relationships, physical units
and position.
Parameters
----------
prog_idx : int
Index of program in VectPrograms.
shape : str
Shape of nodes in graph (passed to pygraphvi... | get_tree_graph | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def get_tree_latex (self, prog_idx = 0, fpath = None, **args_get_tree_graph):
"""
Returns a latex code of the tree program.
Parameters
----------
prog_idx : int
Index of program in VectPrograms.
fpath : str or None
Path where to save latex code. B... |
Returns a latex code of the tree program.
Parameters
----------
prog_idx : int
Index of program in VectPrograms.
fpath : str or None
Path where to save latex code. By default = None, nothing is saved.
args_get_tree_graph : dict
Additi... | get_tree_latex | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def get_tree_image (self, prog_idx = 0, fpath = None, **args_get_tree_graph):
"""
Returns an image of the tree program (less pretty than get_tree_image_via_tex).
Parameters
----------
prog_idx : int
Index of program in VectPrograms.
fpath : str or None
... |
Returns an image of the tree program (less pretty than get_tree_image_via_tex).
Parameters
----------
prog_idx : int
Index of program in VectPrograms.
fpath : str or None
Path where to save image. By default, = None, nothing is saved.
args_get_tr... | get_tree_image | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def get_tree_image_via_tex (self, prog_idx = 0, fname = None, dpi = 300, **args_get_tree_graph):
"""
Returns an image of the tree program going through latex (prettier than get_tree_image by leveraging features
of latex that are not available in AGraph.draw).
Exports AGraph -> .tex (via ... |
Returns an image of the tree program going through latex (prettier than get_tree_image by leveraging features
of latex that are not available in AGraph.draw).
Exports AGraph -> .tex (via dot2tex) -> .pdf (via PDFLaTeX) -> image (via pdf2image)
Parameters
----------
prog_... | get_tree_image_via_tex | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def show_tree (self, prog_idx = 0, via_tex = False, figsize = (30,30), dpi = 300, **args_get_tree_graph):
"""
Shows pyplot (figure, axis) containing tree of program.
Parameters
----------
prog_idx : int
Index of program in VectPrograms.
via_tex : bool
... |
Shows pyplot (figure, axis) containing tree of program.
Parameters
----------
prog_idx : int
Index of program in VectPrograms.
via_tex : bool
If True uses get_tree_image_via_tex (prettier), else uses get_tree_image.
figsize : tuple of int
... | show_tree | python | WassimTenachi/PhySO | physo/physym/vect_programs.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py | MIT |
def check_args_and_build_run_config(multi_X, multi_y, multi_y_weights,
# X
X_names,
X_units,
# y
y_name ,
y_units,
# Fixed constants
fixed_consts,
fixed_consts_units,
# Class free constants
... |
Checks arguments of SR and ClassSR functions and builds run_config for physo.task.fit.
| check_args_and_build_run_config | python | WassimTenachi/PhySO | physo/task/args_handler.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/task/args_handler.py | MIT |
def dummy_epoch_ClassSR (multi_X, multi_y, run_config, multi_y_weights=1.):
"""
Dummy epoch for class SR task.
Plots reward distribution and programs lengths distribution.
Parameters
----------
multi_X : list of len (n_realizations,) of np.array of shape (n_dim, ?,) of float
List of X (... |
Dummy epoch for class SR task.
Plots reward distribution and programs lengths distribution.
Parameters
----------
multi_X : list of len (n_realizations,) of np.array of shape (n_dim, ?,) of float
List of X (one per realization). With X being values of the input variables of the problem wit... | dummy_epoch_ClassSR | python | WassimTenachi/PhySO | physo/task/checks.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/task/checks.py | MIT |
def dummy_epoch_SR (X, y, run_config, y_weights = 1.):
"""
Dummy epoch for SR task.
Plots reward distribution and programs lengths distribution.
Parameters
----------
X : numpy.array of shape (n_dim, ?,) of float
Values of the input variables of the problem with n_dim = nb of input varia... |
Dummy epoch for SR task.
Plots reward distribution and programs lengths distribution.
Parameters
----------
X : numpy.array of shape (n_dim, ?,) of float
Values of the input variables of the problem with n_dim = nb of input variables.
y : numpy.array of shape (?,) of float
Value... | dummy_epoch_SR | python | WassimTenachi/PhySO | physo/task/checks.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/task/checks.py | MIT |
def sanity_check_ClassSR (multi_X, multi_y, run_config, multi_y_weights = 1., candidate_wrapper = None, target_program_str = None, expected_ideal_reward = 1.):
"""
Checks if finding the target program would give the expected ideal reward.
Parameters
----------
multi_X : list of len (n_realizations,)... |
Checks if finding the target program would give the expected ideal reward.
Parameters
----------
multi_X : list of len (n_realizations,) of np.array of shape (n_dim, ?,) of float
List of X (one per realization). With X being values of the input variables of the problem with n_dim = nb
o... | sanity_check_ClassSR | python | WassimTenachi/PhySO | physo/task/checks.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/task/checks.py | MIT |
def sanity_check_SR (X, y, run_config, y_weights = 1., candidate_wrapper = None, target_program_str = None, expected_ideal_reward = 1.):
"""
Checks if finding the target program would give the expected ideal reward.
Parameters
----------
X : numpy.array of shape (n_dim, ?,) of float
Values o... |
Checks if finding the target program would give the expected ideal reward.
Parameters
----------
X : numpy.array of shape (n_dim, ?,) of float
Values of the input variables of the problem with n_dim = nb of input variables.
y : numpy.array of shape (?,) of float
Values of the target... | sanity_check_SR | python | WassimTenachi/PhySO | physo/task/checks.py | https://github.com/WassimTenachi/PhySO/blob/master/physo/task/checks.py | MIT |
def on_train_begin(self, args: "TrainingArguments", state: "TrainerState", control: "TrainerControl", **kwargs):
r"""
Event called at the beginning of training.
"""
if state.is_local_process_zero:
self.in_training = True
self.start_time = time.time()
s... |
Event called at the beginning of training.
| on_train_begin | python | WangRongsheng/CareGPT | src/llmtuner/extras/callbacks.py | https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/extras/callbacks.py | MIT |
def on_train_end(self, args: "TrainingArguments", state: "TrainerState", control: "TrainerControl", **kwargs):
r"""
Event called at the end of training.
"""
if state.is_local_process_zero:
self.in_training = False
self.cur_steps = 0
self.max_steps = 0 |
Event called at the end of training.
| on_train_end | python | WangRongsheng/CareGPT | src/llmtuner/extras/callbacks.py | https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/extras/callbacks.py | MIT |
def on_substep_end(self, args: "TrainingArguments", state: "TrainerState", control: "TrainerControl", **kwargs):
r"""
Event called at the end of an substep during gradient accumulation.
"""
if state.is_local_process_zero and self.runner is not None and self.runner.aborted:
co... |
Event called at the end of an substep during gradient accumulation.
| on_substep_end | python | WangRongsheng/CareGPT | src/llmtuner/extras/callbacks.py | https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/extras/callbacks.py | MIT |
def on_step_end(self, args: "TrainingArguments", state: "TrainerState", control: "TrainerControl", **kwargs):
r"""
Event called at the end of a training step.
"""
if state.is_local_process_zero:
self.cur_steps = state.global_step
self.timing()
if self.... |
Event called at the end of a training step.
| on_step_end | python | WangRongsheng/CareGPT | src/llmtuner/extras/callbacks.py | https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/extras/callbacks.py | MIT |
def on_evaluate(self, args: "TrainingArguments", state: "TrainerState", control: "TrainerControl", **kwargs):
r"""
Event called after an evaluation phase.
"""
if state.is_local_process_zero and not self.in_training:
self.cur_steps = 0
self.max_steps = 0 |
Event called after an evaluation phase.
| on_evaluate | python | WangRongsheng/CareGPT | src/llmtuner/extras/callbacks.py | https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/extras/callbacks.py | MIT |
def on_log(self, args: "TrainingArguments", state: "TrainerState", control: "TrainerControl", **kwargs) -> None:
r"""
Event called after logging the last logs.
"""
if not state.is_local_process_zero:
return
logs = dict(
current_steps=self.cur_steps,
... |
Event called after logging the last logs.
| on_log | python | WangRongsheng/CareGPT | src/llmtuner/extras/callbacks.py | https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/extras/callbacks.py | MIT |
def reset_logging():
r"""
Removes basic config of root logger
"""
root = logging.getLogger()
list(map(root.removeHandler, root.handlers))
list(map(root.removeFilter, root.filters)) |
Removes basic config of root logger
| reset_logging | python | WangRongsheng/CareGPT | src/llmtuner/extras/logging.py | https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/extras/logging.py | MIT |
def count_parameters(model: torch.nn.Module) -> Tuple[int, int]:
r"""
Returns the number of trainable parameters and number of all parameters in the model.
"""
trainable_params, all_param = 0, 0
for param in model.parameters():
num_params = param.numel()
# if using DS Zero 3 and the ... |
Returns the number of trainable parameters and number of all parameters in the model.
| count_parameters | python | WangRongsheng/CareGPT | src/llmtuner/extras/misc.py | https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/extras/misc.py | MIT |
def dispatch_model(model: "PreTrainedModel") -> "PreTrainedModel":
r"""
Dispatches a pre-trained model to GPUs with balanced memory.
Borrowed from: https://github.com/huggingface/transformers/blob/v4.31.0/src/transformers/modeling_utils.py#L2803
"""
if getattr(model, "is_loaded_in_8bit", False) or g... |
Dispatches a pre-trained model to GPUs with balanced memory.
Borrowed from: https://github.com/huggingface/transformers/blob/v4.31.0/src/transformers/modeling_utils.py#L2803
| dispatch_model | python | WangRongsheng/CareGPT | src/llmtuner/extras/misc.py | https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/extras/misc.py | MIT |
def encode_oneturn(
self,
tokenizer: "PreTrainedTokenizer",
query: str,
resp: str,
history: Optional[List[Tuple[str, str]]] = None,
system: Optional[str] = None
) -> Tuple[List[int], List[int]]:
r"""
Returns a single pair of token ids representing prom... |
Returns a single pair of token ids representing prompt and response respectively.
| encode_oneturn | python | WangRongsheng/CareGPT | src/llmtuner/extras/template.py | https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/extras/template.py | MIT |
def encode_multiturn(
self,
tokenizer: "PreTrainedTokenizer",
query: str,
resp: str,
history: Optional[List[Tuple[str, str]]] = None,
system: Optional[str] = None
) -> List[Tuple[List[int], List[int]]]:
r"""
Returns multiple pairs of token ids represen... |
Returns multiple pairs of token ids representing prompts and responses respectively.
| encode_multiturn | python | WangRongsheng/CareGPT | src/llmtuner/extras/template.py | https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/extras/template.py | MIT |
def _format(
self,
query: str,
resp: str,
history: Optional[List[Tuple[str, str]]] = None,
system: Optional[str] = None
) -> Tuple[str, List[Tuple[str, str]]]:
r"""
Aligns inputs to the standard format.
"""
system = system or self.system # use ... |
Aligns inputs to the standard format.
| _format | python | WangRongsheng/CareGPT | src/llmtuner/extras/template.py | https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/extras/template.py | MIT |
def _encode(
self,
tokenizer: "PreTrainedTokenizer",
system: str,
history: List[Tuple[str, str]]
) -> List[Tuple[List[int], List[int]]]:
r"""
Encodes formatted inputs to pairs of token ids.
Turn 0: bos + prefix + sep + query resp + eos
Turn t: sep +... |
Encodes formatted inputs to pairs of token ids.
Turn 0: bos + prefix + sep + query resp + eos
Turn t: sep + bos + query resp + eos
| _encode | python | WangRongsheng/CareGPT | src/llmtuner/extras/template.py | https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/extras/template.py | MIT |
def _encode(
self,
tokenizer: "PreTrainedTokenizer",
system: str,
history: List[Tuple[str, str]]
) -> List[Tuple[List[int], List[int]]]:
r"""
Encodes formatted inputs to pairs of token ids.
Turn 0: bos + prefix + query resp + eos
Turn t: bos + query... |
Encodes formatted inputs to pairs of token ids.
Turn 0: bos + prefix + query resp + eos
Turn t: bos + query resp + eos
| _encode | python | WangRongsheng/CareGPT | src/llmtuner/extras/template.py | https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/extras/template.py | MIT |
def save_to_json(self, json_path: str):
r"""Saves the content of this instance in JSON format inside `json_path`."""
json_string = json.dumps(asdict(self), indent=2, sort_keys=True) + "\n"
with open(json_path, "w", encoding="utf-8") as f:
f.write(json_string) | Saves the content of this instance in JSON format inside `json_path`. | save_to_json | python | WangRongsheng/CareGPT | src/llmtuner/hparams/finetuning_args.py | https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/hparams/finetuning_args.py | MIT |
def load_from_json(cls, json_path: str):
r"""Creates an instance from the content of `json_path`."""
with open(json_path, "r", encoding="utf-8") as f:
text = f.read()
return cls(**json.loads(text)) | Creates an instance from the content of `json_path`. | load_from_json | python | WangRongsheng/CareGPT | src/llmtuner/hparams/finetuning_args.py | https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/hparams/finetuning_args.py | MIT |
def init_adapter(
model: "PreTrainedModel",
model_args: "ModelArguments",
finetuning_args: "FinetuningArguments",
is_trainable: bool,
is_mergeable: bool
) -> "PreTrainedModel":
r"""
Initializes the adapters.
Support full-parameter, freeze and LoRA training.
Note that the trainable ... |
Initializes the adapters.
Support full-parameter, freeze and LoRA training.
Note that the trainable parameters must be cast to float32.
| init_adapter | python | WangRongsheng/CareGPT | src/llmtuner/tuner/core/adapter.py | https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/tuner/core/adapter.py | MIT |
def load_model_and_tokenizer(
model_args: "ModelArguments",
finetuning_args: "FinetuningArguments",
is_trainable: Optional[bool] = False,
stage: Optional[Literal["pt", "sft", "rm", "ppo"]] = "sft"
) -> Tuple[PreTrainedModel, "PreTrainedTokenizer"]:
r"""
Loads pretrained model and tokenizer.
... |
Loads pretrained model and tokenizer.
Support both training and inference.
| load_model_and_tokenizer | python | WangRongsheng/CareGPT | src/llmtuner/tuner/core/loader.py | https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/tuner/core/loader.py | MIT |
def _save(self, output_dir: Optional[str] = None, state_dict: Optional[Dict[str, torch.Tensor]] = None) -> None:
r"""
Saves trainable parameters as model checkpoint.
This function will only be executed at the process zero.
Subclass and override to inject custom behavior. It should not ... |
Saves trainable parameters as model checkpoint.
This function will only be executed at the process zero.
Subclass and override to inject custom behavior. It should not be directly used by external scripts.
| _save | python | WangRongsheng/CareGPT | src/llmtuner/tuner/core/trainer.py | https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/tuner/core/trainer.py | MIT |
def _load_best_model(self):
r"""
Loads trainable parameters from model checkpoint.
Subclass and override to inject custom behavior. It should not be directly used by external scripts.
"""
logger.info(f"Loading best model from {self.state.best_model_checkpoint} (score: {self.stat... |
Loads trainable parameters from model checkpoint.
Subclass and override to inject custom behavior. It should not be directly used by external scripts.
| _load_best_model | python | WangRongsheng/CareGPT | src/llmtuner/tuner/core/trainer.py | https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/tuner/core/trainer.py | MIT |
def __call__(self, features: Sequence[Dict[str, Any]]) -> Dict[str, torch.Tensor]:
r"""
Pads batched data to the longest sequence in the batch.
We generate 2 * n examples where the first n examples represent chosen examples and
the last n examples represent rejected examples.
""... |
Pads batched data to the longest sequence in the batch.
We generate 2 * n examples where the first n examples represent chosen examples and
the last n examples represent rejected examples.
| __call__ | python | WangRongsheng/CareGPT | src/llmtuner/tuner/dpo/collator.py | https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/tuner/dpo/collator.py | MIT |
def ppo_train(self, max_target_length: int) -> None:
r"""
Implements training loop for the PPO stage, like _inner_training_loop() in Huggingface's Trainer.
"""
total_train_batch_size = (
self.args.per_device_train_batch_size * self.args.gradient_accumulation_steps * self.args... |
Implements training loop for the PPO stage, like _inner_training_loop() in Huggingface's Trainer.
| ppo_train | python | WangRongsheng/CareGPT | src/llmtuner/tuner/ppo/trainer.py | https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/tuner/ppo/trainer.py | MIT |
def get_rewards(
self,
queries: List[torch.Tensor],
responses: List[torch.Tensor],
unwrapped_model: "AutoModelForCausalLMWithValueHead"
) -> List[torch.Tensor]:
r"""
Computes scores using given reward model.
"""
replace_model(unwrapped_model, target="r... |
Computes scores using given reward model.
| get_rewards | python | WangRongsheng/CareGPT | src/llmtuner/tuner/ppo/trainer.py | https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/tuner/ppo/trainer.py | MIT |
def batched_forward_pass(
self,
model: "AutoModelForCausalLMWithValueHead",
queries: torch.Tensor,
responses: torch.Tensor,
model_inputs: dict,
return_logits: Optional[bool] = False
):
r"""
Calculates model outputs in multiple batches.
Subclas... |
Calculates model outputs in multiple batches.
Subclass and override to inject custom behavior.
| batched_forward_pass | python | WangRongsheng/CareGPT | src/llmtuner/tuner/ppo/trainer.py | https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/tuner/ppo/trainer.py | MIT |
def __call__(self, features: Sequence[Dict[str, Any]]) -> Dict[str, torch.Tensor]:
r"""
Pads batched data to the longest sequence in the batch.
We generate 2 * n examples where the first n examples represent chosen examples and
the last n examples represent rejected examples.
""... |
Pads batched data to the longest sequence in the batch.
We generate 2 * n examples where the first n examples represent chosen examples and
the last n examples represent rejected examples.
| __call__ | python | WangRongsheng/CareGPT | src/llmtuner/tuner/rm/collator.py | https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/tuner/rm/collator.py | MIT |
def compute_loss(
self,
model: "PreTrainedModel",
inputs: Dict[str, torch.Tensor],
return_outputs: Optional[bool] = False
) -> Union[torch.Tensor, Tuple[torch.Tensor, List[torch.Tensor]]]:
r"""
Computes pairwise loss. The first n examples are chosen and the last n exa... |
Computes pairwise loss. The first n examples are chosen and the last n examples are rejected.
We use score on the EOS token to represent reward of the whole sentence.
Subclass and override to inject custom behavior. It should not be directly used by external scripts.
Note that the fi... | compute_loss | python | WangRongsheng/CareGPT | src/llmtuner/tuner/rm/trainer.py | https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/tuner/rm/trainer.py | MIT |
def save_predictions(
self,
predict_results: "PredictionOutput"
) -> None:
r"""
Saves model predictions to `output_dir`.
A custom behavior that not contained in Seq2SeqTrainer.
"""
if not self.is_world_process_zero():
return
output_predic... |
Saves model predictions to `output_dir`.
A custom behavior that not contained in Seq2SeqTrainer.
| save_predictions | python | WangRongsheng/CareGPT | src/llmtuner/tuner/rm/trainer.py | https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/tuner/rm/trainer.py | MIT |
def __call__(self, eval_preds: Sequence[Union[np.ndarray, Tuple[np.ndarray]]]) -> Dict[str, float]:
r"""
Uses the model predictions to compute metrics.
"""
preds, labels = eval_preds
score_dict = {"rouge-1": [], "rouge-2": [], "rouge-l": [], "bleu-4": []}
preds = np.wher... |
Uses the model predictions to compute metrics.
| __call__ | python | WangRongsheng/CareGPT | src/llmtuner/tuner/sft/metric.py | https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/tuner/sft/metric.py | MIT |
def prediction_step(
self,
model: nn.Module,
inputs: Dict[str, Union[torch.Tensor, Any]],
prediction_loss_only: bool,
ignore_keys: Optional[List[str]] = None,
) -> Tuple[Optional[float], Optional[torch.Tensor], Optional[torch.Tensor]]:
r"""
Removes the prompt ... |
Removes the prompt part in the generated tokens.
Subclass and override to inject custom behavior.
| prediction_step | python | WangRongsheng/CareGPT | src/llmtuner/tuner/sft/trainer.py | https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/tuner/sft/trainer.py | MIT |
def _pad_tensors_to_target_len(
self,
src_tensor: torch.Tensor,
tgt_tensor: torch.Tensor,
pad_token_id: Optional[int] = None
) -> torch.Tensor:
r"""
Pads the tensor to the same length as the target tensor.
Should only be called when predict_with_generate=True... |
Pads the tensor to the same length as the target tensor.
Should only be called when predict_with_generate=True.
| _pad_tensors_to_target_len | python | WangRongsheng/CareGPT | src/llmtuner/tuner/sft/trainer.py | https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/tuner/sft/trainer.py | MIT |
def save_predictions(
self,
predict_results: "PredictionOutput"
) -> None:
r"""
Saves model predictions to `output_dir`.
A custom behavior that not contained in Seq2SeqTrainer.
"""
if not self.is_world_process_zero():
return
output_predic... |
Saves model predictions to `output_dir`.
A custom behavior that not contained in Seq2SeqTrainer.
| save_predictions | python | WangRongsheng/CareGPT | src/llmtuner/tuner/sft/trainer.py | https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/tuner/sft/trainer.py | MIT |
def __init__(self, enum_obj: t.Any) -> None:
"""Initialize attributes for informative output.
:param enum_obj: Enum object.
"""
if enum_obj:
self.name = enum_obj
self.items = ", ".join(map(str, enum_obj))
else:
self.items = "" | Initialize attributes for informative output.
:param enum_obj: Enum object.
| __init__ | python | lk-geimfari/mimesis | mimesis/exceptions.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/exceptions.py | MIT |
def romanize(locale: Locale) -> Callable[[str], str]:
"""Create a closure function to romanize a given string in the specified locale.
Supported locales are:
- Locale.RU (Russian)
- Locale.UK (Ukrainian)
- Locale.KK (Kazakh)
:param locale: Locale.
:return: A closure that takes a string an... | Create a closure function to romanize a given string in the specified locale.
Supported locales are:
- Locale.RU (Russian)
- Locale.UK (Ukrainian)
- Locale.KK (Kazakh)
:param locale: Locale.
:return: A closure that takes a string and returns a romanized string.
| romanize | python | lk-geimfari/mimesis | mimesis/keys.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/keys.py | MIT |
def maybe(value: Any, probability: float = 0.5) -> Callable[[Any, Random], Any]:
"""Return a closure (a key function).
The returned closure itself returns either **value** or
the first argument passed to closure with a certain probability (0.5 by default).
:param value: The value that may be returned.... | Return a closure (a key function).
The returned closure itself returns either **value** or
the first argument passed to closure with a certain probability (0.5 by default).
:param value: The value that may be returned.
:param probability: The probability of returning **value**.
:return: A closure ... | maybe | python | lk-geimfari/mimesis | mimesis/keys.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/keys.py | MIT |
def randints(self, n: int = 3, a: int = 1, b: int = 100) -> list[int]:
"""Generate a list of random integers.
:param n: Number of elements.
:param a: Minimum value of range.
:param b: Maximum value of range.
:return: List of random integers.
:raises ValueError: if the nu... | Generate a list of random integers.
:param n: Number of elements.
:param a: Minimum value of range.
:param b: Maximum value of range.
:return: List of random integers.
:raises ValueError: if the number is less or equal to zero.
| randints | python | lk-geimfari/mimesis | mimesis/random.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/random.py | MIT |
def generate_string_by_mask(
self,
mask: str = "@###",
char: str = "@",
digit: str = "#",
) -> str:
"""Generate custom code using ascii uppercase and random integers.
:param mask: Mask of code.
:param char: Placeholder for characters.
:param digit: Pl... | Generate custom code using ascii uppercase and random integers.
:param mask: Mask of code.
:param char: Placeholder for characters.
:param digit: Placeholder for digits.
:return: Custom code.
| generate_string_by_mask | python | lk-geimfari/mimesis | mimesis/random.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/random.py | MIT |
def weighted_choice(self, choices: dict[t.Any, float]) -> t.Any:
"""Returns a random element according to the specified weights.
:param choices: A dictionary where keys are choices and values are weights.
:raises ValueError: If choices are empty.
:return: Random key from dictionary.
... | Returns a random element according to the specified weights.
:param choices: A dictionary where keys are choices and values are weights.
:raises ValueError: If choices are empty.
:return: Random key from dictionary.
| weighted_choice | python | lk-geimfari/mimesis | mimesis/random.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/random.py | MIT |
def __init__(
self,
locale: Locale = Locale.DEFAULT,
seed: Seed = MissingSeed,
) -> None:
"""Base class for fields.
This class is used as a base class for :class:`Field` and :class:`Fieldset`.
:attr: aliases: A dictionary of aliases for standard fields.
:par... | Base class for fields.
This class is used as a base class for :class:`Field` and :class:`Fieldset`.
:attr: aliases: A dictionary of aliases for standard fields.
:param locale: Locale.
:param seed: Seed for random.
| __init__ | python | lk-geimfari/mimesis | mimesis/schema.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/schema.py | MIT |
def _explicit_lookup(self, name: str) -> Any:
"""An explicit method lookup.
This method is called when the field
defined explicitly, like this: ``provider.method``
:param name: The field name.
:return: Callable object.
:raise FieldError: When field is invalid.
"... | An explicit method lookup.
This method is called when the field
defined explicitly, like this: ``provider.method``
:param name: The field name.
:return: Callable object.
:raise FieldError: When field is invalid.
| _explicit_lookup | python | lk-geimfari/mimesis | mimesis/schema.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/schema.py | MIT |
def _fuzzy_lookup(self, name: str) -> Any:
"""A fuzzy method lookup.
This method is called when the field definition
is fuzzy, like this: ``method``
:param name: The field name.
:return: Callable object.
:raise FieldError: When field is invalid.
"""
for ... | A fuzzy method lookup.
This method is called when the field definition
is fuzzy, like this: ``method``
:param name: The field name.
:return: Callable object.
:raise FieldError: When field is invalid.
| _fuzzy_lookup | python | lk-geimfari/mimesis | mimesis/schema.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/schema.py | MIT |
def _lookup_method(self, name: str) -> Any:
"""Lookup method by the field name.
:param name: The field name.
:return: Callable object.
:raise FieldError: When field is invalid.
"""
# Check if the field is defined in aliases
name = self.aliases.get(name, name)
... | Lookup method by the field name.
:param name: The field name.
:return: Callable object.
:raise FieldError: When field is invalid.
| _lookup_method | python | lk-geimfari/mimesis | mimesis/schema.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/schema.py | MIT |
def register_handler(self, field_name: str, field_handler: FieldHandler) -> None:
"""Register a new field handler.
:param field_name: Name of the field.
:param field_handler: Callable object.
"""
if not isinstance(field_name, str):
raise TypeError("Field name must b... | Register a new field handler.
:param field_name: Name of the field.
:param field_handler: Callable object.
| register_handler | python | lk-geimfari/mimesis | mimesis/schema.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/schema.py | MIT |
def handle(
self, field_name: str | None = None
) -> Callable[[FieldHandler], FieldHandler]:
"""Decorator for registering a custom field handler.
You can use this decorator only for functions,
not for any other callables.
.. versionadded:: 12.0.0
:param field_name:... | Decorator for registering a custom field handler.
You can use this decorator only for functions,
not for any other callables.
.. versionadded:: 12.0.0
:param field_name: Name of the field.
If not specified, the name of the function is used.
:return: Decorator.
... | handle | python | lk-geimfari/mimesis | mimesis/schema.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/schema.py | MIT |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.