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 test_n_dimensional_is_within_visible_spectrum(self) -> None: """ Test :func:`colour.volume.spectrum.is_within_visible_spectrum` definition n-dimensional arrays support. """ a = np.array([0.3205, 0.4131, 0.5100]) b = is_within_visible_spectrum(a) a = np.tile(...
Test :func:`colour.volume.spectrum.is_within_visible_spectrum` definition n-dimensional arrays support.
test_n_dimensional_is_within_visible_spectrum
python
colour-science/colour
colour/volume/tests/test_spectrum.py
https://github.com/colour-science/colour/blob/master/colour/volume/tests/test_spectrum.py
BSD-3-Clause
def test_nan_is_within_visible_spectrum(self) -> None: """ Test :func:`colour.volume.spectrum.is_within_visible_spectrum` definition nan support. """ cases = [-1.0, 0.0, 1.0, -np.inf, np.inf, np.nan] cases = np.array(list(set(product(cases, repeat=3)))) is_within...
Test :func:`colour.volume.spectrum.is_within_visible_spectrum` definition nan support.
test_nan_is_within_visible_spectrum
python
colour-science/colour
colour/volume/tests/test_spectrum.py
https://github.com/colour-science/colour/blob/master/colour/volume/tests/test_spectrum.py
BSD-3-Clause
def extract_todo_items(root_directory: str) -> dict: """ Extract the TODO items from given directory. Parameters ---------- root_directory Directory to extract the TODO items from. Returns ------- :class:`dict` TODO items. """ todo_items = {} for root, _dir...
Extract the TODO items from given directory. Parameters ---------- root_directory Directory to extract the TODO items from. Returns ------- :class:`dict` TODO items.
extract_todo_items
python
colour-science/colour
utilities/export_todo.py
https://github.com/colour-science/colour/blob/master/utilities/export_todo.py
BSD-3-Clause
def export_todo_items(todo_items: dict, file_path: str) -> None: """ Export TODO items to given file. Parameters ---------- todo_items TODO items. file_path File to write the TODO items to. """ todo_rst = [] for module, module_todo_items in todo_items.items(): ...
Export TODO items to given file. Parameters ---------- todo_items TODO items. file_path File to write the TODO items to.
export_todo_items
python
colour-science/colour
utilities/export_todo.py
https://github.com/colour-science/colour/blob/master/utilities/export_todo.py
BSD-3-Clause
def generate_documentation_plots(output_directory: str) -> None: """ Generate documentation plots. Parameters ---------- output_directory Output directory. """ filter_warnings() colour_style() np.random.seed(0) # ******************************************************...
Generate documentation plots. Parameters ---------- output_directory Output directory.
generate_documentation_plots
python
colour-science/colour
utilities/generate_plots.py
https://github.com/colour-science/colour/blob/master/utilities/generate_plots.py
BSD-3-Clause
def literalise(path_module_hints: str = PATH_MODULE_HINTS) -> None: """ Write various literals in the `colour.hints` module. Parameters ---------- path_module_hints Path to the hints module. """ with open(path_module_hints) as file_module_hints: content = file_module_hints....
Write various literals in the `colour.hints` module. Parameters ---------- path_module_hints Path to the hints module.
literalise
python
colour-science/colour
utilities/literalise.py
https://github.com/colour-science/colour/blob/master/utilities/literalise.py
BSD-3-Clause
def unicode_to_ascii(root_directory: str) -> None: """ Recursively convert from unicode to ASCII *.py*, *.bib* and *.rst* files in given directory. Parameters ---------- root_directory Directory to convert the files from unicode to ASCII. """ for root, _dirnames, filenames in o...
Recursively convert from unicode to ASCII *.py*, *.bib* and *.rst* files in given directory. Parameters ---------- root_directory Directory to convert the files from unicode to ASCII.
unicode_to_ascii
python
colour-science/colour
utilities/unicode_to_ascii.py
https://github.com/colour-science/colour/blob/master/utilities/unicode_to_ascii.py
BSD-3-Clause
def main(argv): ''' examine.py is used to display environments and run policies. For an example environment jsonnet, see mujoco-worldgen/examples/example_env_examine.jsonnet You can find saved policies and the in the 'examples' together with the environment they were trained in and the hype...
examine.py is used to display environments and run policies. For an example environment jsonnet, see mujoco-worldgen/examples/example_env_examine.jsonnet You can find saved policies and the in the 'examples' together with the environment they were trained in and the hyperparameters used. The n...
main
python
openai/multi-agent-emergence-environments
bin/examine.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/bin/examine.py
MIT
def _get_obs(self, sim): ''' Loops through modules, calls their observation_step functions, and adds the result to the observation dictionary. ''' obs = {} for module in self.modules: obs.update(module.observation_step(self, self.sim)) retu...
Loops through modules, calls their observation_step functions, and adds the result to the observation dictionary.
_get_obs
python
openai/multi-agent-emergence-environments
mae_envs/envs/base.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/mae_envs/envs/base.py
MIT
def _get_sim(self, seed): ''' Calls build_world_step and then modify_sim_step for each module. If a build_world_step failed, then restarts. ''' self.floor_size = np.random.uniform(self.floor_size_dist[0], self.floor_size_dist[1]) self.metadata['floor_size'] = self...
Calls build_world_step and then modify_sim_step for each module. If a build_world_step failed, then restarts.
_get_sim
python
openai/multi-agent-emergence-environments
mae_envs/envs/base.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/mae_envs/envs/base.py
MIT
def make_env(n_substeps=5, horizon=250, deterministic_mode=False, n_agents=2, n_boxes=2, n_ramps=1): ''' This make_env function is not used anywhere; it exists to provide a simple, bare-bones example of how to construct a multi-agent environment using the modules framework. ''' ...
This make_env function is not used anywhere; it exists to provide a simple, bare-bones example of how to construct a multi-agent environment using the modules framework.
make_env
python
openai/multi-agent-emergence-environments
mae_envs/envs/base.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/mae_envs/envs/base.py
MIT
def _get_next_obj(self, obs): ''' Return the next object that needs to be locked & the distance to it. ''' agent_pos = obs[self.agent_key][:, :2] if len(self.unlocked_objs) == 0: next_obj = None next_obj_dist = 0 elif self.task == 'order': ...
Return the next object that needs to be locked & the distance to it.
_get_next_obj
python
openai/multi-agent-emergence-environments
mae_envs/envs/box_locking.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/mae_envs/envs/box_locking.py
MIT
def _get_lock_reward(self, curr_objs_locked, old_objs_locked): ''' Calculates the locking reward / unlocking penalty ''' n_new_lock = np.sum(np.logical_and(curr_objs_locked == 1, old_objs_locked == 0)) n_new_unlock = np.sum(np.logical_and(curr_objs_locked == 0, old_objs_locke...
Calculates the locking reward / unlocking penalty
_get_lock_reward
python
openai/multi-agent-emergence-environments
mae_envs/envs/box_locking.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/mae_envs/envs/box_locking.py
MIT
def _get_shaped_reward(self, new_next_obj, new_next_obj_dist, new_spawn_pos_dist): ''' Calculates the shaped reward based on the change in distance from the target ''' rew = 0 if (self.next_obj is not None) and (new_next_obj == self.next_obj): rew += (self.next_ob...
Calculates the shaped reward based on the change in distance from the target
_get_shaped_reward
python
openai/multi-agent-emergence-environments
mae_envs/envs/box_locking.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/mae_envs/envs/box_locking.py
MIT
def tri_placement(tri_room_idx): ''' This function expects the wall scenario to be 'var_tri' Returns a placement function that randomly places objects in the room with index tri_room_idx ''' def placement(grid, obj_size, metadata, random_state): assert 'tri_room_grid_cell_ran...
This function expects the wall scenario to be 'var_tri' Returns a placement function that randomly places objects in the room with index tri_room_idx
tri_placement
python
openai/multi-agent-emergence-environments
mae_envs/envs/box_locking.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/mae_envs/envs/box_locking.py
MIT
def rotate_tri_placement(grid, obj_size, metadata, random_state): ''' This function expects the wall scenario to be 'var_tri'. It places objects equally among the three rooms, so that any room has contains at most 1 more object than any other room. ''' if 'tri_placement_rotation' not...
This function expects the wall scenario to be 'var_tri'. It places objects equally among the three rooms, so that any room has contains at most 1 more object than any other room.
rotate_tri_placement
python
openai/multi-agent-emergence-environments
mae_envs/envs/box_locking.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/mae_envs/envs/box_locking.py
MIT
def quadrant_placement(grid, obj_size, metadata, random_state): ''' Places object within the bottom right quadrant of the playing field ''' grid_size = len(grid) qsize = metadata['quadrant_size'] pos = np.array([random_state.randint(grid_size - qsize, grid_size - obj_size[0] - 1), ...
Places object within the bottom right quadrant of the playing field
quadrant_placement
python
openai/multi-agent-emergence-environments
mae_envs/envs/hide_and_seek.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/mae_envs/envs/hide_and_seek.py
MIT
def outside_quadrant_placement(grid, obj_size, metadata, random_state): ''' Places object outside of the bottom right quadrant of the playing field ''' grid_size = len(grid) qsize = metadata['quadrant_size'] poses = [ np.array([random_state.randint(1, grid_size - qsize - obj_size[0] ...
Places object outside of the bottom right quadrant of the playing field
outside_quadrant_placement
python
openai/multi-agent-emergence-environments
mae_envs/envs/hide_and_seek.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/mae_envs/envs/hide_and_seek.py
MIT
def get_size_from_xml(obj): ''' Args: obj (worldgen.Obj): worldgen object Returns: size of object annotation:outerbound if it exists, None if it doesn't ''' outer_bound = None for body in parse_file(obj._generate_xml_path())['worldbody']['body']: if body.get('@name', ...
Args: obj (worldgen.Obj): worldgen object Returns: size of object annotation:outerbound if it exists, None if it doesn't
get_size_from_xml
python
openai/multi-agent-emergence-environments
mae_envs/modules/util.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/mae_envs/modules/util.py
MIT
def rejection_placement(env, placement_fn, floor_size, obj_size, num_tries=10): ''' Args: env (gym.Env): environment placement_fn (function): Function that returns a position on a grid Args: grid (np.ndarray): 2D occupancy grid. 1's mean occupied ...
Args: env (gym.Env): environment placement_fn (function): Function that returns a position on a grid Args: grid (np.ndarray): 2D occupancy grid. 1's mean occupied obj_size_in_cells (int np.ndarray): number of cells in [x, y] ...
rejection_placement
python
openai/multi-agent-emergence-environments
mae_envs/modules/util.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/mae_envs/modules/util.py
MIT
def uniform_placement_middle(area_side_length_fraction): ''' Creates a sampling function that samples object position uniformly within the middle of the playing area. E.g. if the playing area is ------ |AAAA| |ABBA| |ABBA| |AAAA| ----...
Creates a sampling function that samples object position uniformly within the middle of the playing area. E.g. if the playing area is ------ |AAAA| |ABBA| |ABBA| |AAAA| ------ then uniform_placement_middle(0.5) will returned a fu...
uniform_placement_middle
python
openai/multi-agent-emergence-environments
mae_envs/modules/util.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/mae_envs/modules/util.py
MIT
def is_touching(self, pt): ''' Is pt (tuple) touching this wall ''' if self.is_vertical: return pt[0] == self.pt1[0] and pt[1] >= self.pt1[1] and pt[1] <= self.pt2[1] else: return pt[1] == self.pt1[1] and pt[0] >= self.pt1[0] and pt[0] <= self.pt2[0]
Is pt (tuple) touching this wall
is_touching
python
openai/multi-agent-emergence-environments
mae_envs/modules/walls.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/mae_envs/modules/walls.py
MIT
def maybe_add_edge(self, wall): ''' Check if wall is originating from this wall. If so add it to the list of edges. ''' if self.is_vertical == wall.is_vertical: return if self.is_touching(wall.pt1): self.right_edges.append(wall.pt1) elif self.i...
Check if wall is originating from this wall. If so add it to the list of edges.
maybe_add_edge
python
openai/multi-agent-emergence-environments
mae_envs/modules/walls.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/mae_envs/modules/walls.py
MIT
def split_for_doors(self, num_doors=1, door_size=1, all_connect=False, random_state=np.random.RandomState()): ''' Split this wall into many walls with 'doors' in between. Args: num_doors (int): upper bound of number of doors to create ...
Split this wall into many walls with 'doors' in between. Args: num_doors (int): upper bound of number of doors to create door_size (int): door size in grid cells all_connect (bool): create a door in every wall segment between pairs of points ...
split_for_doors
python
openai/multi-agent-emergence-environments
mae_envs/modules/walls.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/mae_envs/modules/walls.py
MIT
def connect_walls(wall1, wall2, min_dist_between, random_state=np.random.RandomState()): ''' Draw a random new wall connecting wall1 and wall2. Return None if the drawn wall was closer than min_dist_between to another wall or the wall wasn't valid. NOTE: This DOES NOT check if the cr...
Draw a random new wall connecting wall1 and wall2. Return None if the drawn wall was closer than min_dist_between to another wall or the wall wasn't valid. NOTE: This DOES NOT check if the created wall overlaps with any existing walls, that should be done outside of this fun...
connect_walls
python
openai/multi-agent-emergence-environments
mae_envs/modules/walls.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/mae_envs/modules/walls.py
MIT
def choose_new_split(walls, min_dist_between, num_tries=10, random_state=np.random.RandomState()): ''' Given a list of walls, choose a random wall and draw a new wall perpendicular to it. NOTE: Right now this O(n_walls^2). We could probably get this to linear if we did something smarter ...
Given a list of walls, choose a random wall and draw a new wall perpendicular to it. NOTE: Right now this O(n_walls^2). We could probably get this to linear if we did something smarter with the occupancy grid. Until n_walls gets way bigger this should be fine though. Arg...
choose_new_split
python
openai/multi-agent-emergence-environments
mae_envs/modules/walls.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/mae_envs/modules/walls.py
MIT
def split_walls(walls, door_size, random_state=np.random.RandomState()): ''' Add a door to each wall in walls. Return the new walls and doors. Args: walls (Wall list): walls door_size (int): door size in grid cells random_state (np.random.RandomState): random stat...
Add a door to each wall in walls. Return the new walls and doors. Args: walls (Wall list): walls door_size (int): door size in grid cells random_state (np.random.RandomState): random state to use for sampling
split_walls
python
openai/multi-agent-emergence-environments
mae_envs/modules/walls.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/mae_envs/modules/walls.py
MIT
def construct_door_obs(doors, floor_size, grid_size): ''' Construct door observations in mujoco frame from door positions in grid frame. Args: doors ((n_doors, 2, 2) array): list of pairs of points of door edges. floor_size (float): size of floor grid_size (int): ...
Construct door observations in mujoco frame from door positions in grid frame. Args: doors ((n_doors, 2, 2) array): list of pairs of points of door edges. floor_size (float): size of floor grid_size (int): size of placement grid
construct_door_obs
python
openai/multi-agent-emergence-environments
mae_envs/modules/walls.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/mae_envs/modules/walls.py
MIT
def add_walls_to_grid(grid, walls): ''' Draw walls onto a grid. Args: grid (np.ndarray): 2D occupancy grid walls (Wall list): walls ''' for wall in walls: if wall.is_vertical: grid[wall.pt1[0], wall.pt1[1]:wall.pt2[1] + 1] = 1 else: ...
Draw walls onto a grid. Args: grid (np.ndarray): 2D occupancy grid walls (Wall list): walls
add_walls_to_grid
python
openai/multi-agent-emergence-environments
mae_envs/modules/walls.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/mae_envs/modules/walls.py
MIT
def walls_to_mujoco(floor, floor_size, grid_size, walls, friction=None): ''' Take a list of walls in grid frame and add them to the floor in the worldgen frame. Args: floor (worldgen.Floor): floor floor_size (float): size of floor grid_size (int): size of placemen...
Take a list of walls in grid frame and add them to the floor in the worldgen frame. Args: floor (worldgen.Floor): floor floor_size (float): size of floor grid_size (int): size of placement grid walls (Wall list): list of walls friction (float)...
walls_to_mujoco
python
openai/multi-agent-emergence-environments
mae_envs/modules/walls.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/mae_envs/modules/walls.py
MIT
def dist_pt_to_cuboid(pt1, cuboid_center, cuboid_dims, cuboid_quat): ''' This function calculates the shortest distance between test points and cuboids at arbitrary locations, widths and rotations Args: pt1 (num points x 3): test point positions cuboid_center (num cu...
This function calculates the shortest distance between test points and cuboids at arbitrary locations, widths and rotations Args: pt1 (num points x 3): test point positions cuboid_center (num cuboids x 3): cuboid centers cuboid_dims (num cuboids x 3): cuboid...
dist_pt_to_cuboid
python
openai/multi-agent-emergence-environments
mae_envs/util/geometry.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/mae_envs/util/geometry.py
MIT
def add_weld_equality_constraint_transform(name, body_name1, body_name2): ''' Creates a weld constraint that maintains relative position and orientation between two objects ''' def fun(xml_dict): if 'equality' not in xml_dict: xml_dict['equality'] = OrderedDict() ...
Creates a weld constraint that maintains relative position and orientation between two objects
add_weld_equality_constraint_transform
python
openai/multi-agent-emergence-environments
mae_envs/util/transforms.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/mae_envs/util/transforms.py
MIT
def set_joint_damping_transform(damping, joint_name): ''' Set joints damping to a single value. Args: damping (float): damping to set joint_name (string): partial name of joint. Any joint with joint_name as a substring will be affected. ''' def closure(node): ...
Set joints damping to a single value. Args: damping (float): damping to set joint_name (string): partial name of joint. Any joint with joint_name as a substring will be affected.
set_joint_damping_transform
python
openai/multi-agent-emergence-environments
mae_envs/util/transforms.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/mae_envs/util/transforms.py
MIT
def remove_hinge_axis_transform(axis): ''' Removes specific hinge axis from the body. ''' def fun(xml_dict): def closure(node): if 'joint' in node: node["joint"] = [j for j in node["joint"] if j["@type"] != "hinge" ...
Removes specific hinge axis from the body.
remove_hinge_axis_transform
python
openai/multi-agent-emergence-environments
mae_envs/util/transforms.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/mae_envs/util/transforms.py
MIT
def in_cone2d(origin_pts, origin_angles, cone_angle, target_pts): ''' Computes whether 2D points target_pts are in the cones originating from origin_pts at angle origin_angles with cone spread angle cone_angle. Args: origin_pts (np.ndarray): array with shape (n_points, 2) of ...
Computes whether 2D points target_pts are in the cones originating from origin_pts at angle origin_angles with cone spread angle cone_angle. Args: origin_pts (np.ndarray): array with shape (n_points, 2) of origin points origin_angles (np.ndarray): array with shape (n...
in_cone2d
python
openai/multi-agent-emergence-environments
mae_envs/util/vision.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/mae_envs/util/vision.py
MIT
def insight(sim, geom1_id, geom2_id=None, pt2=None, dist_thresh=np.inf, check_body=True): ''' Check if geom2 or pt2 is in line of sight of geom1. Args: sim: Mujoco sim object geom1 (int): geom id geom2 (int): geom id pt2 (tuple): xy point d...
Check if geom2 or pt2 is in line of sight of geom1. Args: sim: Mujoco sim object geom1 (int): geom id geom2 (int): geom id pt2 (tuple): xy point dist_thresh (float): Adds a distance threshold for vision. Objects beyond the threshold ...
insight
python
openai/multi-agent-emergence-environments
mae_envs/util/vision.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/mae_envs/util/vision.py
MIT
def splitobs(obs, keepdims=True): ''' Split obs into list of single agent obs. Args: obs: dictionary of numpy arrays where first dim in each array is agent dim ''' n_agents = obs[list(obs.keys())[0]].shape[0] return [{k: v[[i]] if keepdims else v[i] for k, v in obs.items()} f...
Split obs into list of single agent obs. Args: obs: dictionary of numpy arrays where first dim in each array is agent dim
splitobs
python
openai/multi-agent-emergence-environments
mae_envs/viewer/policy_viewer.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/mae_envs/viewer/policy_viewer.py
MIT
def grab_obj(self, action): ''' Implements object grabbing for all agents Args: action: Action dictionary ''' action_pull = action['action_pull'][:, self.actual_body_slice] sim = self.unwrapped.sim agent_pos = sim.data.body_xpos[self.agent...
Implements object grabbing for all agents Args: action: Action dictionary
grab_obj
python
openai/multi-agent-emergence-environments
mae_envs/wrappers/manipulation.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/mae_envs/wrappers/manipulation.py
MIT
def lock_obj(self, action_lock): ''' Implements object gluing for all agents Args: lock: (n_agent, n_obj) boolean matrix ''' sim = self.unwrapped.sim action_lock = action_lock[self.agent_idx_allowed_to_lock] action_lock = action_lock[:, sel...
Implements object gluing for all agents Args: lock: (n_agent, n_obj) boolean matrix
lock_obj
python
openai/multi-agent-emergence-environments
mae_envs/wrappers/manipulation.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/mae_envs/wrappers/manipulation.py
MIT
def _process_self_matrix(self, self_matrix): ''' self_matrix will be a (n_agent, n_agent) boolean matrix. Permute each row such that the matrix is consistent with the circulant permutation used for self observations. E.g. this should be used for agent agent masks ''' ...
self_matrix will be a (n_agent, n_agent) boolean matrix. Permute each row such that the matrix is consistent with the circulant permutation used for self observations. E.g. this should be used for agent agent masks
_process_self_matrix
python
openai/multi-agent-emergence-environments
mae_envs/wrappers/multi_agent.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/mae_envs/wrappers/multi_agent.py
MIT
def construct_schemas_zero_state(spec, ob_space, scope=''): ''' Takes a network spec (as specified in construct_tf_graph docstring) and returns input schemas and zero states. ''' schemas = OrderedDict() zero_states = OrderedDict() for i, layer in enumerate(spec): layer = ...
Takes a network spec (as specified in construct_tf_graph docstring) and returns input schemas and zero states.
construct_schemas_zero_state
python
openai/multi-agent-emergence-environments
ma_policy/graph_construct.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/ma_policy/graph_construct.py
MIT
def entity_avg_pooling_masked(x, mask): ''' Masks and pools x along the second to last dimension. Arguments have dimensions: x: batch x time x n_entities x n_features mask: batch x time x n_entities ''' mask = tf.expand_dims(mask, -1) masked = x * mask summed = tf....
Masks and pools x along the second to last dimension. Arguments have dimensions: x: batch x time x n_entities x n_features mask: batch x time x n_entities
entity_avg_pooling_masked
python
openai/multi-agent-emergence-environments
ma_policy/layers.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/ma_policy/layers.py
MIT
def entity_concat(inps): ''' Concat 4D tensors along the third dimension. If a 3D tensor is in the list then treat it as a single entity and expand the third dimension Args: inps (list of tensors): tensors to concatenate ''' with tf.variable_scope('concat_entities'): ...
Concat 4D tensors along the third dimension. If a 3D tensor is in the list then treat it as a single entity and expand the third dimension Args: inps (list of tensors): tensors to concatenate
entity_concat
python
openai/multi-agent-emergence-environments
ma_policy/layers.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/ma_policy/layers.py
MIT
def concat_entity_masks(inps, masks): ''' Concats masks together. If mask is None, then it creates a tensor of 1's with shape (BS, T, NE). Args: inps (list of tensors): tensors that masks apply to masks (list of tensors): corresponding masks ''' assert len...
Concats masks together. If mask is None, then it creates a tensor of 1's with shape (BS, T, NE). Args: inps (list of tensors): tensors that masks apply to masks (list of tensors): corresponding masks
concat_entity_masks
python
openai/multi-agent-emergence-environments
ma_policy/layers.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/ma_policy/layers.py
MIT
def residual_sa_block(inp, mask, heads, n_embd, layer_norm=False, post_sa_layer_norm=False, n_mlp=1, qk_w=0.125, v_w=0.125, post_w=0.125, mlp_w1=0.125, mlp_w2=0.125, scope="residual_sa_block", reuse=False): ''' Residual ...
Residual self attention block for entities. Notation: T - Time NE - Number entities Args: inp (tf): (BS, T, NE, f) mask (tf): (BS, T, NE) heads (int) -- number of attention heads n_embd (int) -- dimension of queries, keys,...
residual_sa_block
python
openai/multi-agent-emergence-environments
ma_policy/layers.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/ma_policy/layers.py
MIT
def self_attention(inp, mask, heads, n_embd, layer_norm=False, qk_w=1.0, v_w=0.01, scope='', reuse=False): ''' Self attention over entities. Notation: T - Time NE - Number entities Args: inp (tf) -- tensor w/ shape (bs, T, NE, features)...
Self attention over entities. Notation: T - Time NE - Number entities Args: inp (tf) -- tensor w/ shape (bs, T, NE, features) mask (tf) -- binary tensor with shape (bs, T, NE). For each batch x time, nner matrix repres...
self_attention
python
openai/multi-agent-emergence-environments
ma_policy/layers.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/ma_policy/layers.py
MIT
def stable_masked_softmax(logits, mask): ''' Args: logits (tf): tensor with shape (bs, T, heads, NE, NE) mask (tf): tensor with shape(bs, T, 1, NE) ''' with tf.variable_scope('stable_softmax'): # Subtract a big number from the masked logits so they don't interfere wi...
Args: logits (tf): tensor with shape (bs, T, heads, NE, NE) mask (tf): tensor with shape(bs, T, 1, NE)
stable_masked_softmax
python
openai/multi-agent-emergence-environments
ma_policy/layers.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/ma_policy/layers.py
MIT
def qkv_embed(inp, heads, n_embd, layer_norm=False, qk_w=1.0, v_w=0.01, reuse=False): ''' Compute queries, keys, and values Args: inp (tf) -- tensor w/ shape (bs, T, NE, features) heads (int) -- number of attention heads n_embd (int) -- dimension of queries, keys,...
Compute queries, keys, and values Args: inp (tf) -- tensor w/ shape (bs, T, NE, features) heads (int) -- number of attention heads n_embd (int) -- dimension of queries, keys, and values will be n_embd / heads layer_norm (bool) -- normalize embedding prior...
qkv_embed
python
openai/multi-agent-emergence-environments
ma_policy/layers.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/ma_policy/layers.py
MIT
def layernorm(x, scope, epsilon=1e-5, reuse=False): ''' normalize state vector to be zero mean / unit variance + learned scale/shift ''' with tf.variable_scope(scope, reuse=reuse): n_state = x.get_shape()[-1] gain = tf.get_variable('gain', [n_state], initializer=tf.constant_initializ...
normalize state vector to be zero mean / unit variance + learned scale/shift
layernorm
python
openai/multi-agent-emergence-environments
ma_policy/layers.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/ma_policy/layers.py
MIT
def shape_list(x): ''' deal with dynamic shape in tensorflow cleanly ''' ps = x.get_shape().as_list() ts = tf.shape(x) return [ts[i] if ps[i] is None else ps[i] for i in range(len(ps))]
deal with dynamic shape in tensorflow cleanly
shape_list
python
openai/multi-agent-emergence-environments
ma_policy/load_policy.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/ma_policy/load_policy.py
MIT
def load_policy(path, env=None, scope='policy'): ''' Load a policy. Args: path (string): policy path env (Gym.Env): This will update the observation space of the policy that is returned scope (string): The base scope for the policy variables ''...
Load a policy. Args: path (string): policy path env (Gym.Env): This will update the observation space of the policy that is returned scope (string): The base scope for the policy variables
load_policy
python
openai/multi-agent-emergence-environments
ma_policy/load_policy.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/ma_policy/load_policy.py
MIT
def _init(self, inputs, gaussian_fixed_var=True, **kwargs): ''' Args: inputs (dict): input dictionary containing tf tensors gaussian_fixed_var (bool): If True the policies variance won't be conditioned on state ''' taken_actions = {k: inputs[k] for k i...
Args: inputs (dict): input dictionary containing tf tensors gaussian_fixed_var (bool): If True the policies variance won't be conditioned on state
_init
python
openai/multi-agent-emergence-environments
ma_policy/ma_policy.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/ma_policy/ma_policy.py
MIT
def process_observation_batch(self, obs): ''' Batch obs together. Args: obs -- list of lists (batch, time), where elements are dictionary observations ''' new_obs = deepcopy(obs) # List tranpose -- now in (time, batch) new_obs = list(map(l...
Batch obs together. Args: obs -- list of lists (batch, time), where elements are dictionary observations
process_observation_batch
python
openai/multi-agent-emergence-environments
ma_policy/ma_policy.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/ma_policy/ma_policy.py
MIT
def prepare_input(self, observation, state_in, taken_action=None): ''' Add in time dimension to observations, assumes that first dimension of observation is already the batch dimension and does not need to be added.''' obs = deepcopy(observation) obs.update(state_in) if taken...
Add in time dimension to observations, assumes that first dimension of observation is already the batch dimension and does not need to be added.
prepare_input
python
openai/multi-agent-emergence-environments
ma_policy/ma_policy.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/ma_policy/ma_policy.py
MIT
def listdict2dictnp(l, keepdims=False): ''' Convert a list of dicts of numpy arrays to a dict of numpy arrays. If keepdims is False the new outer dimension in each dict element will be the length of the list If keepdims is True, then the new outdimension in each dict will be the ...
Convert a list of dicts of numpy arrays to a dict of numpy arrays. If keepdims is False the new outer dimension in each dict element will be the length of the list If keepdims is True, then the new outdimension in each dict will be the sum of the outer dimensions of each...
listdict2dictnp
python
openai/multi-agent-emergence-environments
ma_policy/util.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/ma_policy/util.py
MIT
def l2_loss(pred, label, std, mask): ''' Masked L2 loss with a scaling paramter (std). We made the choice that the loss would scale with the number of unmasked data points rather than have the same magnitude regardless of how many samples came in. TODO: Revisit whether th...
Masked L2 loss with a scaling paramter (std). We made the choice that the loss would scale with the number of unmasked data points rather than have the same magnitude regardless of how many samples came in. TODO: Revisit whether this is the right choice.
l2_loss
python
openai/multi-agent-emergence-environments
ma_policy/util.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/ma_policy/util.py
MIT
def __init__(self, shape, dtype): """Creates a schema for a variable used in policy. Allows for symbolic definition of shape. Shape can consist of integers, as well as strings BATCH and TIMESTEPS. This is taken advantage of in the optimizers, to create placeholders or variables that asyn...
Creates a schema for a variable used in policy. Allows for symbolic definition of shape. Shape can consist of integers, as well as strings BATCH and TIMESTEPS. This is taken advantage of in the optimizers, to create placeholders or variables that asynchronously prefetch the inputs. Para...
__init__
python
openai/multi-agent-emergence-environments
ma_policy/variable_schema.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/ma_policy/variable_schema.py
MIT
def substitute(self, *, batch=BATCH, timesteps=TIMESTEPS): """Make a new VariableSchema with batch or timesteps optionally filled in.""" # Coerse None to default value. batch = batch or BATCH timesteps = timesteps or TIMESTEPS shape = self._substituted_shape(batch, timesteps) ...
Make a new VariableSchema with batch or timesteps optionally filled in.
substitute
python
openai/multi-agent-emergence-environments
ma_policy/variable_schema.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/ma_policy/variable_schema.py
MIT
def zero_action(ac_space): ''' Define default zero action for when an agent dies such that it stays in place and doesn't do anything. ''' ac = OrderedDict() for ac_key, s in ac_space.spaces.items(): assert isinstance(s, gym.spaces.Tuple), f"space {s} is not a Tuple" single_agent_...
Define default zero action for when an agent dies such that it stays in place and doesn't do anything.
zero_action
python
openai/multi-agent-emergence-environments
randomized_uncertain_social_preferences/rusp/env_oasis.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/randomized_uncertain_social_preferences/rusp/env_oasis.py
MIT
def get_all_integer_partitions(n, min_team_size=1, max_team_size=np.inf): ''' Return a list of all integer partitions of n. Args: n (int): number of entities. min_team_size (int): minimum number of entities in a partition max_team_size (int): maximum number of ent...
Return a list of all integer partitions of n. Args: n (int): number of entities. min_team_size (int): minimum number of entities in a partition max_team_size (int): maximum number of entities in a partition
get_all_integer_partitions
python
openai/multi-agent-emergence-environments
randomized_uncertain_social_preferences/rusp/wrappers_rusp.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/randomized_uncertain_social_preferences/rusp/wrappers_rusp.py
MIT
def _partition_agents(self, n_agents, min_team_size, max_team_size): ''' Return a random partition from the set of all integer partitions ''' settings = (n_agents, min_team_size, max_team_size) if settings not in self.cached_partitions: self.cached_partitions[sett...
Return a random partition from the set of all integer partitions
_partition_agents
python
openai/multi-agent-emergence-environments
randomized_uncertain_social_preferences/rusp/wrappers_rusp.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/randomized_uncertain_social_preferences/rusp/wrappers_rusp.py
MIT
def _generate_social_preferences(self, n_agents): ''' Generate the relationship graph (without uncertainty) ''' # Generate random partitions if self.max_team_size != self.min_team_size: random_partitions = self._partition_agents(n_agents, self.min_team_size, self....
Generate the relationship graph (without uncertainty)
_generate_social_preferences
python
openai/multi-agent-emergence-environments
randomized_uncertain_social_preferences/rusp/wrappers_rusp.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/randomized_uncertain_social_preferences/rusp/wrappers_rusp.py
MIT
def _generate_uncertainty(self, n_agents): ''' Generate uncertainty levels and noise to be applied to the matrices ''' self.noise_std = np.random.uniform(low=self.obs_noise_std_range[0], high=self.obs_noise_std_range[1], ...
Generate uncertainty levels and noise to be applied to the matrices
_generate_uncertainty
python
openai/multi-agent-emergence-environments
randomized_uncertain_social_preferences/rusp/wrappers_rusp.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/randomized_uncertain_social_preferences/rusp/wrappers_rusp.py
MIT
def _precompute_observations(self, n_agents): ''' Precompute observations since they are static per episode. ''' # We have independent noisy observations per agents, so we copy the reward matrix n_agents times and # then add the noise matrices rew_mats = np.repeat(n...
Precompute observations since they are static per episode.
_precompute_observations
python
openai/multi-agent-emergence-environments
randomized_uncertain_social_preferences/rusp/wrappers_rusp.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/randomized_uncertain_social_preferences/rusp/wrappers_rusp.py
MIT
def _index_into_mats(key, *indices): ''' Helper function to create 3 observation types with the same indices ''' self.precomputed_obs[key] = rew_mats[indices] # Non-noisy version of the reward matrix self.precomputed_obs[key + "_noisy"] = noisy_rew_mats[i...
Helper function to create 3 observation types with the same indices
_index_into_mats
python
openai/multi-agent-emergence-environments
randomized_uncertain_social_preferences/rusp/wrappers_rusp.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/randomized_uncertain_social_preferences/rusp/wrappers_rusp.py
MIT
def _transpose_existing(new_key, existing_key): ''' Helper function to transpose all 3 observations for an key. This is useful if an agent policy or value function needs to observe what other agents observe about it. ''' self.precomputed_obs[new_ke...
Helper function to transpose all 3 observations for an key. This is useful if an agent policy or value function needs to observe what other agents observe about it.
_transpose_existing
python
openai/multi-agent-emergence-environments
randomized_uncertain_social_preferences/rusp/wrappers_rusp.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/randomized_uncertain_social_preferences/rusp/wrappers_rusp.py
MIT
def add_rew_share_observation_keys(*, keys_self: List[str], keys_additional_self_vf: List[str], keys_other_agents: List[str], keys_additional_other_agents_vf: List[str], keys_self_...
Determines how keys about the relationship graph should be observed. Args: keys_self: keys that the agent should observe about itself keys_additional_self_vf: keys about an agent but only that the value function should observe keys_other_agents: keys about other agen...
add_rew_share_observation_keys
python
openai/multi-agent-emergence-environments
randomized_uncertain_social_preferences/rusp/wrappers_rusp.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/randomized_uncertain_social_preferences/rusp/wrappers_rusp.py
MIT
def _get_target_actor(self, actor, action): ''' Return the true index of the targeted agent. Indicies given by the action will be in a rotated space defined based on how entities are presented to the policy, so we must map back to the underlying ordering. If the index is...
Return the true index of the targeted agent. Indicies given by the action will be in a rotated space defined based on how entities are presented to the policy, so we must map back to the underlying ordering. If the index is -1, this means no other agent was chosen.
_get_target_actor
python
openai/multi-agent-emergence-environments
randomized_uncertain_social_preferences/rusp/wrappers_util.py
https://github.com/openai/multi-agent-emergence-environments/blob/master/randomized_uncertain_social_preferences/rusp/wrappers_util.py
MIT
def dropout_condition_(sample: ConditionAttributes, condition_type: str, condition: str) -> None: """Utility function for nullifying an attribute inside a ConditionAttributes object. Works in-place. """ valid_conditions = ConditionAttributes.condition_types() if condition_type not in valid_condition...
Utility function for nullifying an attribute inside a ConditionAttributes object. Works in-place.
dropout_condition_
python
kyutai-labs/moshi
moshi/moshi/conditioners/base.py
https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/conditioners/base.py
Apache-2.0
def dropout_all_conditions(attributes: tp.Sequence[ConditionAttributes]) -> list[ConditionAttributes]: """ Args: attributes (list[ConditionAttributes]): All conditions attributes. Returns: list[ConditionAttributes]: Same with all conditions dropped. """ attributes = [attribute.copy()...
Args: attributes (list[ConditionAttributes]): All conditions attributes. Returns: list[ConditionAttributes]: Same with all conditions dropped.
dropout_all_conditions
python
kyutai-labs/moshi
moshi/moshi/conditioners/base.py
https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/conditioners/base.py
Apache-2.0
def _collate_text(self, samples: tp.Sequence[ConditionAttributes]) -> tp.Dict[str, tp.List[tp.Optional[str]]]: """Given a list of ConditionAttributes objects, compile a dictionary where the keys are the attributes and the values are the aggregated input per attribute. For example: Input:...
Given a list of ConditionAttributes objects, compile a dictionary where the keys are the attributes and the values are the aggregated input per attribute. For example: Input: [ ConditionAttributes(text={"genre": "Rock", "description": "A rock song with a guitar solo"}, wav=.....
_collate_text
python
kyutai-labs/moshi
moshi/moshi/conditioners/base.py
https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/conditioners/base.py
Apache-2.0
def _collate_tensors(self, samples: tp.Sequence[ConditionAttributes]) -> tp.Dict[str, TensorCondition]: """For each tensor attribute, collate the tensor from individual batch items. Args: samples (list of ConditionAttributes): List of ConditionAttributes samples. Returns: ...
For each tensor attribute, collate the tensor from individual batch items. Args: samples (list of ConditionAttributes): List of ConditionAttributes samples. Returns: dict[str, TensorCondition]: A dictionary mapping an attribute name to tensor.
_collate_tensors
python
kyutai-labs/moshi
moshi/moshi/conditioners/base.py
https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/conditioners/base.py
Apache-2.0
def prepare(self, inputs: tp.Sequence[ConditionAttributes]) -> tp.Dict[str, tp.Any]: """Match attributes/tensors with existing conditioners in self, and call `prepare` for each one. This should be called before starting any real GPU work to avoid synchronization points. This will return a dict m...
Match attributes/tensors with existing conditioners in self, and call `prepare` for each one. This should be called before starting any real GPU work to avoid synchronization points. This will return a dict matching conditioner names to their arbitrary prepared representations. Args: ...
prepare
python
kyutai-labs/moshi
moshi/moshi/conditioners/base.py
https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/conditioners/base.py
Apache-2.0
def forward(self, prepared: tp.Dict[str, tp.Any]) -> tp.Dict[str, ConditionType]: """Compute pairs of `(embedding, mask)` using the configured conditioners and the prepared representations. The output is for example: { "genre": (torch.Tensor([B, 1, D_genre]), torch.Tensor([B, 1])), ...
Compute pairs of `(embedding, mask)` using the configured conditioners and the prepared representations. The output is for example: { "genre": (torch.Tensor([B, 1, D_genre]), torch.Tensor([B, 1])), "description": (torch.Tensor([B, T_desc, D_desc]), torch.Tensor([B, T_desc])), ...
forward
python
kyutai-labs/moshi
moshi/moshi/conditioners/base.py
https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/conditioners/base.py
Apache-2.0
def get_cross(self, conditions: ConditionTensors) -> torch.Tensor | None: """Return the tensor to be provided for the cross attention.""" cross = None for name in self.fuse2cond['cross']: cond, _ = conditions[name] if cross is None: cross = cond ...
Return the tensor to be provided for the cross attention.
get_cross
python
kyutai-labs/moshi
moshi/moshi/conditioners/base.py
https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/conditioners/base.py
Apache-2.0
def get_sum(self, conditions: ConditionTensors) -> torch.Tensor | None: """Return the tensor to be provided as an extra sum offset shared for each step.""" sum = None for name in self.fuse2cond['sum']: cond, _ = conditions[name] assert cond.shape[1] == 1, cond.shape ...
Return the tensor to be provided as an extra sum offset shared for each step.
get_sum
python
kyutai-labs/moshi
moshi/moshi/conditioners/base.py
https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/conditioners/base.py
Apache-2.0
def get_prepend(self, conditions: ConditionTensors) -> torch.Tensor | None: """Return the tensor to be prepended to the transformer.""" prepend = None for name in self.fuse2cond['prepend']: cond, _ = conditions[name] if prepend is None: prepend = cond ...
Return the tensor to be prepended to the transformer.
get_prepend
python
kyutai-labs/moshi
moshi/moshi/conditioners/base.py
https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/conditioners/base.py
Apache-2.0
def length_to_mask(lengths: torch.Tensor, max_len: tp.Optional[int] = None) -> torch.Tensor: """Utility function to convert a tensor of sequence lengths to a mask (useful when working on padded sequences). For example: [3, 5] => [[1, 1, 1, 0, 0], [1, 1, 1, 1, 1]] Args: lengths (torch.Tensor): tenso...
Utility function to convert a tensor of sequence lengths to a mask (useful when working on padded sequences). For example: [3, 5] => [[1, 1, 1, 0, 0], [1, 1, 1, 1, 1]] Args: lengths (torch.Tensor): tensor with lengths max_len (int): can set the max length manually. Defaults to None. Returns...
length_to_mask
python
kyutai-labs/moshi
moshi/moshi/conditioners/text.py
https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/conditioners/text.py
Apache-2.0
def hash_trick(word: str, vocab_size: int) -> int: """Hash trick to pair each word with an index Args: word (str): word we wish to convert to an index vocab_size (int): size of the vocabulary Returns: int: index of the word in the embedding LUT """ hash = int(hashlib.sha256(...
Hash trick to pair each word with an index Args: word (str): word we wish to convert to an index vocab_size (int): size of the vocabulary Returns: int: index of the word in the embedding LUT
hash_trick
python
kyutai-labs/moshi
moshi/moshi/conditioners/text.py
https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/conditioners/text.py
Apache-2.0
def _encode_to_unquantized_latent(self, x: torch.Tensor) -> torch.Tensor: """Projects a batch of waveforms to unquantized latent space. Args: x (torch.Tensor): Float tensor of shape [B, C, T]. Returns: Unquantized embeddings. """ assert ( x.d...
Projects a batch of waveforms to unquantized latent space. Args: x (torch.Tensor): Float tensor of shape [B, C, T]. Returns: Unquantized embeddings.
_encode_to_unquantized_latent
python
kyutai-labs/moshi
moshi/moshi/models/compression.py
https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/models/compression.py
Apache-2.0
def encode(self, x: torch.Tensor) -> torch.Tensor: """Encode the given input tensor to quantized representation. Args: x (torch.Tensor): Float tensor of shape [B, C, T] Returns: codes (torch.Tensor): an int tensor of shape [B, K, T] with K the number of ...
Encode the given input tensor to quantized representation. Args: x (torch.Tensor): Float tensor of shape [B, C, T] Returns: codes (torch.Tensor): an int tensor of shape [B, K, T] with K the number of codebooks used and T the timestep.
encode
python
kyutai-labs/moshi
moshi/moshi/models/compression.py
https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/models/compression.py
Apache-2.0
def encode_to_latent(self, x: torch.Tensor, quantize: bool = True) -> torch.Tensor: """Projects a batch of waveforms to latent space. Args: x (torch.Tensor): Float tensor of shape [B, C, T]. Returns: Embeddings, either quantized or not. """ emb = self._e...
Projects a batch of waveforms to latent space. Args: x (torch.Tensor): Float tensor of shape [B, C, T]. Returns: Embeddings, either quantized or not.
encode_to_latent
python
kyutai-labs/moshi
moshi/moshi/models/compression.py
https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/models/compression.py
Apache-2.0
def decode(self, codes: torch.Tensor): """Decode the given codes to a reconstructed representation. Args: codes (torch.Tensor): Int tensor of shape [B, K, T] Returns: out (torch.Tensor): Float tensor of shape [B, C, T], the reconstructed audio. """ state...
Decode the given codes to a reconstructed representation. Args: codes (torch.Tensor): Int tensor of shape [B, K, T] Returns: out (torch.Tensor): Float tensor of shape [B, C, T], the reconstructed audio.
decode
python
kyutai-labs/moshi
moshi/moshi/models/compression.py
https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/models/compression.py
Apache-2.0
def scatter_with_mask_(tensor: torch.Tensor, dim: int, index: torch.Tensor, value: torch.Tensor, mask: torch.Tensor) -> None: """Scatter but skipping the updates that are masked.""" old_value = tensor.gather(dim, index) value = torch.where(mask, value, old_value) tensor.scatter_(d...
Scatter but skipping the updates that are masked.
scatter_with_mask_
python
kyutai-labs/moshi
moshi/moshi/models/lm.py
https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/models/lm.py
Apache-2.0
def forward( self, codes: torch.Tensor, condition_tensors: tp.Optional[ConditionTensors] = None) -> LMOutput: """Given an input tensor of codes [B, K, T] and list of conditions, returns the logits along with masks indicating the valid positions at which to compute the loss. ...
Given an input tensor of codes [B, K, T] and list of conditions, returns the logits along with masks indicating the valid positions at which to compute the loss. The logits time steps are aligned with those in the input `code`. Should only be used for training, not inference (use `LMGen` for tha...
forward
python
kyutai-labs/moshi
moshi/moshi/models/lm.py
https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/models/lm.py
Apache-2.0
def _init_weights(self): """Initialization of the transformer module weights. Mostly truncated gaussian, with `std = 1 / sqrt(dim_in)`. Embeddings are also initialized with `1 / sqrt(dim)` rather than `1`. Some layers are not going to be properly initialized: - in_proj in MHA...
Initialization of the transformer module weights. Mostly truncated gaussian, with `std = 1 / sqrt(dim_in)`. Embeddings are also initialized with `1 / sqrt(dim)` rather than `1`. Some layers are not going to be properly initialized: - in_proj in MHA. - depth transformer la...
_init_weights
python
kyutai-labs/moshi
moshi/moshi/models/lm.py
https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/models/lm.py
Apache-2.0
def from_hf_repo( hf_repo: str, moshi_weights: Path | str | None = None, mimi_weights: Path | str | None = None, tokenizer: Path | str | None = None, config_path: Path | str | None = None, lora_weights: Path | str | None = None, ) -> "CheckpointInfo": """Downl...
Downloads the checkpoints from the given repo, along with its config. Extra overrides are possible for each of Moshi, Mimi, or the text tokenizer, which should be either a Path to a local file or a string representing a path to a local file or starting with `hf://` for pointing to a file in ano...
from_hf_repo
python
kyutai-labs/moshi
moshi/moshi/models/loaders.py
https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/models/loaders.py
Apache-2.0
def get_mimi( filename: str | Path | None, device: torch.device | str = "cpu", num_codebooks: int = 8 ) -> MimiModel: """Return a pretrained Mimi model, or unintialized if `filename` is None.""" encoder = SEANetEncoder(**_seanet_kwargs) decoder = SEANetDecoder(**_seanet_kwargs) encoder_transformer =...
Return a pretrained Mimi model, or unintialized if `filename` is None.
get_mimi
python
kyutai-labs/moshi
moshi/moshi/models/loaders.py
https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/models/loaders.py
Apache-2.0
def test_conv1d(batch_size, in_channels, out_channels, seq_len, kernel_size): """Test that StreamingConv1d() calls are causal. Having new inputs does not change the previous output.""" assert seq_len > kernel_size layer = StreamingConv1d(in_channels, out_channels, kernel_size, causal=True, norm="none", pad...
Test that StreamingConv1d() calls are causal. Having new inputs does not change the previous output.
test_conv1d
python
kyutai-labs/moshi
moshi/moshi/modules/conv_test.py
https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/modules/conv_test.py
Apache-2.0
def test_conv1d_streaming(batch_size, in_channels, out_channels, seq_len, kernel_size): """Test that StreamingConv1d() streaming works as expected.""" assert seq_len > kernel_size layer = StreamingConv1d(in_channels, out_channels, kernel_size, causal=True, norm="none", pad_mode="constant") generator =...
Test that StreamingConv1d() streaming works as expected.
test_conv1d_streaming
python
kyutai-labs/moshi
moshi/moshi/modules/conv_test.py
https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/modules/conv_test.py
Apache-2.0
def test_conv1d_transpose(batch_size, in_channels, out_channels, seq_len, kernel_size, stride): """Test that StreamingConvTranspose1d() calls are causal. Having new inputs does not change the previous output.""" assert seq_len > kernel_size layer = StreamingConvTranspose1d(in_channels, out_channels, kernel...
Test that StreamingConvTranspose1d() calls are causal. Having new inputs does not change the previous output.
test_conv1d_transpose
python
kyutai-labs/moshi
moshi/moshi/modules/conv_test.py
https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/modules/conv_test.py
Apache-2.0
def test_conv1d_transpose_streaming(batch_size, in_channels, out_channels, seq_len, kernel_size, stride): """Test that StreamingConvTranspose1d() streaming works as expected.""" assert seq_len > kernel_size layer = StreamingConvTranspose1d(in_channels, out_channels, kernel_size, stride, causal=True, norm="...
Test that StreamingConvTranspose1d() streaming works as expected.
test_conv1d_transpose_streaming
python
kyutai-labs/moshi
moshi/moshi/modules/conv_test.py
https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/modules/conv_test.py
Apache-2.0
def replace_all_linear_with_lora(module, rank: int, scaling: float, device=None, dtype=None): """ Recursively replace all Linear layers with LoRALinear layers.""" for name, child in module.named_children(): if isinstance(child, nn.Linear): if device is None: this_device = chi...
Recursively replace all Linear layers with LoRALinear layers.
replace_all_linear_with_lora
python
kyutai-labs/moshi
moshi/moshi/modules/lora.py
https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/modules/lora.py
Apache-2.0
def replace_lora_with_linear(module): """Recursively replace all LoRALinear layers with Linear layers.""" for name, child in module.named_children(): if isinstance(child, LoRALinear): # Compute merged weights: W' = W + scaling * B @ A merged_weight = child.frozen_W.weight.data + ...
Recursively replace all LoRALinear layers with Linear layers.
replace_lora_with_linear
python
kyutai-labs/moshi
moshi/moshi/modules/lora.py
https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/modules/lora.py
Apache-2.0
def apply_rope( q: torch.Tensor, k: torch.Tensor, offset: torch.Tensor, max_period: float = 10_000, time_before_heads: bool = False, ): """ Args: q (torch.Tensor): queries, shape `[B, T, H, D]`. k (torch.Tensor): keys, shape `[B, T, H, D]`. offset (int): current offse...
Args: q (torch.Tensor): queries, shape `[B, T, H, D]`. k (torch.Tensor): keys, shape `[B, T, H, D]`. offset (int): current offset, e.g. when streaming. max_period (float): maximum period for the cos and sin. time_before_heads (bool): if True, expected [B, T, H, D], else [B,...
apply_rope
python
kyutai-labs/moshi
moshi/moshi/modules/rope.py
https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/modules/rope.py
Apache-2.0
def forward( self, q: torch.Tensor, k: torch.Tensor, offset: torch.Tensor, time_before_heads: bool = False, ): """Apply rope rotation to query or key tensor.""" return apply_rope(q, k, offset, self.max_period, time_before_heads)
Apply rope rotation to query or key tensor.
forward
python
kyutai-labs/moshi
moshi/moshi/modules/rope.py
https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/modules/rope.py
Apache-2.0
def test_resnet(batch_size, dim, res_layer_index, seq_len, kernel_size): """Test that SEANetResnetBlock() calls are causal. Having new inputs does not change the previous output.""" assert seq_len > kernel_size dilation_base = 2 layer = SEANetResnetBlock(dim=dim, dilations=[dilation_base**res_layer_ind...
Test that SEANetResnetBlock() calls are causal. Having new inputs does not change the previous output.
test_resnet
python
kyutai-labs/moshi
moshi/moshi/modules/seanet_test.py
https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/modules/seanet_test.py
Apache-2.0
def test_resnet_streaming(batch_size, dim, res_layer_index, seq_len, kernel_size): """Test that SEANetResnetBlock() streaming works as expected.""" assert seq_len > kernel_size dilation_base = 2 layer = SEANetResnetBlock(dim=dim, dilations=[dilation_base**res_layer_index, 1], pad_mode="constant", causa...
Test that SEANetResnetBlock() streaming works as expected.
test_resnet_streaming
python
kyutai-labs/moshi
moshi/moshi/modules/seanet_test.py
https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/modules/seanet_test.py
Apache-2.0
def test_nonstreaming_causal_decode(num_timesteps, seanet_kwargs): """Test that the SEANetDecoder does not depend on future inputs.""" device = 'cuda' if torch.cuda.is_available() else 'cpu' decoder = SEANetDecoder(**seanet_kwargs).to(device=device) generator = torch.Generator(device=device) gener...
Test that the SEANetDecoder does not depend on future inputs.
test_nonstreaming_causal_decode
python
kyutai-labs/moshi
moshi/moshi/modules/seanet_test.py
https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/modules/seanet_test.py
Apache-2.0
def streaming(self, batch_size: int) -> ExitStack: """Context manager to enter streaming mode. Reset streaming state on exit.""" exit_stack = ExitStack() self._start_streaming(batch_size, exit_stack) exit_stack.callback(self._stop_streaming) return exit_stack
Context manager to enter streaming mode. Reset streaming state on exit.
streaming
python
kyutai-labs/moshi
moshi/moshi/modules/streaming.py
https://github.com/kyutai-labs/moshi/blob/master/moshi/moshi/modules/streaming.py
Apache-2.0