def run(self, session, primers, length, temperature, hp=None): batch_size = len(primers) # process in segments to avoid tensorflow eating all the memory max_segment_length = min(10000, hp.segment_length) print "conditioning..." segment_length = min(max_segment_length, max(len(primer[0]) for primer in primers)) # ensure segment_length is a multiple of chunk_size segment_length -= segment_length % hp.chunk_size state = NS(model=self.model.initial_state(batch_size)) for segment in util.segments(primers, segment_length, overlap=hp.chunk_size): x, = util.examples_as_arrays(segment) feed_dict = {self.tensors.x: x.T} feed_dict.update(self.model.feed_dict(state.model)) values = NS.FlatCall( ft.partial(session.run, feed_dict=feed_dict), self.tensors.cond.Extract("final_state.model final_xchunk")) state.model = values.final_state.model sys.stderr.write(".") sys.stderr.write("\n") cond_values = values # make sure length is a multiple of chunk_size chunky_length = length + hp.chunk_size - length % hp.chunk_size print "sampling..." length_left = chunky_length xhats = [] state = NS(model=cond_values.final_state.model, initial_xchunk=cond_values.final_xchunk) while length_left > 0: segment_length = min(max_segment_length, length_left) length_left -= segment_length feed_dict = { self.tensors.initial_xchunk: state.initial_xchunk, self.tensors.length: segment_length, self.tensors.temperature: temperature } feed_dict.update(self.model.feed_dict(state.model)) sample_values = NS.FlatCall( ft.partial(session.run, feed_dict=feed_dict), self.tensors.sample.Extract( "final_state.model xhat final_xhatchunk")) state.model = sample_values.final_state.model state.initial_xchunk = sample_values.final_xhatchunk xhats.append(sample_values.xhat) sys.stderr.write(".") sys.stderr.write("\n") xhat = np.concatenate(xhats, axis=0) # truncate from chunky_length to the desired sample length xhat = xhat[:length] return xhat.T
def run(self, session, primers, length, temperature, hp=None): batch_size = len(primers) # process in segments to avoid tensorflow eating all the memory max_segment_length = min(10000, hp.segment_length) print "conditioning..." segment_length = min(max_segment_length, max(len(primer[0]) for primer in primers)) state = NS(model=self.model.initial_state(batch_size)) for segment in util.segments(primers, segment_length, overlap=LEFTOVER): x, = util.examples_as_arrays(segment) feed_dict = {self.tensors.x: x.T} feed_dict.update(self.model.feed_dict(state.model)) values = tfutil.run(session, tensors=self.tensors.cond.Extract( "final_state.model final_xelt"), feed_dict=feed_dict) state.model = values.final_state.model sys.stderr.write(".") sys.stderr.write("\n") cond_values = values print "sampling..." length_left = length + LEFTOVER xhats = [] state = NS(model=cond_values.final_state.model, initial_xelt=cond_values.final_xelt) while length_left > 0: segment_length = min(max_segment_length, length_left) length_left -= segment_length feed_dict = { self.tensors.initial_xelt: state.initial_xelt, self.tensors.length: segment_length, self.tensors.temperature: temperature } feed_dict.update(self.model.feed_dict(state.model)) sample_values = tfutil.run( session, tensors=self.tensors.sample.Extract( "final_state.model xhat final_xhatelt"), feed_dict=feed_dict), state.model = sample_values.final_state.model state.initial_xelt = sample_values.final_xhatelt xhats.append(sample_values.xhat) sys.stderr.write(".") sys.stderr.write("\n") xhat = np.concatenate(xhats, axis=0) return xhat.T
def run(self, session, examples, max_step_count=None, hooks=None, hp=None): tensors = self.tensors.Extract( "loss error summaries global_step training_op learning_rate final_state.model" ) state = NS(global_step=tf.train.global_step(session, self.tensors.global_step), model=self.model.initial_state(hp.batch_size)) while True: for batch in util.batches(examples, hp.batch_size): for segment in util.segments(batch, self.segment_length, overlap=LEFTOVER): if max_step_count is not None and state.global_step >= max_step_count: return hooks.Get("step.before", util.noop)(state) x, = util.examples_as_arrays(segment) feed_dict = {self.tensors.x: x.T} feed_dict.update(self.model.feed_dict(state.model)) values = tfutil.run(session, tensors, feed_dict=feed_dict) state.model = values.final_state.model state.global_step = values.global_step hooks.Get("step.after", util.noop)(state, values) print("step #%d loss %f error %f learning rate %e" % (values.global_step, values.loss, values.error, values.learning_rate)) if np.isnan(values.loss): raise ValueError("loss has become NaN")
def run(self, session, examples, max_step_count=None, hp=None, aggregates=None): aggregates = NS(aggregates or {}) for key in "loss error".split(): if key not in aggregates: aggregates[key] = util.MeanAggregate() tensors = self.tensors.Extract(*[key for key in aggregates.Keys()]) tensors.Update(self.tensors.Extract("final_state.model")) state = NS(step=0, model=self.model.initial_state(hp.batch_size)) try: for batch in util.batches(examples, hp.batch_size): for segment in util.segments(batch, hp.segment_length, overlap=hp.chunk_size): if max_step_count is not None and state.step >= max_step_count: raise StopIteration() x, = util.examples_as_arrays(segment) feed_dict = {self.tensors.x: x.T} feed_dict.update(self.model.feed_dict(state.model)) values = NS.FlatCall( ft.partial(session.run, feed_dict=feed_dict), tensors) for key in aggregates.Keys(): aggregates[key].add(values[key]) sys.stderr.write(".") state.model = values.final_state.model state.step += 1 except StopIteration: pass sys.stderr.write("\n") values = NS( (key, aggregate.value) for key, aggregate in aggregates.Items()) values.summaries = [ tf.Summary.Value(tag="%s_valid" % key, simple_value=values[key]) for key in "loss error".split() ] print "### evaluation loss %6.5f error %6.5f" % (values.loss, values.error) if np.isnan(values.loss): raise ValueError("loss has become NaN") return values
def run(self, session, examples, max_step_count=None, hooks=None, hp=None): state = NS(global_step=tf.train.global_step(session, self.tensors.global_step), model=self.model.initial_state(hp.batch_size)) while True: for batch in util.batches(examples, hp.batch_size): for segment in util.segments( batch, # the last chunk is not processed, so grab # one more to ensure we backpropagate # through at least one full model cycle. # TODO(cotim): rename segment_length to # backprop_length? hp.segment_length + hp.chunk_size, overlap=hp.chunk_size): if max_step_count is not None and state.global_step >= max_step_count: return hooks.Get("step.before", util.noop)(state) x, = util.examples_as_arrays(segment) feed_dict = {self.tensors.x: x.T} feed_dict.update(self.model.feed_dict(state.model)) values = NS.FlatCall( ft.partial(session.run, feed_dict=feed_dict), self.tensors.Extract( "loss error summaries global_step training_op learning_rate final_state.model" )) state.model = values.final_state.model state.global_step = values.global_step hooks.Get("step.after", util.noop)(state, values) print("step #%d loss %f error %f learning rate %e" % (values.global_step, values.loss, values.error, values.learning_rate)) if np.isnan(values.loss): raise ValueError("loss has become NaN")
def _make_sequence_graph_with_unroll(self, model_state=None, x=None, initial_xelt=None, context=None, length=None, temperature=1.0, hp=None, back_prop=False): """Create a sequence graph by unrolling upper layers. This method is similar to `_make_sequence_graph`, except that `length` must be provided. The resulting graph behaves in the same way as that constructed by `_make_sequence_graph`, except that the upper layers are outside of the while loop and so the gradient can actually be truncated between runs of lower layers. If `x` is given, the graph processes the sequence `x` one element at a time. At step `i`, the model receives the `i`th element as input, and its output is used to predict the `i + 1`th element. The last element is not processed, as there would be no further element available to compare against and compute loss. To ensure all data is processed during TBPTT, segments `x` fed into successive computations of the graph should overlap by 1. If `x` is not given, `initial_xelt` must be given as the first input to the model. Further elements are constructed from the model's predictions. Args: model_state: initial state of the model. x: Sequence of integer (categorical) inputs. Not needed if sampling. Axes [time, batch]. initial_xelt: When sampling, x is not given; initial_xelt specifies the input x[0] to the first timestep. context: a `Tensor` denoting context, e.g. for conditioning. Axes [batch, features]. length: Optional length of sequence. Inferred from `x` if possible. temperature: Softmax temperature to use for sampling. hp: Model hyperparameters. back_prop: Whether the graph will be backpropagated through. Raises: ValueError: if `length` is not an int. Returns: Namespace containing relevant symbolic variables. """ if length is None or not isinstance(length, int): raise ValueError( "For partial unrolling, length must be known at graph construction time." ) if model_state is None: model_state = self.state_placeholders() state = NS(model=model_state, inner_initial_xelt=initial_xelt, xhats=[], losses=[], errors=[]) # i suspect ugly gradient biases may occur if gradients are truncated # somewhere halfway through the cycle. ensure we start at a cycle boundary. state.model.time = tfutil.assertion(state.model.time, tf.equal(state.model.time, 0), [state.model.time], name="outer_alignment_assertion") # ensure we end at a cycle boundary too. assert (length - LEFTOVER) % self.period == 0 inner_period = int(np.prod(hp.periods[:self.outer_indices[0] + 1])) # hp.boundaries specifies truncation boundaries relative to the end of the sequence and in terms # of each layer's own steps; translate this to be relative to the beginning of the sequence and # in terms of sequence elements. note that due to the dynamic unrolling of the inner graph, the # inner layers necessarily get truncated at the topmost inner layer's boundary. boundaries = [ length - 1 - hp.boundaries[i] * int(np.prod(hp.periods[:i + 1])) for i in range(len(hp.periods)) ] assert all(0 <= boundary and boundary < length - LEFTOVER for boundary in boundaries) assert boundaries == list(reversed(sorted(boundaries))) print "length %s periods %s boundaries %s %s inner period %s" % ( length, hp.periods, hp.boundaries, boundaries, inner_period) outer_step_count = length // inner_period for outer_time in range(outer_step_count): if outer_time > 0: tf.get_variable_scope().reuse_variables() # update outer layers (wrap in seq scope to be consistent with the fully # symbolic version of this graph) with tf.variable_scope("seq"): # truncate gradient (only effective on outer layers) for i in range(len(self.cells)): if outer_time * inner_period <= boundaries[i]: state.model.cells[i] = list( map(tf.stop_gradient, state.model.cells[i])) state.model.cells = Wayback.transition( outer_time * inner_period, state.model.cells, self.cells, below=None, above=context, subset=self.outer_indices, hp=hp, symbolic=False) # run inner layers on subsequence if x is None: inner_x = None else: start = inner_period * outer_time stop = inner_period * (outer_time + 1) + LEFTOVER inner_x = x[start:stop, :] # grab a copy of the outer states. they will not be updated in the inner # loop, so we can put back the copy after the inner loop completes. # this avoids the gradient truncation due to calling `while_loop` with # `back_prop=False`. outer_cell_states = NS.Copy(state.model.cells[self.outer_slice]) def _inner_transition(input_, state, context=None): assert not context state.cells = Wayback.transition(state.time, state.cells, self.cells, below=input_, above=None, subset=self.inner_indices, hp=hp, symbolic=True) state.time += 1 state.time %= self.period h = self.get_output(state) return h, state inner_back_prop = back_prop and outer_time * inner_period >= boundaries[ self.inner_indices[-1]] inner_ts = _make_sequence_graph( transition=_inner_transition, model_state=state.model, x=inner_x, initial_xelt=state.inner_initial_xelt, temperature=temperature, hp=hp, back_prop=inner_back_prop) state.model = inner_ts.final_state.model state.inner_initial_xelt = inner_ts.final_xelt if x is not None else inner_ts.final_xhatelt state.final_xhatelt = inner_ts.final_xhatelt if x is not None: state.final_x = inner_x state.final_xelt = inner_ts.final_xelt # track only losses and errors after the boundary to avoid bypassing the truncation boundary. if inner_back_prop: state.losses.append(inner_ts.loss) state.errors.append(inner_ts.error) state.xhats.append(inner_ts.xhat) # restore static outer states state.model.cells[self.outer_slice] = outer_cell_states # double check alignment to be safe state.model.time = tfutil.assertion( state.model.time, tf.equal(state.model.time % inner_period, 0), [state.model.time, tf.shape(inner_x)], name="inner_alignment_assertion") ts = NS() ts.xhat = tf.concat(0, state.xhats) ts.final_xhatelt = state.final_xhatelt ts.final_state = state if x is not None: ts.final_x = state.final_x ts.final_xelt = state.final_xelt # inner means are all on the same sample size, so taking their mean is valid ts.loss = tf.reduce_mean(state.losses) ts.error = tf.reduce_mean(state.errors) return ts