INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Returns a resized copy of this bounding box :param size: The requested size in pixels, as a 2-tuple: (width, height).
def resize(self, size, *args, **kwargs): """ Returns a resized copy of this bounding box :param size: The requested size in pixels, as a 2-tuple: (width, height). """ ratios = tuple(float(s) / float(s_orig) for s, s_orig in zip(size, self.size)) if ratios[0]...
Transpose bounding box (flip or rotate in 90 degree steps) :param method: One of :py:attr:`PIL.Image.FLIP_LEFT_RIGHT`, :py:attr:`PIL.Image.FLIP_TOP_BOTTOM`, :py:attr:`PIL.Image.ROTATE_90`, :py:attr:`PIL.Image.ROTATE_180`, :py:attr:`PIL.Image.ROTATE_270`, :py:attr:`PIL.Image.TRANSPO...
def transpose(self, method): """ Transpose bounding box (flip or rotate in 90 degree steps) :param method: One of :py:attr:`PIL.Image.FLIP_LEFT_RIGHT`, :py:attr:`PIL.Image.FLIP_TOP_BOTTOM`, :py:attr:`PIL.Image.ROTATE_90`, :py:attr:`PIL.Image.ROTATE_180`, :py:attr:`PIL.Image.R...
Cropss a rectangular region from this bounding box. The box is a 4-tuple defining the left, upper, right, and lower pixel coordinate.
def crop(self, box): """ Cropss a rectangular region from this bounding box. The box is a 4-tuple defining the left, upper, right, and lower pixel coordinate. """ xmin, ymin, xmax, ymax = self._split_into_xyxy() w, h = box[2] - box[0], box[3] - box[1] crop...
Parse commandline arguments.
def parse_args(): """ Parse commandline arguments. """ def exclusive_group(group, name, default, help): destname = name.replace('-', '_') subgroup = group.add_mutually_exclusive_group(required=False) subgroup.add_argument(f'--{name}', dest=f'{destname}', ...
Launches translation (inference). Inference is executed on a single GPU, implementation supports beam search with length normalization and coverage penalty.
def main(): """ Launches translation (inference). Inference is executed on a single GPU, implementation supports beam search with length normalization and coverage penalty. """ args = parse_args() utils.set_device(args.cuda, args.local_rank) utils.init_distributed(args.cuda) setup_lo...
Given a list of numeric sequences, returns the corresponding strings
def convert_to_strings(self, sequences, sizes=None): """Given a list of numeric sequences, returns the corresponding strings""" strings = [] for x in xrange(len(sequences)): seq_len = sizes[x] if sizes is not None else len(sequences[x]) string = self._convert_to_string(se...
Given a list of strings, removes blanks and replace space character with space. Option to remove repetitions (e.g. 'abbca' -> 'abca'). Arguments: sequences: list of 1-d array of integers remove_repetitions (boolean, optional): If true, repeating characters are re...
def process_strings(self, sequences, remove_repetitions=False): """ Given a list of strings, removes blanks and replace space character with space. Option to remove repetitions (e.g. 'abbca' -> 'abca'). Arguments: sequences: list of 1-d array of integers remove_r...
Computes the Word Error Rate, defined as the edit distance between the two provided sentences after tokenizing to words. Arguments: s1 (string): space-separated sentence s2 (string): space-separated sentence
def wer(self, s1, s2): """ Computes the Word Error Rate, defined as the edit distance between the two provided sentences after tokenizing to words. Arguments: s1 (string): space-separated sentence s2 (string): space-separated sentence """ # build ...
Returns the argmax decoding given the probability matrix. Removes repeated elements in the sequence, as well as blanks. Arguments: probs: Tensor of character probabilities from the network. Expected shape of seq_length x batch x output_dim sizes(optional): Size of each sequence ...
def decode(self, probs, sizes=None): """ Returns the argmax decoding given the probability matrix. Removes repeated elements in the sequence, as well as blanks. Arguments: probs: Tensor of character probabilities from the network. Expected shape of seq_length x batch x outpu...
Arguments: x (tuple[tensor, tensor]): x contains the class logits and the box_regression from the model. boxes (list[BoxList]): bounding boxes that are used as reference, one for ech image Returns: results (list[BoxList]): one BoxList for each...
def forward(self, x, boxes): """ Arguments: x (tuple[tensor, tensor]): x contains the class logits and the box_regression from the model. boxes (list[BoxList]): bounding boxes that are used as reference, one for ech image Returns: ...
Returns BoxList from `boxes` and adds probability scores information as an extra field `boxes` has shape (#detections, 4 * #classes), where each row represents a list of predicted bounding boxes for each of the object classes in the dataset (including the background class). The detection...
def prepare_boxlist(self, boxes, scores, image_shape): """ Returns BoxList from `boxes` and adds probability scores information as an extra field `boxes` has shape (#detections, 4 * #classes), where each row represents a list of predicted bounding boxes for each of the object cla...
Returns bounding-box detection results by thresholding on scores and applying non-maximum suppression (NMS).
def filter_results(self, boxlist, num_classes): """Returns bounding-box detection results by thresholding on scores and applying non-maximum suppression (NMS). """ # unwrap the boxlist to avoid additional overhead. # if we had multi-class NMS, we could perform this directly on th...
Returns the full path of the chunk to make (gs://...) and a boolean, indicating whether we should wait for a new model or if we're 'behind' and should just write out our current chunk immediately True == write immediately.
def _determine_chunk_to_make(write_dir): """ Returns the full path of the chunk to make (gs://...) and a boolean, indicating whether we should wait for a new model or if we're 'behind' and should just write out our current chunk immediately True == write immediately. """ models = fsdb.get_mo...
Fills a ringbuffer with positions from the most recent games, then continually rsync's and updates the buffer until a new model is promoted. Once it detects a new model, iit then dumps its contents for training to immediately begin on the next model.
def fill_and_wait_models(bufsize=EXAMPLES_PER_GENERATION, write_dir=None, threads=8, model_window=100, skip_first_rsync=False): """ Fills a ringbuffer with positions from the most recent games, then continually r...
Explicitly make a golden chunk for a given model `model_num` (not necessarily the most recent one). While we haven't yet got enough samples (EXAMPLES_PER_GENERATION) Add samples from the games of previous model.
def make_chunk_for(output_dir=LOCAL_DIR, local_dir=LOCAL_DIR, game_dir=None, model_num=1, positions=EXAMPLES_PER_GENERATION, threads=8, sampling_frac=0.02): """ Explicitly make a golden chunk for a ...
games is a list of .tfrecord.zz game records.
def parallel_fill(self, games, threads=8): """ games is a list of .tfrecord.zz game records. """ games.sort(key=os.path.basename) # A couple extra in case parsing fails max_games = int(self.max_size / self.sampling_frac / 200) + 480 if len(games) > max_games: games = ...
new_games is a list of .tfrecord.zz new game records.
def update(self, new_games): """ new_games is a list of .tfrecord.zz new game records. """ new_games.sort(key=os.path.basename) first_new_game = None for idx, game in enumerate(new_games): timestamp = file_timestamp(game) if timestamp <= self.examples[-1][0]: ...
Arguments: anchors: list[BoxList] box_cls: tensor of size N, A * C, H, W box_regression: tensor of size N, A * 4, H, W
def forward_for_single_feature_map( self, anchors, box_cls, box_regression): """ Arguments: anchors: list[BoxList] box_cls: tensor of size N, A * C, H, W box_regression: tensor of size N, A * 4, H, W """ device = box_cls.device N, _...
Args: features: [N, N, FEATURE_DIM] nparray of uint8 pi: [N * N + 1] nparray of float32 value: float
def make_tf_example(features, pi, value): """ Args: features: [N, N, FEATURE_DIM] nparray of uint8 pi: [N * N + 1] nparray of float32 value: float """ return tf.train.Example(features=tf.train.Features(feature={ 'x': tf.train.Feature( bytes_list=tf.train.Bytes...
Args: filename: Where to write tf.records tf_examples: An iterable of tf.Example serialize: whether to serialize the examples.
def write_tf_examples(filename, tf_examples, serialize=True): """ Args: filename: Where to write tf.records tf_examples: An iterable of tf.Example serialize: whether to serialize the examples. """ with tf.python_io.TFRecordWriter( filename, options=TF_RECORD_CONFIG) a...
Args: example_batch: a batch of tf.Example Returns: A tuple (feature_tensor, dict of output tensors)
def batch_parse_tf_example(batch_size, example_batch): """ Args: example_batch: a batch of tf.Example Returns: A tuple (feature_tensor, dict of output tensors) """ features = { 'x': tf.FixedLenFeature([], tf.string), 'pi': tf.FixedLenFeature([], tf.string), 'o...
Args: batch_size: batch size to return tf_records: a list of tf_record filenames num_repeats: how many times the data should be read (default: One) shuffle_records: whether to shuffle the order of files read shuffle_examples: whether to shuffle the tf.Examples shuffle_buf...
def read_tf_records(batch_size, tf_records, num_repeats=1, shuffle_records=True, shuffle_examples=True, shuffle_buffer_size=None, interleave=True, filter_amount=1.0): """ Args: batch_size: batch size to return tf_records: a list of tf_r...
Read tf.Records and prepare them for ingestion by dual_net. See `read_tf_records` for parameter documentation. Returns a dict of tensors (see return value of batch_parse_tf_example)
def get_input_tensors(batch_size, tf_records, num_repeats=1, shuffle_records=True, shuffle_examples=True, shuffle_buffer_size=None, filter_amount=0.05, random_rotation=True): """Read tf.Records and prepare them for ingestion by dual_net. See `re...
Returns an iterable of tf.Examples. Args: data_extracts: An iterable of (position, pi, result) tuples
def make_dataset_from_selfplay(data_extracts): """ Returns an iterable of tf.Examples. Args: data_extracts: An iterable of (position, pi, result) tuples """ tf_examples = (make_tf_example(features_lib.extract_features(pos), pi, result) for pos, pi, result in data_extracts)...
Arguments: features (list[Tensor]): feature-maps from possibly several levels proposals (list[BoxList]): proposal boxes targets (list[BoxList], optional): the ground-truth targets. Returns: x (Tensor): the result of the feature extractor proposals (li...
def forward(self, features, proposals, targets=None): """ Arguments: features (list[Tensor]): feature-maps from possibly several levels proposals (list[BoxList]): proposal boxes targets (list[BoxList], optional): the ground-truth targets. Returns: ...
Return a boolean representing whether a model should be stopped. Args: stop_threshold: float, the threshold above which a model should stop training. eval_metric: float, the current value of the relevant metric to check. Returns: True if training should stop, False otherwise. Raises: Valu...
def past_stop_threshold(stop_threshold, eval_metric): """Return a boolean representing whether a model should be stopped. Args: stop_threshold: float, the threshold above which a model should stop training. eval_metric: float, the current value of the relevant metric to check. Returns: True if...
Arguments: images (ImageList): images for which we want to compute the predictions features (list[Tensor]): features computed from the images that are used for computing the predictions. Each tensor in the list correspond to different feature levels ta...
def forward(self, images, features, targets=None): """ Arguments: images (ImageList): images for which we want to compute the predictions features (list[Tensor]): features computed from the images that are used for computing the predictions. Each tensor in the lis...
Helper function to synchronize (barrier) among all processes when using distributed training
def synchronize(): """ Helper function to synchronize (barrier) among all processes when using distributed training """ if not dist.is_available(): return if not dist.is_initialized(): return world_size = dist.get_world_size() if world_size == 1: return dist.b...
Run all_gather on arbitrary picklable data (not necessarily tensors) Args: data: any picklable object Returns: list[data]: list of data gathered from each rank
def all_gather(data): """ Run all_gather on arbitrary picklable data (not necessarily tensors) Args: data: any picklable object Returns: list[data]: list of data gathered from each rank """ world_size = get_world_size() if world_size == 1: return [data] # seriali...
Args: input_dict (dict): all the values will be reduced average (bool): whether to do average or sum Reduce the values in the dictionary from all processes so that process with rank 0 has the averaged results. Returns a dict with the same fields as input_dict, after reduction.
def reduce_dict(input_dict, average=True): """ Args: input_dict (dict): all the values will be reduced average (bool): whether to do average or sum Reduce the values in the dictionary from all processes so that process with rank 0 has the averaged results. Returns a dict with the same fi...
Bootstrap random weights.
def main(unused_argv): """Bootstrap random weights.""" utils.ensure_dir_exists(os.path.dirname(FLAGS.export_path)) if FLAGS.create_bootstrap: dual_net.bootstrap() dual_net.export_model(FLAGS.export_path)
Greedy decoder. :param batch_size: decoder batch size :param initial_input: initial input, usually tensor of BOS tokens :param initial_context: initial context, usually [encoder_context, src_seq_lengths, None] returns: (translation, lengths, counter) translation...
def greedy_search(self, batch_size, initial_input, initial_context=None): """ Greedy decoder. :param batch_size: decoder batch size :param initial_input: initial input, usually tensor of BOS tokens :param initial_context: initial context, usually [encoder_context, sr...
Beam search decoder. :param batch_size: decoder batch size :param initial_input: initial input, usually tensor of BOS tokens :param initial_context: initial context, usually [encoder_context, src_seq_lengths, None] returns: (translation, lengths, counter) transl...
def beam_search(self, batch_size, initial_input, initial_context=None): """ Beam search decoder. :param batch_size: decoder batch size :param initial_input: initial input, usually tensor of BOS tokens :param initial_context: initial context, usually [encoder_context, ...
evaluate dataset using different methods based on dataset type. Args: dataset: Dataset object predictions(list[BoxList]): each item in the list represents the prediction results for one image. output_folder: output folder, to save evaluation files or results. **kwargs: ot...
def evaluate(dataset, predictions, output_folder, **kwargs): """evaluate dataset using different methods based on dataset type. Args: dataset: Dataset object predictions(list[BoxList]): each item in the list represents the prediction results for one image. output_folder: outp...
Efficient version of torch.cat that avoids a copy if there is only a single element in a list
def cat(tensors, dim=0): """ Efficient version of torch.cat that avoids a copy if there is only a single element in a list """ assert isinstance(tensors, (list, tuple)) if len(tensors) == 1: return tensors[0] return torch.cat(tensors, dim)
Validate that examples are well formed. Pi should sum to 1.0 value should be {-1,1} Usage: validate_examples("../data/300.tfrecord.zz")
def validate_examples(example_file): """Validate that examples are well formed. Pi should sum to 1.0 value should be {-1,1} Usage: validate_examples("../data/300.tfrecord.zz") """ def test_example(raw): example = tf.train.Example() example.ParseFromString(raw) ...
Factory for getting a list of TensorFlow hooks for training by name. Args: name_list: a list of strings to name desired hook classes. Allowed: LoggingTensorHook, ProfilerHook, ExamplesPerSecondHook, which are defined as keys in HOOKS **kwargs: a dictionary of arguments to the hooks. Returns: ...
def get_train_hooks(name_list, **kwargs): """Factory for getting a list of TensorFlow hooks for training by name. Args: name_list: a list of strings to name desired hook classes. Allowed: LoggingTensorHook, ProfilerHook, ExamplesPerSecondHook, which are defined as keys in HOOKS **kwargs: a dict...
Function to get LoggingTensorHook. Args: every_n_iter: `int`, print the values of `tensors` once every N local steps taken on the current worker. tensors_to_log: List of tensor names or dictionary mapping labels to tensor names. If not set, log _TENSORS_TO_LOG by default. **kwargs: a dictiona...
def get_logging_tensor_hook(every_n_iter=100, tensors_to_log=None, **kwargs): # pylint: disable=unused-argument """Function to get LoggingTensorHook. Args: every_n_iter: `int`, print the values of `tensors` once every N local steps taken on the current worker. tensors_to_log: List of tensor names or...
Function to get ExamplesPerSecondHook. Args: every_n_steps: `int`, print current and average examples per second every N steps. batch_size: `int`, total batch size used to calculate examples/second from global time. warm_steps: skip this number of steps before logging and running average. ...
def get_examples_per_second_hook(every_n_steps=100, batch_size=128, warm_steps=5, **kwargs): # pylint: disable=unused-argument """Function to get ExamplesPerSecondHook. Args: every_n_steps: `int`, print current ...
Function to get LoggingMetricHook. Args: benchmark_log_dir: `string`, directory path to save the metric log. tensors_to_log: List of tensor names or dictionary mapping labels to tensor names. If not set, log _TENSORS_TO_LOG by default. every_n_secs: `int`, the frequency for logging the metric. Defa...
def get_logging_metric_hook(benchmark_log_dir=None, tensors_to_log=None, every_n_secs=600, **kwargs): # pylint: disable=unused-argument """Function to get LoggingMetricHook. Args: benchmark_log_dir: `string`, directory path to...
Parse a PASCAL VOC xml file
def parse_rec(filename): """ Parse a PASCAL VOC xml file """ tree = ET.parse(filename) objects = [] for obj in tree.findall('object'): obj_struct = {} obj_struct['name'] = obj.find('name').text obj_struct['pose'] = obj.find('pose').text obj_struct['truncated'] = int(obj.f...
rec, prec, ap = voc_eval(detpath, annopath, imagesetfile, classname, [ovthresh], [use_07_metric]) Top level function that does the PASCAL VOC evaluation. detpath: Path to detections ...
def voc_eval(detpath, annopath, imagesetfile, classname, cachedir, ovthresh=0.5, use_07_metric=True): """rec, prec, ap = voc_eval(detpath, annopath, imagesetfile, ...
Factory for collate_fn functions. :param batch_first: if True returns batches in (batch, seq) format, if False returns in (seq, batch) format :param parallel: if True builds batches from parallel corpus (src, tgt) :param sort: if True sorts by src sequence length within each batch
def build_collate_fn(batch_first=False, parallel=True, sort=False): """ Factory for collate_fn functions. :param batch_first: if True returns batches in (batch, seq) format, if False returns in (seq, batch) format :param parallel: if True builds batches from parallel corpus (src, tgt) :para...
Sorts dataset by the sequence length.
def sort_by_length(self): """ Sorts dataset by the sequence length. """ self.lengths, indices = self.lengths.sort(descending=True) self.src = [self.src[idx] for idx in indices] self.indices = indices.tolist() self.sorted = True
"Unsorts" given array (restores original order of elements before dataset was sorted by sequence length). :param array: array to be "unsorted"
def unsort(self, array): """ "Unsorts" given array (restores original order of elements before dataset was sorted by sequence length). :param array: array to be "unsorted" """ if self.sorted: inverse = sorted(enumerate(self.indices), key=itemgetter(1)) ...
Preserves only samples which satisfy the following inequality: min_len <= sample sequence length <= max_len :param min_len: minimum sequence length :param max_len: maximum sequence length
def filter_data(self, min_len, max_len): """ Preserves only samples which satisfy the following inequality: min_len <= sample sequence length <= max_len :param min_len: minimum sequence length :param max_len: maximum sequence length """ logging.info(f'Filteri...
Loads data from the input file. :param fname: input file name :param tokenizer: tokenizer :param max_size: loads at most 'max_size' samples from the input file, if None loads the entire dataset
def process_data(self, fname, tokenizer, max_size): """ Loads data from the input file. :param fname: input file name :param tokenizer: tokenizer :param max_size: loads at most 'max_size' samples from the input file, if None loads the entire dataset """ ...
Sorts dataset by the sequence length.
def sort_by_length(self): """ Sorts dataset by the sequence length. """ self.lengths, indices = self.lengths.sort(descending=True) self.src = [self.src[idx] for idx in indices] self.tgt = [self.tgt[idx] for idx in indices] self.src_lengths = [self.src_lengths[idx...
Preserves only samples which satisfy the following inequality: min_len <= src sample sequence length <= max_len AND min_len <= tgt sample sequence length <= max_len :param min_len: minimum sequence length :param max_len: maximum sequence length
def filter_data(self, min_len, max_len): """ Preserves only samples which satisfy the following inequality: min_len <= src sample sequence length <= max_len AND min_len <= tgt sample sequence length <= max_len :param min_len: minimum sequence length :param max_le...
Loads data from the input file. :param fname: input file name :param max_size: loads at most 'max_size' samples from the input file, if None loads the entire dataset
def process_raw_data(self, fname, max_size): """ Loads data from the input file. :param fname: input file name :param max_size: loads at most 'max_size' samples from the input file, if None loads the entire dataset """ logging.info(f'Processing data from {fna...
Preserves only samples which satisfy the following inequality: min_len <= src sample sequence length <= max_len AND min_len <= tgt sample sequence length <= max_len :param min_len: minimum sequence length :param max_len: maximum sequence length
def filter_raw_data(self, min_len, max_len): """ Preserves only samples which satisfy the following inequality: min_len <= src sample sequence length <= max_len AND min_len <= tgt sample sequence length <= max_len :param min_len: minimum sequence length :param ma...
Extract predicted keypoint locations from heatmaps. Output has shape (#rois, 4, #keypoints) with the 4 rows corresponding to (x, y, logit, prob) for each keypoint.
def heatmaps_to_keypoints(maps, rois): """Extract predicted keypoint locations from heatmaps. Output has shape (#rois, 4, #keypoints) with the 4 rows corresponding to (x, y, logit, prob) for each keypoint. """ # This function converts a discrete image coordinate in a HEATMAP_SIZE x # HEATMAP_SIZ...
Returns a input_receiver_fn that can be used during serving. This expects examples to come through as float tensors, and simply wraps them as TensorServingInputReceivers. Arguably, this should live in tf.estimator.export. Testing here first. Args: shape: list representing target size of a single example....
def build_tensor_serving_input_receiver_fn(shape, dtype=tf.float32, batch_size=1): """Returns a input_receiver_fn that can be used during serving. This expects examples to come through as float tensors, and simply wraps them as TensorServingInputReceivers. Arguably, ...
Validate which keypoints are contained inside a given box. points: NxKx2 boxes: Nx4 output: NxK
def _within_box(points, boxes): """Validate which keypoints are contained inside a given box. points: NxKx2 boxes: Nx4 output: NxK """ x_within = (points[..., 0] >= boxes[:, 0, None]) & ( points[..., 0] <= boxes[:, 2, None] ) y_within = (points[..., 1] >= boxes[:, 1, None]) & ( ...
Called once before using the session to check global step.
def begin(self): """Called once before using the session to check global step.""" self._global_step_tensor = tf.train.get_global_step() if self._global_step_tensor is None: raise RuntimeError( 'Global step should be created to use StepCounterHook.')
Called after each call to run(). Args: run_context: A SessionRunContext object. run_values: A SessionRunValues object.
def after_run(self, run_context, run_values): # pylint: disable=unused-argument """Called after each call to run(). Args: run_context: A SessionRunContext object. run_values: A SessionRunValues object. """ global_step = run_values.results if self._timer.should_trigger_for_step( ...
Visualizes keypoints (adapted from vis_one_image). kps has shape (4, #keypoints) where 4 rows are (x, y, logit, prob).
def vis_keypoints(img, kps, kp_thresh=2, alpha=0.7): """Visualizes keypoints (adapted from vis_one_image). kps has shape (4, #keypoints) where 4 rows are (x, y, logit, prob). """ dataset_keypoints = PersonKeypoints.NAMES kp_lines = PersonKeypoints.CONNECTIONS # Convert from plt 0-1 RGBA colors ...
Creates a basic transformation that was used to train the models
def build_transform(self): """ Creates a basic transformation that was used to train the models """ cfg = self.cfg # we are loading images with OpenCV, so we don't need to convert them # to BGR, they are already! So all we need to do is to normalize # by 255 if w...
Arguments: image (np.ndarray): an image as returned by OpenCV Returns: prediction (BoxList): the detected objects. Additional information of the detection properties can be found in the fields of the BoxList via `prediction.fields()`
def run_on_opencv_image(self, image): """ Arguments: image (np.ndarray): an image as returned by OpenCV Returns: prediction (BoxList): the detected objects. Additional information of the detection properties can be found in the fields of t...
Arguments: original_image (np.ndarray): an image as returned by OpenCV Returns: prediction (BoxList): the detected objects. Additional information of the detection properties can be found in the fields of the BoxList via `prediction.fields()`
def compute_prediction(self, original_image): """ Arguments: original_image (np.ndarray): an image as returned by OpenCV Returns: prediction (BoxList): the detected objects. Additional information of the detection properties can be found in the fields of ...
Select only predictions which have a `score` > self.confidence_threshold, and returns the predictions in descending order of score Arguments: predictions (BoxList): the result of the computation by the model. It should contain the field `scores`. Returns: ...
def select_top_predictions(self, predictions): """ Select only predictions which have a `score` > self.confidence_threshold, and returns the predictions in descending order of score Arguments: predictions (BoxList): the result of the computation by the model. ...
Simple function that adds fixed colors depending on the class
def compute_colors_for_labels(self, labels): """ Simple function that adds fixed colors depending on the class """ colors = labels[:, None] * self.palette colors = (colors % 255).numpy().astype("uint8") return colors
Adds the predicted boxes on top of the image Arguments: image (np.ndarray): an image as returned by OpenCV predictions (BoxList): the result of the computation by the model. It should contain the field `labels`.
def overlay_boxes(self, image, predictions): """ Adds the predicted boxes on top of the image Arguments: image (np.ndarray): an image as returned by OpenCV predictions (BoxList): the result of the computation by the model. It should contain the field `lab...
Adds the instances contours for each predicted object. Each label has a different color. Arguments: image (np.ndarray): an image as returned by OpenCV predictions (BoxList): the result of the computation by the model. It should contain the field `mask` and `label...
def overlay_mask(self, image, predictions): """ Adds the instances contours for each predicted object. Each label has a different color. Arguments: image (np.ndarray): an image as returned by OpenCV predictions (BoxList): the result of the computation by the mode...
Create a montage showing the probability heatmaps for each one one of the detected objects Arguments: image (np.ndarray): an image as returned by OpenCV predictions (BoxList): the result of the computation by the model. It should contain the field `mask`.
def create_mask_montage(self, image, predictions): """ Create a montage showing the probability heatmaps for each one one of the detected objects Arguments: image (np.ndarray): an image as returned by OpenCV predictions (BoxList): the result of the computation by...
Adds detected class names and scores in the positions defined by the top-left corner of the predicted bounding box Arguments: image (np.ndarray): an image as returned by OpenCV predictions (BoxList): the result of the computation by the model. It should contain t...
def overlay_class_names(self, image, predictions): """ Adds detected class names and scores in the positions defined by the top-left corner of the predicted bounding box Arguments: image (np.ndarray): an image as returned by OpenCV predictions (BoxList): the resu...
Collect the CPU information for the local environment.
def _collect_cpu_info(run_info): """Collect the CPU information for the local environment.""" cpu_info = {} cpu_info["num_cores"] = multiprocessing.cpu_count() # Note: cpuinfo is not installed in the TensorFlow OSS tree. # It is installable via pip. import cpuinfo # pylint: disable=g-import-not-at-top ...
Collect local GPU information by TF device library.
def _collect_gpu_info(run_info): """Collect local GPU information by TF device library.""" gpu_info = {} local_device_protos = device_lib.list_local_devices() gpu_info["count"] = len([d for d in local_device_protos if d.device_type == "GPU"]) # The device description usually is a J...
Log the evaluation result for a estimator. The evaluate result is a directory that contains metrics defined in model_fn. It also contains a entry for global_step which contains the value of the global step when evaluation was performed. Args: eval_results: dict, the result of evaluate() from a e...
def log_estimator_evaluation_result(self, eval_results): """Log the evaluation result for a estimator. The evaluate result is a directory that contains metrics defined in model_fn. It also contains a entry for global_step which contains the value of the global step when evaluation was performed. A...
Log the benchmark metric information to local file. Currently the logging is done in a synchronized way. This should be updated to log asynchronously. Args: name: string, the name of the metric to log. value: number, the value of the metric. The value will not be logged if it is not a ...
def log_metric(self, name, value, unit=None, global_step=None, extras=None): """Log the benchmark metric information to local file. Currently the logging is done in a synchronized way. This should be updated to log asynchronously. Args: name: string, the name of the metric to log. value: n...
Collect most of the TF runtime information for the local env. The schema of the run info follows official/benchmark/datastore/schema. Args: model_name: string, the name of the model.
def log_run_info(self, model_name): """Collect most of the TF runtime information for the local env. The schema of the run info follows official/benchmark/datastore/schema. Args: model_name: string, the name of the model. """ run_info = { "model_name": model_name, "machine_co...
Return the SGF filename for each existing eval record.
def read_existing_paths(bt_table): """Return the SGF filename for each existing eval record.""" rows = bt_table.read_rows( filter_=row_filters.ColumnRangeFilter( METADATA, SGF_FILENAME, SGF_FILENAME)) names = (row.cell_value(METADATA, SGF_FILENAME).decode() for row in rows) processed...
Keep filename and some date folders
def canonical_name(sgf_name): """Keep filename and some date folders""" sgf_name = os.path.normpath(sgf_name) assert sgf_name.endswith('.sgf'), sgf_name # Strip off '.sgf' sgf_name = sgf_name[:-4] # Often eval is inside a folder with the run name. # include from folder before /eval/ if part...
Read all SGFs that match glob Parse each game and extract relevant metadata for eval games table.
def read_games(glob, existing_paths): """Read all SGFs that match glob Parse each game and extract relevant metadata for eval games table. """ globbed = sorted(gfile.Glob(glob)) skipped = 0 to_parse = [] for sgf_name in tqdm(globbed): assert sgf_name.lower().endswith('.sgf'), sgf_...
Write all eval_records to eval_table In addition to writing new rows table_state must be updated in row `table_state` columns `metadata:eval_game_counter` Args: bt_table: bigtable table to add rows to. game_data: metadata pairs (column name, value) for each eval record. last_game: last...
def write_eval_records(bt_table, game_data, last_game): """Write all eval_records to eval_table In addition to writing new rows table_state must be updated in row `table_state` columns `metadata:eval_game_counter` Args: bt_table: bigtable table to add rows to. game_data: metadata pairs (c...
All of the magic together.
def main(unusedargv): """All of the magic together.""" del unusedargv bt_table = (bigtable .Client(FLAGS.cbt_project, admin=True) .instance(FLAGS.cbt_instance) .table(FLAGS.cbt_table)) assert bt_table.exists(), "Table doesn't exist" # Get current gam...
Initialize the reinforcement learning loop from a checkpoint.
def initialize_from_checkpoint(state): """Initialize the reinforcement learning loop from a checkpoint.""" # The checkpoint's work_dir should contain the most recently trained model. model_paths = glob.glob(os.path.join(FLAGS.checkpoint_dir, 'work_dir/model.ckpt-*.pb')) i...
Run the given subprocess command in a coroutine. Args: *cmd: the command to run and its arguments. Returns: The output that the command wrote to stdout as a list of strings, one line per element (stderr output is piped to stdout). Raises: RuntimeError: if the command returns a non-zero result.
async def run(*cmd): """Run the given subprocess command in a coroutine. Args: *cmd: the command to run and its arguments. Returns: The output that the command wrote to stdout as a list of strings, one line per element (stderr output is piped to stdout). Raises: RuntimeError: if the command r...
Return up to num_records of golden chunks to train on. Returns: A list of golden chunks up to num_records in length, sorted by path.
def get_golden_chunk_records(): """Return up to num_records of golden chunks to train on. Returns: A list of golden chunks up to num_records in length, sorted by path. """ pattern = os.path.join(fsdb.golden_chunk_dir(), '*.zz') return sorted(tf.gfile.Glob(pattern), reverse=True)[:FLAGS.window_size]
Run selfplay and write a training chunk to the fsdb golden_chunk_dir. Args: state: the RL loop State instance. flagfile: the name of the flagfile to use for selfplay, either 'selfplay' (the default) or 'boostrap'.
async def selfplay(state, flagfile='selfplay'): """Run selfplay and write a training chunk to the fsdb golden_chunk_dir. Args: state: the RL loop State instance. flagfile: the name of the flagfile to use for selfplay, either 'selfplay' (the default) or 'boostrap'. """ output_dir = os.path.join...
Run training and write a new model to the fsdb models_dir. Args: state: the RL loop State instance. tf_records: a list of paths to TensorFlow records to train on.
async def train(state, tf_records): """Run training and write a new model to the fsdb models_dir. Args: state: the RL loop State instance. tf_records: a list of paths to TensorFlow records to train on. """ model_path = os.path.join(fsdb.models_dir(), state.train_model_name) await run( 'python3...
Validate the trained model against holdout games. Args: state: the RL loop State instance. holdout_glob: a glob that matches holdout games.
async def validate(state, holdout_glob): """Validate the trained model against holdout games. Args: state: the RL loop State instance. holdout_glob: a glob that matches holdout games. """ if not glob.glob(holdout_glob): print('Glob "{}" didn\'t match any files, skipping validation'.format( ...
Evaluate one model against a target. Args: eval_model_path: the path to the model to evaluate. target_model_path: the path to the model to compare to. sgf_dif: directory path to write SGF output to. seed: random seed to use when running eval. Returns: The win-rate of eval_model against target_...
async def evaluate_model(eval_model_path, target_model_path, sgf_dir, seed): """Evaluate one model against a target. Args: eval_model_path: the path to the model to evaluate. target_model_path: the path to the model to compare to. sgf_dif: directory path to write SGF output to. seed: random seed to...
Evaluate the most recently trained model against the current best model. Args: state: the RL loop State instance.
async def evaluate_trained_model(state): """Evaluate the most recently trained model against the current best model. Args: state: the RL loop State instance. """ return await evaluate_model( state.train_model_path, state.best_model_path, os.path.join(fsdb.eval_dir(), state.train_model_name), s...
The main reinforcement learning (RL) loop.
def rl_loop(): """The main reinforcement learning (RL) loop.""" state = State() if FLAGS.checkpoint_dir: # Start from a partially trained model. initialize_from_checkpoint(state) else: # Play the first round of selfplay games with a fake model that returns # random noise. We do this instead of...
Run the reinforcement learning loop.
def main(unused_argv): """Run the reinforcement learning loop.""" print('Wiping dir %s' % FLAGS.base_dir, flush=True) shutil.rmtree(FLAGS.base_dir, ignore_errors=True) dirs = [fsdb.models_dir(), fsdb.selfplay_dir(), fsdb.holdout_dir(), fsdb.eval_dir(), fsdb.golden_chunk_dir(), fsdb.working_dir()] f...
Wrapper for a go.Position which replays its history. Assumes an empty start position! (i.e. no handicap, and history must be exhaustive.) Result must be passed in, since a resign cannot be inferred from position history alone. for position_w_context in replay_position(position): print(position...
def replay_position(position, result): """ Wrapper for a go.Position which replays its history. Assumes an empty start position! (i.e. no handicap, and history must be exhaustive.) Result must be passed in, since a resign cannot be inferred from position history alone. for position_w_context i...
Check if c is surrounded on all sides by 1 color, and return that color
def is_koish(board, c): 'Check if c is surrounded on all sides by 1 color, and return that color' if board[c] != EMPTY: return None neighbors = {board[n] for n in NEIGHBORS[c]} if len(neighbors) == 1 and EMPTY not in neighbors: return list(neighbors)[0] else: return None
Check if c is an eye, for the purpose of restricting MC rollouts.
def is_eyeish(board, c): 'Check if c is an eye, for the purpose of restricting MC rollouts.' # pass is fine. if c is None: return color = is_koish(board, c) if color is None: return None diagonal_faults = 0 diagonals = DIAGONALS[c] if len(diagonals) < 4: diagonal_...
Checks that a move is on an empty space, not on ko, and not suicide
def is_move_legal(self, move): 'Checks that a move is on an empty space, not on ko, and not suicide' if move is None: return True if self.board[move] != EMPTY: return False if move == self.ko: return False if self.is_move_suicidal(move): ...
Returns a np.array of size go.N**2 + 1, with 1 = legal, 0 = illegal
def all_legal_moves(self): 'Returns a np.array of size go.N**2 + 1, with 1 = legal, 0 = illegal' # by default, every move is legal legal_moves = np.ones([N, N], dtype=np.int8) # ...unless there is already a stone there legal_moves[self.board != EMPTY] = 0 # calculate whic...
Return score from B perspective. If W is winning, score is negative.
def score(self): 'Return score from B perspective. If W is winning, score is negative.' working_board = np.copy(self.board) while EMPTY in working_board: unassigned_spaces = np.where(working_board == EMPTY) c = unassigned_spaces[0][0], unassigned_spaces[1][0] ...
Return supervised examples from positions NOTE: last move is not played because no p.next_move after.
def parse_sgf_to_examples(sgf_path): """Return supervised examples from positions NOTE: last move is not played because no p.next_move after. """ return zip(*[(p.position, p.next_move, p.result) for p in sgf_wrapper.replay_sgf_file(sgf_path)])
Finds all sgf files in base_dir with year >= min_year and komi
def find_and_filter_sgf_files(base_dir, min_year=None, komi=None): """Finds all sgf files in base_dir with year >= min_year and komi""" sgf_files = [] for dirpath, dirnames, filenames in os.walk(base_dir): for filename in filenames: if filename.endswith('.sgf'): path = os...
Returns all model paths in the model_dir.
def get_model_paths(model_dir): """Returns all model paths in the model_dir.""" all_models = gfile.Glob(os.path.join(model_dir, '*.meta')) model_filenames = [os.path.basename(m) for m in all_models] model_numbers_names = [ (shipname.detect_model_num(m), shipname.detect_model_name(m)) for...
Turn a game into SGF. Doesn't handle handicap games or positions with incomplete history. Args: move_history: iterable of PlayerMoves result_string: "B+R", "W+0.5", etc. comments: iterable of string/None. Will be zipped with move_history.
def make_sgf( move_history, result_string, ruleset="Chinese", komi=7.5, white_name=PROGRAM_IDENTIFIER, black_name=PROGRAM_IDENTIFIER, comments=[] ): """Turn a game into SGF. Doesn't handle handicap games or positions with incomplete history. Args: move_history: iterable...
A node can either add B+W stones, play as B, or play as W.
def handle_node(pos, node): 'A node can either add B+W stones, play as B, or play as W.' props = node.properties black_stones_added = [coords.from_sgf( c) for c in props.get('AB', [])] white_stones_added = [coords.from_sgf( c) for c in props.get('AW', [])] if black_stones_added or wh...
Wrapper for sgf files, returning go.PositionWithContext instances. It does NOT return the very final position, as there is no follow up. To get the final position, call pwc.position.play_move(pwc.next_move) on the last PositionWithContext returned. Example usage: with open(filename) as f: ...
def replay_sgf(sgf_contents): """Wrapper for sgf files, returning go.PositionWithContext instances. It does NOT return the very final position, as there is no follow up. To get the final position, call pwc.position.play_move(pwc.next_move) on the last PositionWithContext returned. Example usage: ...
Applies the decoder to inputs, given the context from the encoder. :param inputs: tensor with inputs (batch, seq_len) if 'batch_first' else (seq_len, batch) :param context: context from the encoder :param inference: if True inference mode, if False training mode
def decode(self, inputs, context, inference=False): """ Applies the decoder to inputs, given the context from the encoder. :param inputs: tensor with inputs (batch, seq_len) if 'batch_first' else (seq_len, batch) :param context: context from the encoder :param infere...
Autoregressive generator, works with SequenceGenerator class. Executes decoder (in inference mode), applies log_softmax and topK for inference with beam search decoding. :param inputs: tensor with inputs to the decoder :param context: context from the encoder :param beam_size: b...
def generate(self, inputs, context, beam_size): """ Autoregressive generator, works with SequenceGenerator class. Executes decoder (in inference mode), applies log_softmax and topK for inference with beam search decoding. :param inputs: tensor with inputs to the decoder ...