INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
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_buffer_size: how big of a buffer to fill before ... | 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. | 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. | 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. | 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 targets ( list [ BoxList ): ground - truth boxes present in the... | 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. | 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. | 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: other args. Returns: evaluation result | 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. | 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. | 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. | 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. | 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. | 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 detpath. format ( classname ) should produce the detection results file. annopath: Path to annotations annopath. format ( imagename ) shou... | 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. | 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 ). | 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 | 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. | 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 | 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. | 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 | 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. | 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 (). | 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 | 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 | 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 | 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 | 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. | 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 | 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 | 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. | 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. | 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. | 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 | 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 | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. ) | 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 | 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. | 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. | 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. | 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. | 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
... |
Appends index of the current epoch and index of the current iteration to the name of the file with results. | def build_eval_path(self, epoch, iteration):
"""
Appends index of the current epoch and index of the current iteration
to the name of the file with results.
:param epoch: index of the current epoch
:param iteration: index of the current iteration
"""
if iteration... |
Runs translation on test dataset. | def run(self, calc_bleu=True, epoch=None, iteration=None, eval_path=None,
summary=False, reference_path=None):
"""
Runs translation on test dataset.
:param calc_bleu: if True compares results with reference and computes
BLEU score
:param epoch: index of the curre... |
Runs evaluation on test dataset. | def evaluate(self, epoch, iteration, summary):
"""
Runs evaluation on test dataset.
:param epoch: index of the current epoch
:param iteration: index of the current iteration
:param summary: if True prints summary
"""
batch_time = AverageMeter(False)
tot_t... |
Executes moses detokenizer on eval_path file and saves result to eval_path +. detok file. | def run_detokenizer(self, eval_path):
"""
Executes moses detokenizer on eval_path file and saves result to
eval_path + ".detok" file.
:param eval_path: path to the tokenized input
"""
logging.info('Running detokenizer')
detok_path = os.path.join(self.dataset_dir,... |
Executes sacrebleu and returns BLEU score. | def run_sacrebleu(self, detok_eval_path, reference_path):
"""
Executes sacrebleu and returns BLEU score.
:param detok_eval_path: path to the test file
:param reference_path: path to the reference file
"""
if reference_path is None:
reference_path = os.path.jo... |
Configures cloud logging | def configure(project=LOGGING_PROJECT):
"""Configures cloud logging
This is called for all main calls. If a $LOGGING_PROJECT is environment
variable configured, then STDERR and STDOUT are redirected to cloud
logging.
"""
if not project:
sys.stderr.write('!! Error: The $LOGGING_PROJECT e... |
Strategy: suppose that the models that we will create will have prefixes appended to each of its keys for example due to an extra level of nesting that the original pre - trained weights from ImageNet won t contain. For example model. state_dict () might return backbone [ 0 ]. body. res2. conv1. weight while the pre - ... | def align_and_update_state_dicts(model_state_dict, loaded_state_dict):
"""
Strategy: suppose that the models that we will create will have prefixes appended
to each of its keys, for example due to an extra level of nesting that the original
pre-trained weights from ImageNet won't contain. For example, m... |
Compute the ratio of gradient norm to weight norm. | def compute_update_ratio(weight_tensors, before_weights, after_weights):
"""Compute the ratio of gradient norm to weight norm."""
deltas = [after - before for after,
before in zip(after_weights, before_weights)]
delta_norms = [np.linalg.norm(d.ravel()) for d in deltas]
weight_norms = [np.l... |
Train on examples. | def train(*tf_records: "Records to train on"):
"""Train on examples."""
tf.logging.set_verbosity(tf.logging.INFO)
estimator = dual_net.get_estimator()
effective_batch_size = FLAGS.train_batch_size
if FLAGS.use_tpu:
effective_batch_size *= FLAGS.num_tpu_cores
if FLAGS.use_tpu:
i... |
Train on examples and export the updated model weights. | def main(argv):
"""Train on examples and export the updated model weights."""
tf_records = argv[1:]
logging.info("Training on %s records: %s to %s",
len(tf_records), tf_records[0], tf_records[-1])
with utils.logged_timer("Training"):
train(*tf_records)
if FLAGS.export_path:
... |
Freeze a model to a GraphDef proto. | def main(unused_argv):
"""Freeze a model to a GraphDef proto."""
if FLAGS.use_tpu:
dual_net.freeze_graph_tpu(FLAGS.model_path)
else:
dual_net.freeze_graph(FLAGS.model_path) |
Itertools recipe >>> list ( grouper ( 3 iter ( ABCDEFG ))) [[ A B C ] [ D E F ] [ G ]] | def grouper(n, iterable):
"""Itertools recipe
>>> list(grouper(3, iter('ABCDEFG')))
[['A', 'B', 'C'], ['D', 'E', 'F'], ['G']]
"""
return (iterable[i:i + n] for i in range(0, len(iterable), n)) |
Sample num_positions postions from each game in sgf_dir | def subsample():
"""Sample num_positions postions from each game in sgf_dir
Usage:
python3 sharp_positions.py subsample --num_positions 10 --sgf_dir data/s
NOTE(sethtroisi): see link for a script to truncate SGFs at move number
https://github.com/sethtroisi/go-scripts
"""
sgf_file... |
Get Policy and Value for each network for each position | def evaluate():
"""Get Policy and Value for each network, for each position
Usage:
python3 sharp_positions.py evaluate --sgf_dir data/s --model_dir models/
"""
def short_str(v):
if isinstance(v, float):
return "{.3f}".format(v)
return str(v)
# Load positons
... |
Find a subset of problems that maximal explains rating. | def minimize():
"""Find a subset of problems that maximal explains rating.
Usage:
python3 sharp_positions.py minimize \
--model_dir models --sgf_dir data/s
--rating_json ratings.json --results results.csv
"""
########################### HYPER PARAMETERS #################... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.