text
stringlengths
81
112k
Gets current model step. :return: current model step. def get_current_step(self): """ Gets current model step. :return: current model step. """ step = self.sess.run(self.model.global_step) return step
Saves the model :param steps: The number of steps the model was trained for :return: def save_model(self, steps): """ Saves the model :param steps: The number of steps the model was trained for :return: """ with self.graph.as_default(): last_c...
Exports latest saved model to .nn format for Unity embedding. def export_model(self): """ Exports latest saved model to .nn format for Unity embedding. """ with self.graph.as_default(): target_nodes = ','.join(self._process_graph()) ckpt = tf.train.get_checkpoin...
Gets the list of the output nodes present in the graph for inference :return: list of node names def _process_graph(self): """ Gets the list of the output nodes present in the graph for inference :return: list of node names """ all_nodes = [x.name for x in self.graph.as_...
Resets all the local local_buffers def reset_local_buffers(self): """ Resets all the local local_buffers """ agent_ids = list(self.keys()) for k in agent_ids: self[k].reset_agent()
Appends the buffer of an agent to the update buffer. :param agent_id: The id of the agent which data will be appended :param key_list: The fields that must be added. If None: all fields will be appended. :param batch_size: The number of elements that must be appended. If None: All of them will b...
Appends the buffer of all agents to the update buffer. :param key_list: The fields that must be added. If None: all fields will be appended. :param batch_size: The number of elements that must be appended. If None: All of them will be. :param training_length: The length of the samples that must ...
Launches training session. :param process_queue: Queue used to send signal back to main. :param sub_id: Unique id for training session. :param run_seed: Random seed used for training. :param run_options: Command line arguments for training. def run_training(sub_id: int, run_seed: int, run_options, proc...
Get an action using this trainer's current policy. :param curr_info: Current BrainInfo. :return: The ActionInfo given by the policy given the BrainInfo. def get_action(self, curr_info: BrainInfo) -> ActionInfo: """ Get an action using this trainer's current policy. :param curr_i...
Saves training statistics to Tensorboard. :param delta_train_start: Time elapsed since training started. :param lesson_num: Current lesson number in curriculum. :param global_step: The number of steps the simulation has been going for def write_summary(self, global_step, delta_train_start, les...
Saves text to Tensorboard. Note: Only works on tensorflow r1.2 or above. :param key: The name of the text. :param input_dict: A dictionary that will be displayed in a table on Tensorboard. def write_tensorboard_text(self, key, input_dict): """ Saves text to Tensorboard. ...
A dict from brain name to the brain's curriculum's lesson number. def lesson_nums(self): """A dict from brain name to the brain's curriculum's lesson number.""" lesson_nums = {} for brain_name, curriculum in self.brains_to_curriculums.items(): lesson_nums[brain_name] = curriculum.le...
Attempts to increments all the lessons of all the curriculums in this MetaCurriculum. Note that calling this method does not guarantee the lesson of a curriculum will increment. The lesson of a curriculum will only increment if the specified measure threshold defined in the curriculum ha...
Sets all the curriculums in this meta curriculum to a specified lesson number. Args: lesson_num (int): The lesson number which all the curriculums will be set to. def set_all_curriculums_to_lesson_num(self, lesson_num): """Sets all the curriculums in this meta curri...
Get the combined configuration of all curriculums in this MetaCurriculum. Returns: A dict from parameter to value. def get_config(self): """Get the combined configuration of all curriculums in this MetaCurriculum. Returns: A dict from parameter to value...
Sends a signal to reset the unity environment. :return: AllBrainInfo : A data structure corresponding to the initial reset state of the environment. def reset(self, config=None, train_mode=True, custom_reset_parameters=None) -> AllBrainInfo: """ Sends a signal to reset the unity environment. ...
Provides the environment with an action, moves the environment dynamics forward accordingly, and returns observation, state, and reward information to the agent. :param value: Value estimates provided by agents. :param vector_action: Agent's vector action. Can be a scalar or vector of int/floats...
Converts arrays to list. :param arr: numpy vector. :return: flattened list. def _flatten(cls, arr) -> List[float]: """ Converts arrays to list. :param arr: numpy vector. :return: flattened list. """ if isinstance(arr, cls.SCALAR_ACTION_TYPES): ...
Collects experience information from all external brains in environment at current step. :return: a dictionary of BrainInfo objects. def _get_state(self, output: UnityRLOutput) -> (AllBrainInfo, bool): """ Collects experience information from all external brains in environment at current step. ...
Inform Metrics class that experience collection is done. def end_experience_collection_timer(self): """ Inform Metrics class that experience collection is done. """ if self.time_start_experience_collection: curr_delta = time() - self.time_start_experience_collection ...
Inform Metrics class about time to step in environment. def add_delta_step(self, delta: float): """ Inform Metrics class about time to step in environment. """ if self.delta_last_experience_collection: self.delta_last_experience_collection += delta else: ...
Inform Metrics class that policy update has started. :int number_experiences: Number of experiences in Buffer at this point. :float mean_return: Return averaged across all cumulative returns since last policy update def start_policy_update_timer(self, number_experiences: int, mean_return: float): ...
Inform Metrics class that policy update has started. def end_policy_update(self): """ Inform Metrics class that policy update has started. """ if self.time_policy_update_start: self.delta_policy_update = time() - self.time_policy_update_start else: self.d...
Write Training Metrics to CSV def write_training_metrics(self): """ Write Training Metrics to CSV """ with open(self.path, 'w') as file: writer = csv.writer(file) writer.writerow(FIELD_NAMES) for row in self.rows: writer.writerow(row)
Creates TF ops to track and increment recent average cumulative reward. def create_reward_encoder(): """Creates TF ops to track and increment recent average cumulative reward.""" last_reward = tf.Variable(0, name="last_reward", trainable=False, dtype=tf.float32) new_reward = tf.placeholder(shap...
Creates state encoders for current and future observations. Used for implementation of Curiosity-driven Exploration by Self-supervised Prediction See https://arxiv.org/abs/1705.05363 for more details. :return: current and future state encoder tensors. def create_curiosity_encoders(self): ...
Creates inverse model TensorFlow ops for Curiosity module. Predicts action taken given current and future encoded states. :param encoded_state: Tensor corresponding to encoded current state. :param encoded_next_state: Tensor corresponding to encoded next state. def create_inverse_model(self, en...
Creates forward model TensorFlow ops for Curiosity module. Predicts encoded future state based on encoded current state and given action. :param encoded_state: Tensor corresponding to encoded current state. :param encoded_next_state: Tensor corresponding to encoded next state. def create_forwar...
Creates training-specific Tensorflow ops for PPO models. :param probs: Current policy probabilities :param old_probs: Past policy probabilities :param value: Current value estimate :param beta: Entropy regularization strength :param entropy: Current policy entropy :param ...
Evaluates policy for the agent experiences provided. :param brain_info: BrainInfo object containing inputs. :return: Outputs from network as defined by self.inference_dict. def evaluate(self, brain_info): """ Evaluates policy for the agent experiences provided. :param brain_info...
Updates model using buffer. :param num_sequences: Number of trajectories in batch. :param mini_batch: Experience batch. :return: Output from update process. def update(self, mini_batch, num_sequences): """ Updates model using buffer. :param num_sequences: Number of traje...
Generates intrinsic reward used for Curiosity-based training. :BrainInfo curr_info: Current BrainInfo. :BrainInfo next_info: Next BrainInfo. :return: Intrinsic rewards for all agents. def get_intrinsic_rewards(self, curr_info, next_info): """ Generates intrinsic reward used for ...
Generates value estimates for bootstrapping. :param brain_info: BrainInfo to be used for bootstrapping. :param idx: Index in BrainInfo of agent. :return: Value estimate. def get_value_estimate(self, brain_info, idx): """ Generates value estimates for bootstrapping. :para...
Updates reward value for policy. :param new_reward: New reward to save. def update_reward(self, new_reward): """ Updates reward value for policy. :param new_reward: New reward to save. """ self.sess.run(self.model.update_reward, feed_dict={self.mode...
Adds experiences to each agent's experience history. :param curr_info: Current AllBrainInfo (Dictionary of all current brains and corresponding BrainInfo). :param next_info: Next AllBrainInfo (Dictionary of all current brains and corresponding BrainInfo). :param take_action_outputs: The outputs ...
Checks agent histories for processing condition, and processes them as necessary. Processing involves calculating value and advantage targets for model updating step. :param current_info: Current AllBrainInfo :param next_info: Next AllBrainInfo def process_experiences(self, current_info: AllBra...
A signal that the Episode has ended. The buffer must be reset. Get only called when the academy resets. def end_episode(self): """ A signal that the Episode has ended. The buffer must be reset. Get only called when the academy resets. """ self.evaluation_buffer.reset_loc...
Updates the policy. def update_policy(self): """ Updates the policy. """ self.demonstration_buffer.update_buffer.shuffle() batch_losses = [] num_batches = min(len(self.demonstration_buffer.update_buffer['actions']) // self.n_sequences, self.batc...
Creates TF ops to track and increment global training step. def create_global_steps(): """Creates TF ops to track and increment global training step.""" global_step = tf.Variable(0, name="global_step", trainable=False, dtype=tf.int32) increment_step = tf.assign(global_step, tf.add(global_step, ...
Creates image input op. :param camera_parameters: Parameters for visual observation from BrainInfo. :param name: Desired name of input op. :return: input op. def create_visual_input(camera_parameters, name): """ Creates image input op. :param camera_parameters: Parameter...
Creates ops for vector observation input. :param name: Name of the placeholder op. :param vec_obs_size: Size of stacked vector observation. :return: def create_vector_input(self, name='vector_observation'): """ Creates ops for vector observation input. :param name: Name ...
Builds a set of hidden state encoders. :param reuse: Whether to re-use the weights within the same scope. :param scope: Graph scope for the encoder ops. :param observation_input: Input vector. :param h_size: Hidden layer size. :param activation: What type of activation function t...
Builds a set of visual (CNN) encoders. :param reuse: Whether to re-use the weights within the same scope. :param scope: The scope of the graph within which to create the ops. :param image_input: The placeholder for the image input to use. :param h_size: Hidden layer size. :param ...
Creates a masking layer for the discrete actions :param all_logits: The concatenated unnormalized action probabilities for all branches :param action_masks: The mask for the logits. Must be of dimension [None x total_number_of_action] :param action_size: A list containing the number of possible ...
Creates encoding stream for observations. :param num_streams: Number of streams to create. :param h_size: Size of hidden linear layers in stream. :param num_layers: Number of hidden linear layers in stream. :return: List of encoded streams. def create_observation_streams(self, num_strea...
Builds a recurrent encoder for either state or observations (LSTM). :param sequence_length: Length of sequence to unroll. :param input_state: The input tensor to the LSTM cell. :param memory_in: The input memory to the LSTM cell. :param name: The scope of the LSTM cell. def create_recur...
Creates Continuous control actor-critic model. :param h_size: Size of hidden linear layers. :param num_layers: Number of hidden linear layers. def create_cc_actor_critic(self, h_size, num_layers): """ Creates Continuous control actor-critic model. :param h_size: Size of hidden l...
Creates Discrete control actor-critic model. :param h_size: Size of hidden linear layers. :param num_layers: Number of hidden linear layers. def create_dc_actor_critic(self, h_size, num_layers): """ Creates Discrete control actor-critic model. :param h_size: Size of hidden linea...
Adds experiences to each agent's experience history. :param curr_info: Current AllBrainInfo (Dictionary of all current brains and corresponding BrainInfo). :param next_info: Next AllBrainInfo (Dictionary of all current brains and corresponding BrainInfo). :param take_action_outputs: The outputs ...
Checks agent histories for processing condition, and processes them as necessary. Processing involves calculating value and advantage targets for model updating step. :param current_info: Current AllBrainInfo :param next_info: Next AllBrainInfo def process_experiences(self, current_info: AllBra...
Yield items from any nested iterable; see REF. def flatten(items,enter=lambda x:isinstance(x, list)): # http://stackoverflow.com/a/40857703 # https://github.com/ctmakro/canton/blob/master/canton/misc.py """Yield items from any nested iterable; see REF.""" for x in items: if enter(x): ...
A value in replace_with_strings can be either single string or list of strings def replace_strings_in_list(array_of_strigs, replace_with_strings): "A value in replace_with_strings can be either single string or list of strings" potentially_nested_list = [replace_with_strings.get(s) or s for s in array_of_strig...
Preserves the order of elements in the list def remove_duplicates_from_list(array): "Preserves the order of elements in the list" output = [] unique = set() for a in array: if a not in unique: unique.add(a) output.append(a) return output
Convert from NHWC|NCHW => HW def pool_to_HW(shape, data_frmt): """ Convert from NHWC|NCHW => HW """ if len(shape) != 4: return shape # Not NHWC|NCHW, return as is if data_frmt == 'NCHW': return [shape[2], shape[3]] return [shape[1], shape[2]]
Converts a TensorFlow model into a Barracuda model. :param source_file: The TensorFlow Model :param target_file: The name of the file the converted model will be saved to :param trim_unused_by_output: The regexp to match output nodes to remain in the model. All other uconnected nodes will be removed. :p...
Loads demonstration file and uses it to fill training buffer. :param file_path: Location of demonstration file (.demo). :param sequence_length: Length of trajectories to fill buffer. :return: def demo_to_buffer(file_path, sequence_length): """ Loads demonstration file and uses it to fill training b...
Loads and parses a demonstration file. :param file_path: Location of demonstration file (.demo). :return: BrainParameter and list of BrainInfos containing demonstration data. def load_demonstration(file_path): """ Loads and parses a demonstration file. :param file_path: Location of demonstration fi...
Saves current model to checkpoint folder. :param steps: Current number of steps in training process. :param saver: Tensorflow saver for session. def _save_model(self, steps=0): """ Saves current model to checkpoint folder. :param steps: Current number of steps in training proces...
Write all CSV metrics :return: def _write_training_metrics(self): """ Write all CSV metrics :return: """ for brain_name in self.trainers.keys(): if brain_name in self.trainer_metrics: self.trainers[brain_name].write_training_metrics()
Exports latest saved models to .nn format for Unity embedding. def _export_graph(self): """ Exports latest saved models to .nn format for Unity embedding. """ for brain_name in self.trainers.keys(): self.trainers[brain_name].export_model()
Initialization of the trainers :param trainer_config: The configurations of the trainers def initialize_trainers(self, trainer_config: Dict[str, Dict[str, str]]): """ Initialization of the trainers :param trainer_config: The configurations of the trainers """ trainer_par...
Resets the environment. Returns: A Data structure corresponding to the initial reset state of the environment. def _reset_env(self, env: BaseUnityEnvironment): """Resets the environment. Returns: A Data structure corresponding to the initial reset state of ...
Sends a shutdown signal to the unity environment, and closes the socket connection. def close(self): """ Sends a shutdown signal to the unity environment, and closes the socket connection. """ if self._socket is not None and self._conn is not None: message_input = UnityMessa...
float sqrt_var = sqrt(var_data[i]); a_data[i] = bias_data[i] - slope_data[i] * mean_data[i] / sqrt_var; b_data[i] = slope_data[i] / sqrt_var; ... ptr[i] = b * ptr[i] + a; def fuse_batchnorm_weights(gamma, beta, mean, var, epsilon): # https://github.com/Tencent/ncnn/blob/master/src/l...
- Ht = f(Xt*Wi + Ht_1*Ri + Wbi + Rbi) def rnn(name, input, state, kernel, bias, new_state, number_of_gates = 2): ''' - Ht = f(Xt*Wi + Ht_1*Ri + Wbi + Rbi) ''' nn = Build(name) nn.tanh( nn.mad(kernel=kernel, bias=bias, x=nn.concat(input, state)), out=new_state); return n...
- zt = f(Xt*Wz + Ht_1*Rz + Wbz + Rbz) - rt = f(Xt*Wr + Ht_1*Rr + Wbr + Rbr) - ht = g(Xt*Wh + (rt . Ht_1)*Rh + Rbh + Wbh) - Ht = (1-zt).ht + zt.Ht_1 def gru(name, input, state, kernel_r, kernel_u, kernel_c, bias_r, bias_u, bias_c, new_state, number_of_gates = 2): ''' - zt = f(X...
Full: - it = f(Xt*Wi + Ht_1*Ri + Pi . Ct_1 + Wbi + Rbi) - ft = f(Xt*Wf + Ht_1*Rf + Pf . Ct_1 + Wbf + Rbf) - ct = g(Xt*Wc + Ht_1*Rc + Wbc + Rbc) - Ct = ft . Ct_1 + it . ct - ot = f(Xt*Wo + Ht_1*Ro + Po . Ct + Wbo + Rbo) - Ht = ot . h(Ct) def lstm(name, input, state_c, state_h, kernel_i, kerne...
Evaluates policy for the agent experiences provided. :param brain_info: BrainInfo input to network. :return: Results of evaluation. def evaluate(self, brain_info): """ Evaluates policy for the agent experiences provided. :param brain_info: BrainInfo input to network. :re...
Performs update on model. :param mini_batch: Batch of experiences. :param num_sequences: Number of sequences to process. :return: Results of update. def update(self, mini_batch, num_sequences): """ Performs update on model. :param mini_batch: Batch of experiences. ...
Increments the lesson number depending on the progress given. :param measure_val: Measure of progress (either reward or percentage steps completed). :return Whether the lesson was incremented. def increment_lesson(self, measure_val): """ Increments the lesson number depen...
Returns reset parameters which correspond to the lesson. :param lesson: The lesson you want to get the config of. If None, the current lesson is returned. :return: The configuration of the reset parameters. def get_config(self, lesson=None): """ Returns reset parameters w...
Computes generalized advantage estimate for use in updating policy. :param rewards: list of rewards for time-steps t to T. :param value_next: Value estimate for time-step T+1. :param value_estimates: list of value estimates for time-steps t to T. :param gamma: Discount factor. :param lambd: GAE weig...
Increment the step count of the trainer and Updates the last reward def increment_step_and_update_last_reward(self): """ Increment the step count of the trainer and Updates the last reward """ if len(self.stats['Environment/Cumulative Reward']) > 0: mean_reward = np.mean(sel...
Constructs a BrainInfo which contains the most recent previous experiences for all agents info which correspond to the agents in a provided next_info. :BrainInfo next_info: A t+1 BrainInfo. :return: curr_info: Reconstructed BrainInfo to match agents of next_info. def construct_curr_info(self, n...
Adds experiences to each agent's experience history. :param curr_all_info: Dictionary of all current brains and corresponding BrainInfo. :param next_all_info: Dictionary of all current brains and corresponding BrainInfo. :param take_action_outputs: The outputs of the Policy's get_action method. ...
Checks agent histories for processing condition, and processes them as necessary. Processing involves calculating value and advantage targets for model updating step. :param current_info: Dictionary of all current brains and corresponding BrainInfo. :param new_info: Dictionary of all next brains...
A signal that the Episode has ended. The buffer must be reset. Get only called when the academy resets. def end_episode(self): """ A signal that the Episode has ended. The buffer must be reset. Get only called when the academy resets. """ self.training_buffer.reset_local...
Returns whether or not the trainer has enough elements to run update model :return: A boolean corresponding to whether or not update_model() can be run def is_ready_update(self): """ Returns whether or not the trainer has enough elements to run update model :return: A boolean correspond...
Uses demonstration_buffer to update the policy. def update_policy(self): """ Uses demonstration_buffer to update the policy. """ self.trainer_metrics.start_policy_update_timer( number_experiences=len(self.training_buffer.update_buffer['actions']), mean_return=flo...
Resets the state of the environment and returns an initial observation. In the case of multi-agent environments, this is a list. Returns: observation (object/list): the initial observation of the space. def reset(self): """Resets the state of the environment and returns an initial o...
Run one timestep of the environment's dynamics. When end of episode is reached, you are responsible for calling `reset()` to reset this environment's state. Accepts an action and returns a tuple (observation, reward, done, info). In the case of multi-agent environments, these are lists. ...
Creates a Dict that maps discrete actions (scalars) to branched actions (lists). Each key in the Dict maps to one unique set of branched actions, and each value contains the List of branched actions. def _create_lookup(self, branched_action_space): """ Creates a Dict that maps discrete ...
Creates the GRPC server. def create_server(self): """ Creates the GRPC server. """ self.check_port(self.port) try: # Establish communication grpc self.server = grpc.server(ThreadPoolExecutor(max_workers=10)) self.unity_to_external = UnityToEx...
Attempts to bind to the requested communicator port, checking if it is already in use. def check_port(self, port): """ Attempts to bind to the requested communicator port, checking if it is already in use. """ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: ...
Sends a shutdown signal to the unity environment, and closes the grpc connection. def close(self): """ Sends a shutdown signal to the unity environment, and closes the grpc connection. """ if self.is_open: message_input = UnityMessage() message_input.header.statu...
Converts byte array observation image into numpy array, re-sizes it, and optionally converts it to grey scale :param gray_scale: Whether to convert the image to grayscale. :param image_bytes: input byte array corresponding to image :return: processed numpy array of observation from envir...
Converts list of agent infos to BrainInfo. def from_agent_proto(agent_info_list, brain_params): """ Converts list of agent infos to BrainInfo. """ vis_obs = [] for i in range(brain_params.number_visual_observations): obs = [BrainInfo.process_pixels(x.visual_observati...
Converts brain parameter proto to BrainParameter object. :param brain_param_proto: protobuf object. :return: BrainParameter object. def from_proto(brain_param_proto): """ Converts brain parameter proto to BrainParameter object. :param brain_param_proto: protobuf object. ...
Creates a new, blank dashboard and redirects to it in edit mode def new(self): """Creates a new, blank dashboard and redirects to it in edit mode""" new_dashboard = models.Dashboard( dashboard_title='[ untitled dashboard ]', owners=[g.user], ) db.session.add(new_...
List all tags a given object has. def get(self, object_type, object_id): """List all tags a given object has.""" if object_id == 0: return json_success(json.dumps([])) query = db.session.query(TaggedObject).filter(and_( TaggedObject.object_type == object_type, ...
Add new tags to an object. def post(self, object_type, object_id): """Add new tags to an object.""" if object_id == 0: return Response(status=404) tagged_objects = [] for name in request.get_json(force=True): if ':' in name: type_name = name.spli...
Remove tags from an object. def delete(self, object_type, object_id): """Remove tags from an object.""" tag_names = request.get_json(force=True) if not tag_names: return Response(status=403) db.session.query(TaggedObject).filter(and_( TaggedObject.object_type ==...
Imports the datasource from the object to the database. Metrics and columns and datasource will be overrided if exists. This function can be used to import/export dashboards between multiple superset instances. Audit metadata isn't copies over. def import_datasource( session, i_datasour...
Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. def run_migrations_online(): """Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. """ # thi...
Returns a pandas dataframe based on the query object def get_df(self, query_obj=None): """Returns a pandas dataframe based on the query object""" if not query_obj: query_obj = self.query_obj() if not query_obj: return None self.error_msg = '' timestamp_...
Building a query object def query_obj(self): """Building a query object""" form_data = self.form_data self.process_query_filters() gb = form_data.get('groupby') or [] metrics = self.all_metrics or [] columns = form_data.get('columns') or [] groupby = [] f...
The cache key is made out of the key/values in `query_obj`, plus any other key/values in `extra`. We remove datetime bounds that are hard values, and replace them with the use-provided inputs to bounds, which may be time-relative (as in "5 days ago" or "now"). The `extra` argum...
This is the data object serialized to the js layer def data(self): """This is the data object serialized to the js layer""" content = { 'form_data': self.form_data, 'token': self.token, 'viz_name': self.viz_type, 'filter_select_enabled': self.datasource.f...
Returns the query object for this visualization def query_obj(self): """Returns the query object for this visualization""" d = super().query_obj() d['row_limit'] = self.form_data.get( 'row_limit', int(config.get('VIZ_ROW_LIMIT'))) numeric_columns = self.form_data.get('all_co...
Returns the chart data def get_data(self, df): """Returns the chart data""" chart_data = [] if len(self.groupby) > 0: groups = df.groupby(self.groupby) else: groups = [((), df)] for keys, data in groups: chart_data.extend([{ 'k...