text stringlengths 81 112k |
|---|
Gets the 95th percentile of bleakest_eval from bigtable
def get_95_percentile_bleak(games_nr, n_back=500):
"""Gets the 95th percentile of bleakest_eval from bigtable"""
end_game = int(games_nr.latest_game_number)
start_game = end_game - n_back if end_game >= n_back else 0
moves = games_nr.bleakest_move... |
Updates the flagfile at `flags_path`, changing the value for
`resign_threshold` to `new_threshold`
def update_flagfile(flags_path, new_threshold):
"""Updates the flagfile at `flags_path`, changing the value for
`resign_threshold` to `new_threshold`
"""
if abs(new_threshold) > 1:
raise Value... |
Prints the current MCTS search status to stderr.
Reports the current search path, root node's child_Q, root node's
child_N, the most visited path in a format that can be parsed by
one of the STDERR_HANDLERS in minigui.ts.
Args:
leaves: list of leaf MCTSNodes returned by tree_... |
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'{destnam... |
Launches data-parallel multi-gpu training.
def main():
"""
Launches data-parallel multi-gpu training.
"""
mlperf_log.ROOT_DIR_GNMT = os.path.dirname(os.path.abspath(__file__))
mlperf_log.LOGGER.propagate = False
args = parse_args()
device = utils.set_device(args.cuda, args.local_rank)
... |
Validate on held-out selfplay data.
def validate_holdout_selfplay():
"""Validate on held-out selfplay data."""
holdout_dirs = (os.path.join(fsdb.holdout_dir(), d)
for d in reversed(gfile.ListDirectory(fsdb.holdout_dir()))
if gfile.IsDirectory(os.path.join(fsdb.holdout_di... |
Validate on professional data.
def validate_pro():
"""Validate on professional data."""
cmd = ['python3', 'validate.py', FLAGS.pro_dataset,
'--use_tpu',
'--tpu_name={}'.format(TPU_NAME),
'--work_dir={}'.format(fsdb.working_dir()),
'--flagfile=rl_loop/distributed_flag... |
get number of groups used by GroupNorm, based on number of channels.
def get_group_gn(dim, dim_per_gp, num_groups):
"""get number of groups used by GroupNorm, based on number of channels."""
assert dim_per_gp == -1 or num_groups == -1, \
"GroupNorm: can only specify G or C/G."
if dim_per_gp > 0:
... |
Caffe2 implementation uses XavierFill, which in fact
corresponds to kaiming_uniform_ in PyTorch
def make_fc(dim_in, hidden_dim, use_gn=False):
'''
Caffe2 implementation uses XavierFill, which in fact
corresponds to kaiming_uniform_ in PyTorch
'''
if use_gn:
fc = nn.Linear(di... |
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:
... |
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... |
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 pixe... |
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'{destnam... |
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 n... |
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 ... |
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... |
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... |
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 ... |
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... |
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... |
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).
"""
# unwr... |
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 ch... |
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... |
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,
... |
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
... |
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)... |
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]
... |
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
"""
ret... |
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.Examp... |
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)
"""
... |
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... |
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,... |
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_... |
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... |
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... |
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... |
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():
... |
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 pick... |
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_di... |
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... |
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... |
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... |
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... |
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:
vali... |
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:
... |
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... |
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.
... |
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... |
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_st... |
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
... |
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_collat... |
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 = T... |
"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).
... |
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 ... |
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 ... |
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]
s... |
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, ma... |
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: inpu... |
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... |
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 ... |
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.... |
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]) & (... |
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 S... |
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.
... |
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).
"""
d... |
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 a... |
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_im... |
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... |
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:
... |
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... |
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 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... |
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 cr... |
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... |
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.
... |
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... |
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... |
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 ... |
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... |
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(METADAT... |
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.
# incl... |
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
... |
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... |
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 e... |
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,
... |
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.
... |
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.
... |
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... |
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 instanc... |
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... |
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_... |
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_... |
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 retur... |
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.golde... |
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... |
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 neighb... |
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
di... |
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:
... |
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
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.