id stringlengths 15 25 | source stringclasses 1
value | chunk_index int64 0 393k | token_count int32 449 512 | text stringlengths 203 7.95k |
|---|---|---|---|---|
combine_chunk_391800 | combine.txt | 391,800 | 512 | `Layer`s and `Optimizer`s will automatically add
dependencies on their variables (e.g. "kernel" and "bias" for
`tf.keras.layers.Dense`). Inheriting from `tf.keras.Model` makes managing
dependencies easy in user-defined classes, since `Model` hooks into attribute
assignment. For example:
```python
class Re... |
combine_chunk_391801 | combine.txt | 391,801 | 512 | with _END_TIME_OF_LAST_WRITE_LOCK:
if _END_TIME_OF_LAST_WRITE is None:
_END_TIME_OF_LAST_WRITE = time.time()
for k, v in sorted(kwargs.items(), key=lambda item: item[0]):
setattr(self, k, v)
if not isinstance(
getattr(self, k), (base.Trackable, def_function.Function)):
... |
combine_chunk_391802 | combine.txt | 391,802 | 512 | """
return self._write(file_prefix, session, options=options)
def _write(self, file_prefix, session=None, options=None):
"""Writes a training checkpoint.
The checkpoint includes variables created by this object and any
trackable objects it depends on at the time `Checkpoint.write()` is
called.
... |
combine_chunk_391803 | combine.txt | 391,803 | 512 |
@property
def save_counter(self):
"""An integer variable which starts at zero and is incremented on save.
Used to number checkpoints.
Returns:
The save counter variable.
"""
self._maybe_create_save_counter()
return self._save_counter
def save(self, file_prefix, session=None, opt... |
combine_chunk_391804 | combine.txt | 391,804 | 512 | _value=True)
if graph_building:
self._save_assign_op = data_structures.NoDependency(assign_op)
if graph_building:
checkpoint_number = session.run(self._save_assign_op)
else:
checkpoint_number = assign_op.numpy()
file_path = self.write(
"%s-%d" % (file_prefix, checkpoint_num... |
combine_chunk_391805 | combine.txt | 391,805 | 512 | in your graph have been created.
Name-based `tf.compat.v1.train.Saver` checkpoints can be loaded using this
method. Names are used to match variables. No restore ops are created/run
until `run_restore_ops()` or `initialize_or_restore()` are called on the
returned status object when graph building, but... |
combine_chunk_391806 | combine.txt | 391,806 | 512 | a very weak assertion, but is useful for
sanity checking in library code where objects may exist in the
checkpoint which haven't been created in Python and some Python
objects may not have a checkpointed value.
* `expect_partial()`: Silence warnings about incomplete checkpoint
... |
combine_chunk_391807 | combine.txt | 391,807 | 512 | .keras.Model(...)
checkpoint = tf.train.Checkpoint(model)
# Save a checkpoint to /tmp/training_checkpoints-{save_counter}. Every time
# checkpoint.save is called, the save counter is increased.
save_path = checkpoint.save('/tmp/training_checkpoints')
# Restore the checkpointed values to the `model` object.
... |
combine_chunk_391808 | combine.txt | 391,808 | 512 | # ...
def call(self, inputs):
x = self.input_transform(inputs)
# ...
```
This `Model` has a dependency named "input_transform" on its `Dense` layer,
which in turn depends on its variables. As a result, saving an instance of
`Regress` using `tf.train.Checkpoint` will also save all the variable... |
combine_chunk_391809 | combine.txt | 391,809 | 512 | _TIME_OF_LAST_WRITE is None:
_END_TIME_OF_LAST_WRITE = time.time()
# Store a reference to root and kwargs if we need to instantiate an
# AsyncCheckpointer later.
self._root = root
self._kwargs = kwargs
self._delete_tracking("_kwargs")
# Don't instantiate the AsyncCheckpointer unless re... |
combine_chunk_391810 | combine.txt | 391,810 | 512 | counter if it does not yet exist."""
if self._save_counter is None:
# Initialized to 0 and incremented before saving.
with ops.device("/cpu:0"):
# add_variable creates a dependency named "save_counter"; NoDependency
# prevents creating a second dependency named "_save_counter".
... |
combine_chunk_391811 | combine.txt | 391,811 | 512 | localhost")
checkpoint.write("/tmp/ckpt", options=options)
# Later, read the checkpoint with read()
checkpoint.read("/tmp/ckpt", options=options)
```
Args:
file_prefix: A prefix to use for the checkpoint filenames
(/path/to/directory/and_a_prefix).
options: Optional `tf.train.C... |
combine_chunk_391812 | combine.txt | 391,812 | 512 | options or checkpoint_options.CheckpointOptions()
output = self._saver.save(file_prefix=file_prefix, options=options)
output = _convert_file_name_tensor_to_string(output)
# Execute callbacks (the only place they are executed; i.e. all entry points
# for callbacks will ultimately be directed to here fo... |
combine_chunk_391813 | combine.txt | 391,813 | 512 |
called.
`save` is a basic convenience wrapper around the `write` method,
sequentially numbering checkpoints using `save_counter` and updating the
metadata used by `tf.train.latest_checkpoint`. More advanced checkpoint
management, for example garbage collection and custom numbering, may be
prov... |
combine_chunk_391814 | combine.txt | 391,814 | 512 | Like):
file_prefix = os.fspath(file_prefix)
# pylint:enable=line-too-long
# We create a copy so that user's `options` instance would not be mutated
# by internal mechanisms.
options = copy.copy(options) or checkpoint_options.CheckpointOptions()
graph_building = not context.executing_eagerly()
... |
combine_chunk_391815 | combine.txt | 391,815 | 512 | ()
ckpt = tf.train.Checkpoint(v=tf.Variable(1.))
path = ckpt.write('/tmp/my_checkpoint')
# Later, load the checkpoint with read()
# With restore() assert_consumed() would have failed.
checkpoint.read(path).assert_consumed()
# You can also pass options to read(). For example this
# runs the... |
combine_chunk_391816 | combine.txt | 391,816 | 512 | are
created. Dependencies added after this call will be matched if they have a
corresponding object in the checkpoint (the restore request will queue in
any trackable object waiting for the expected dependency to be added).
```python
checkpoint = tf.train.Checkpoint( ... )
checkpoint.restore(p... |
combine_chunk_391817 | combine.txt | 391,817 | 512 | an exception if any variables are unmatched: either
checkpointed values which don't have a matching Python object or
Python objects in the dependency graph with no values in the
checkpoint. This method returns the status object, and so may be
chained with other assertions.
... |
combine_chunk_391818 | combine.txt | 391,818 | 512 | if isinstance(save_path, os.PathLike):
save_path = os.fspath(save_path)
if save_path is not None and gfile.IsDirectory(save_path) and (
(gfile.Exists(path_helpers.get_saved_model_pb_path(save_path)) or
gfile.Exists(path_helpers.get_saved_model_pbtxt_path(save_path)))):
save_path = pat... |
combine_chunk_391819 | combine.txt | 391,819 | 512 | logging
from tensorflow.python.checkpoint import checkpoint_context
from tensorflow.python.checkpoint import trackable_view
from tensorflow.python.distribute import device_util
from tensorflow.python.eager import context
from tensorflow.python.eager import def_function
from tensorflow.python.eager import executor
fro... |
combine_chunk_391820 | combine.txt | 391,820 | 512 | erset of `saveable_trackables`.
"""
all_trackables = trackable_view.TrackableView(root=root).descendants()
# Kick out the trackable we want to exclude.
# The goal of writing such loop is to only scan the list once and stop
# scanning as early as possible (unlike filtering with list comprehension).
trackabl... |
combine_chunk_391821 | combine.txt | 391,821 | 512 | in type(obj).mro():
if t is base.Trackable:
# Base class always has them implemented, but would raise error.
continue
elif ("_serialize_to_tensors" in t.__dict__
or "_gather_saveables_for_checkpoint" in t.__dict__
or "_copy_trackable_to_cpu" in t.__dict__):
r... |
combine_chunk_391822 | combine.txt | 391,822 | 512 | list of TPUEmbedding objects included in the checkpoint items.
self._tpu_embedding_objects = None
# A list of highest level `Trackable`s we will copy; does not contain
# TPUEmbedding objects
self._saveable_trackables = None
self._default_device = device_util.current() or "CPU:0"
self._default_... |
combine_chunk_391823 | combine.txt | 391,823 | 512 | pointer(self):
"""Gets or creates the underlying Checkpoint instance."""
if self._checkpoint is None:
self._checkpoint = self._checkpointer_impl(**self._checkpoint_items)
return self._checkpoint
def _ensure_initialized(self):
"""Initialize the async checkpoint internal state."""
# This map ... |
combine_chunk_391824 | combine.txt | 391,824 | 512 | hasattr may result in KeyError
original_slot_variable = t.get_slot(original_variable, slot_name)
except (AttributeError, KeyError):
continue
if isinstance(original_slot_variable, base.Trackable):
self._saveable_trackables.append(original_slot_variable)
... |
combine_chunk_391825 | combine.txt | 391,825 | 512 | 2). Join the async save thread. (The thread may finish before joining.)
"""
try:
self._queue.put(False, timeout=300) # Step-1.
logging.info("Joining the async save thread.")
if self._async_save_thread is not None:
self._async_save_thread.join() # Step-2.
except queue.Full:
... |
combine_chunk_391826 | combine.txt | 391,826 | 512 | , the duration of the final
# async checkpoint is excluded, which is fine since it does not take
# much time.
global _END_TIME_OF_LAST_ASYNC_WRITE
with _END_TIME_OF_LAST_ASYNC_WRITE_LOCK:
metrics.AddTrainingTimeSaved(
api_label=_ASYNC_CHECKPOINT,
mic... |
combine_chunk_391827 | combine.txt | 391,827 | 512 | AsyncCheckpoint class. The number starts at 0 and gets incremented for each
checkpoint event.
Returns:
The save counter variable.
"""
return self.checkpointer().save_counter
def write(self, save_path, options=None):
"""Save the checkpointed variables.
Args:
save_path: The fi... |
combine_chunk_391828 | combine.txt | 391,828 | 512 | """Save the checkpointed variables.
Args:
save_path: The file prefix of the checkpoint file.
options: Optional CheckpointOption instance.
Returns:
The full path of the checkpoint file.
"""
save_start_time = time.time()
# If this is the first time that AsyncCheckpoint.save() ... |
combine_chunk_391829 | combine.txt | 391,829 | 512 | _enable_async_checkpoint = False
self._queue.put(True) # Trigger save in async thread
save_end_time = time.time()
metrics.AddCheckpointWriteDuration(
api_label=_ASYNC_CHECKPOINT,
microseconds=_get_duration_microseconds(save_start_time, save_end_time))
return full_path
def read(sel... |
combine_chunk_391830 | combine.txt | 391,830 | 512 | 2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License... |
combine_chunk_391831 | combine.txt | 391,831 | 512 | # Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==... |
combine_chunk_391832 | combine.txt | 391,832 | 512 | checkpoint_key], [shape_and_slice_spec])
class AbstractCheckpointAdapter(abc.ABC):
"""Abstract API for checkpoint adapter.
This is an experimental API that specifies how checkpoint restore should be
adapted for specific trackable objects.
"""
@classmethod
@abc.abstractmethod
def create_from_checkpoint... |
combine_chunk_391833 | combine.txt | 391,833 | 512 | tensorflow.python.checkpoint import util
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.saved_model import registration
from tensorflow.python.trackable import base
from tensorflow.python.trackable im... |
combine_chunk_391834 | combine.txt | 391,834 | 512 | (for compatibility purposes during
# SaveableObject deprecation)
key_suffix = saveable_compat.get_saveable_name(object_to_save) or name
checkpoint_key = trackable_utils.checkpoint_key(object_name, key_suffix)
if not saveable_compat.force_checkpoint_conversion_enabled():
# Ma... |
combine_chunk_391835 | combine.txt | 391,835 | 512 | object_proto.registered_saver.object_name = object_name
object_to_save = util.get_mapped_trackable(trackable, object_map)
registered_savers[saver_name][object_name] = object_to_save
return registered_savers
def generate_saveable_objects(checkpoint_factory_map,
object_grap... |
combine_chunk_391836 | combine.txt | 391,836 | 512 | (
saveable_object_util.saveable_objects_for_op(
op=maybe_saveable, name=key))
for saveable in saveables:
if key not in saveable.name:
raise AssertionError(
f"The object {trackable} produced a SaveableObject with name "
f"'{sav... |
combine_chunk_391837 | combine.txt | 391,837 | 512 | for checkpoint_id, trackable in enumerate(trackable_objects):
assert node_ids[trackable] == checkpoint_id
object_proto = object_graph_proto.nodes.add(
slot_variables=slot_variables.get(trackable, ())
)
for child in graph_view.list_children(trackable):
object_proto.children.add(
... |
combine_chunk_391838 | combine.txt | 391,838 | 512 | ableObjects and registered savers in the frozen graph."""
if to_graph:
target_context = to_graph.as_default
else:
target_context = ops.NullContextmanager
with target_context():
named_saveable_objects, graph_proto, _, registered_savers = (
serialize_gathered_objects(graph_view, object_map,
... |
combine_chunk_391839 | combine.txt | 391,839 | 512 | dtype, device)
<|file|>tensorflow/tensorflow/python/checkpoint/sharding/sharding_util.py
# Copyright 2023 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the L... |
combine_chunk_391840 | combine.txt | 391,840 | 512 | , self.dtype, str(self.device), self.checkpoint_key))
def __repr__(self) -> str:
return (f"\n{self.__class__.__name__}:\n"
f" _tensor_save_spec={self._tensor_save_spec!r}\n"
f" tensor={self.tensor!r}\n"
f" dtype={self.dtype!r}\n"
f" device={self.device!r}\n"
... |
combine_chunk_391841 | combine.txt | 391,841 | 512 | tensors.set_default(checkpoint_key, {})[slice_spec] = tensor
return [tensors]
ckpt.save(
"path",
options=tf.train.CheckpointOptions(
experimental_sharding_callback=AllInOnePolicy()))
```
The `description` attribute is used to identify the callback and to aid
debugging durin... |
combine_chunk_391842 | combine.txt | 391,842 | 512 | "tensors with the same checkpoint key and slice spec were "
"found:\n"
f" callback_description: {callback_description}\n"
f" checkpoint_key: {checkpoint_key}\n"
f" slice_spec: {slice_spec}\n")
# Validate no added tensors.
if check... |
combine_chunk_391843 | combine.txt | 391,843 | 512 | f" checkpoint_key: {checkpoint_key}\n"
f" slice_spec: {slice_spec}\n"
f" original tensor_task: {target_task}\n"
f" new tensor_task: {shard_tensor_task}\n")
# Validate tensors in shard have the same task.
if task_tensor is None:
task_... |
combine_chunk_391844 | combine.txt | 391,844 | 512 | >tensorflow/tensorflow/python/checkpoint/sharding/sharding_policies.py
# Copyright 2023 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# ht... |
combine_chunk_391845 | combine.txt | 391,845 | 512 | return [tensors_by_task]
_OffsetAndShape = tuple[Sequence[int], Sequence[int]]
@tf_export.tf_export("train.experimental.MaxShardSizePolicy")
class MaxShardSizePolicy(sharding_util.ShardingCallback):
"""Policy that splits tensors into shards with a max shard size.
Shards may exceed the max shard size if the... |
combine_chunk_391846 | combine.txt | 391,846 | 512 | for axis in range(1, rank):
parts_along_axis = num_partitions(axis)
part_size = num_elems * self._dtype_size / parts_along_axis
if (parts_along_axis < min_parts and
part_size <= self._shard_size_remaining):
min_axis, min_parts = axis, int(parts_along_axis)
retur... |
combine_chunk_391847 | combine.txt | 391,847 | 512 | :
(self._tensors_by_shard[-1]
.setdefault(self._checkpoint_key, {})[slice_spec]) = tensor_slice
self._shard_size_remaining -= slice_size_in_bytes
if self._shard_size_remaining == 0:
self._tensors_by_shard.append({})
self._shard_size_remaining = self.max_shard_size
... |
combine_chunk_391848 | combine.txt | 391,848 | 512 | .shape
self._root_offset = [0] * self._root_shape.rank
self._dtype_size = dtypes.as_dtype(self._dtype).size
total_size = self._root_shape.num_elements() * self._dtype_size # bytes
# Calculate string tensor sizes.
if self._checkpoint_key == base.OBJECT_GRAPH_PROTO_KEY:
... |
combine_chunk_391849 | combine.txt | 391,849 | 512 | is a %s scalar of size %s bytes and cannot be "
"partitioned into a shard of max shard size %s bytes. It will "
"be added as an individual shard that exceeds the max shard "
"size.", self._checkpoint_key, self._dtype, total_size,
self.max_shard_size)
... |
combine_chunk_391850 | combine.txt | 391,850 | 512 | _slice_spec]) = working_tensor
self._shard_size_remaining -= working_tensor_size
shards = []
if self._tensors_by_shard[0]:
shards.extend(self._tensors_by_shard)
shards.extend(self._large_scalars)
return shards
def __init__(self, max_shard_size: int):
self.max_shard_size ... |
combine_chunk_391851 | combine.txt | 391,851 | 512 | object_identity
class CheckpointPosition(object):
"""Indicates a position within a `_CheckpointRestoreCoordinator`."""
__slots__ = ["_checkpoint", "_proto_id", "skip_restore", "callback"]
def __init__(self, checkpoint, proto_id):
"""Specify an object within a checkpoint.
Args:
checkpoint: A _C... |
combine_chunk_391852 | combine.txt | 391,852 | 512 | .weight` reference the "
"same variable, while in the current object these are two different"
" variables. The referenced variables are:"
f"({current_assignment} and {trackable}).")
return False # Not a new assignment
def update_resharding_callback(
self, callback: ch... |
combine_chunk_391853 | combine.txt | 391,853 | 512 |
and serialized_tensor.name in shape_and_slices
):
shape_and_slice = shape_and_slices[serialized_tensor.name]
else:
shape_and_slice = ""
checkpoint_keys, full_shape_and_slices = (
self.callback.update_restore_inputs(
che... |
combine_chunk_391854 | combine.txt | 391,854 | 512 | ).
# Set the Trackable's object name to the first checkpoint key that is
# stored in checkpoint. If there is a use case that requires the other
# keys, then we can take another look at this.
registered_savers[saver_name] = {
self.object_proto.attributes[0].checkpoint_key: self.trackab... |
combine_chunk_391855 | combine.txt | 391,855 | 512 | able_name] = saveable
return [], {saveable_name: saveable}
def _create_saveables_by_attribute_name(self, saveable_factories):
"""Creates or caches SaveableObjects by matching the attribute names.
The attribute name keys in the `saveable_factories` is used to find the
corresponding attribute in the o... |
combine_chunk_391856 | combine.txt | 391,856 | 512 | = saveable_list
else:
# Don't use cached SaveableObjects for partitioned variables, which is
# the only case where we'd have a list of SaveableObjects. Op caching
# will catch them.
saveable = None
if saveable is not None:
# The name of this attribute has c... |
combine_chunk_391857 | combine.txt | 391,857 | 512 | self._checkpoint.object_by_proto_id[self._proto_id]
@property
def object_proto(self):
return self._checkpoint.object_graph_proto.nodes[self._proto_id]
@property
def proto_id(self):
return self._proto_id
@property
def restore_uid(self):
return self._checkpoint.restore_uid
def __repr__(self... |
combine_chunk_391858 | combine.txt | 391,858 | 512 | for optimizer_v2 objects.
slot_variable_position.update_resharding_callback(reshard_callback)
slot_variable = optimizer_object._create_or_restore_slot_variable(
slot_variable_position=slot_variable_position,
variable=variable,
slot_name=slot_name,
slot_variable_shape... |
combine_chunk_391859 | combine.txt | 391,859 | 512 | _queue_children_for_restoration(current_position, visit_queue)
_queue_slot_variables(current_position, visit_queue)
restore_ops.extend(
current_position.checkpoint.restore_saveables(
tensor_saveables, python_positions, registered_savers, reader=reader
)
)
return rest... |
combine_chunk_391860 | combine.txt | 391,860 | 512 | restore is empty.
if trackable is None or not isinstance(trackable, base.Trackable):
raise ValueError(
f"Expecting a valid Trackable to node_id: {node_id} but got "
f"trackable: {trackable}."
)
serialized_tensors = object_identity.ObjectIdentityDictionary()
for node_id, current... |
combine_chunk_391861 | combine.txt | 391,861 | 512 | if not trackable_expects_ckpted_value and ckpt_contains_serialized_tensors:
raise ValueError(
f"Trackable {current_trackable} does not expect checkpointed "
"values but checkpoint contains serialized tensors: "
f"{ckpt_contains_serialized_tensors} for node_id: {node_id}.")
if l... |
combine_chunk_391862 | combine.txt | 391,862 | 512 | .local_name,
trackable_children)
child_proto = child_position.object_proto
if local_object is None:
# We don't yet have a dependency registered with this name. Save it
# in case we do.
if child_proto.HasField("has_checkpoint_values"):
has... |
combine_chunk_391863 | combine.txt | 391,863 | 512 | if slot_variable_position is not None:
visit_queue.append((slot_variable_position, slot_variable))
for slot_restoration in checkpoint.slot_restorations.pop(
checkpoint_position.proto_id, ()):
optimizer_object = checkpoint.object_by_proto_id.get(
slot_restoration.optimizer_id, None)
if ... |
combine_chunk_391864 | combine.txt | 391,864 | 512 | : the name already exactly matches a key in saveable_factories.
if expected_factory_name in saveable_factories:
matched_factory = saveable_factories[expected_factory_name]
# Case 2: (Forward compat) The serialized name is composed of
# "factory_name" + "SUFFIX". Get the matching factory name.
if matched_fa... |
combine_chunk_391865 | combine.txt | 391,865 | 512 | ()
for trackable in non_slot_objects:
# TODO(b/110718070): Fix Keras imports.
# Note: dir() is used rather than hasattr() here to avoid triggering
# custom __getattr__ code, see b/152031870 for context.
if "get_slot_names" in dir(trackable):
slot_names = trackable.get_slot_names()
... |
combine_chunk_391866 | combine.txt | 391,866 | 512 | pylint: disable=protected-access
if (not (isinstance(var, variables.Variable) or
# Some objects do not subclass Variable but still act as one.
resource_variable_ops.is_resource_variable(var))):
return ""
if getattr(var, "_save_slice_info", None) is not None:
# Use getattr because `va... |
combine_chunk_391867 | combine.txt | 391,867 | 512 | which are dependencies of
`root_trackable`. Includes slot variables only if the variable they are
slotting for and the optimizer are dependencies of `root_trackable`
(i.e. if they would be saved with a checkpoint).
Args:
graph_view: A GraphView object.
skip_slot_variables: If True does not return trac... |
combine_chunk_391868 | combine.txt | 391,868 | 512 | def value(self) -> bool: ...
class Flags:
enable_aggressive_constant_replication: Flag
enable_colocation_key_propagation_in_while_op_lowering: Flag
enable_fatal_error_on_collective_abort: Flag
enable_function_pruning_before_inlining: Flag
enable_graph_debug_info_caching_for_stack_frames: Flag
... |
combine_chunk_391869 | combine.txt | 391,869 | 512 | in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either... |
combine_chunk_391870 | combine.txt | 391,870 | 512 | arding import sharding_util
from tensorflow.python.checkpoint.sharding import sharding_policies
# Compat
from tensorflow.python.compat import v2_compat
# Compiler
from tensorflow.python.compiler.xla import jit
from tensorflow.python.compiler.xla import xla
from tensorflow.python.compiler.mlir import mlir
# Data
from... |
combine_chunk_391871 | combine.txt | 391,871 | 512 | import gen_sendrecv_ops
from tensorflow.python.ops import gen_tpu_ops
from tensorflow.python.ops import gen_uniform_quant_ops
from tensorflow.python.ops import gradient_checker_v2
from tensorflow.python.ops import image_ops as image
from tensorflow.python.ops import initializers_ns as initializers
from tensorflow.pyth... |
combine_chunk_391872 | combine.txt | 391,872 | 512 | profiler_v2
from tensorflow.python.profiler import trace
# Saved Model
from tensorflow.python.saved_model import saved_model
# Session
from tensorflow.python.client.client_lib import *
# Summary
from tensorflow.python.summary import summary
from tensorflow.python.summary import tb_summary
# TPU
from tensorflow.pyt... |
combine_chunk_391873 | combine.txt | 391,873 | 512 | implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Logging tensorflow::tfprof::OpLogProto.
OpLogProto is used to add extra model information for offline analysis.
"""
import... |
combine_chunk_391874 | combine.txt | 391,874 | 512 | _meta: RunMetadata proto used to complete shape information.
add_trace: Whether to add op trace information.
add_trainable_var: Whether to assign tf.compat.v1.trainable_variables() op
type '_trainable_variables'.
Returns:
logged_ops: dict mapping from op_name to OpLogEntry.
string_to_id: dict ma... |
combine_chunk_391875 | combine.txt | 391,875 | 512 | _meta:
sys.stderr.write('%d ops no flops stats due to incomplete shapes.\n' %
op_missing_shape)
return logged_ops, string_to_id
def merge_default_with_oplog(graph, op_log=None, run_meta=None,
add_trace=True, add_trainable_var=True):
"""Merge the tfprof default... |
combine_chunk_391876 | combine.txt | 391,876 | 512 | an op type
called '_trainable_variables'.
The API also logs 'flops' statistics for ops with op.RegisterStatistics()
defined. flops calculation depends on Tensor shapes defined in 'graph',
which might not be complete. 'run_meta', if provided, completes the shape
information with best effort.
Args... |
combine_chunk_391877 | combine.txt | 391,877 | 512 | sess:
...
sess.run(computation, run_metadata=run_metadata, options=options)
pprof_profiler.profile(sess.graph, run_metadata, output_dir)
The code above would output a pprof profile to separate output_dir/.*.pb.gz
file for each device. These files can be passed to pprof for formatting.
For e.g.:
... |
combine_chunk_391878 | combine.txt | 391,878 | 512 | string_table: A `StringTable` object.
"""
self._string_table = string_table
# Maps tuples in the form (file_path, function_name, start_line_number)
# to `Function` protos.
self._function_key_to_function = {}
def index_of(self, file_path, function_name, function_start_line):
"""Returns index ... |
combine_chunk_391879 | combine.txt | 391,879 | 512 | _file_path: (string) Path to file where the called function is
defined.
called_function_start_line: (integer) Start line number of called
function definition in `called_file_path` file.
Returns:
Index of location.
"""
location_key = (file_path, called_function_name, line_number)... |
combine_chunk_391880 | combine.txt | 391,880 | 512 | string_table.index_of(node_name)
label = sample.label.add()
label.key = self._string_table.index_of('op_type')
label.str = self._string_table.index_of(datum.op_type)
self._node_name_to_sample[node_name] = sample
sample.value[0] += 1
sample.value[1] += datum.node_exec_stats.all_end_rel_mi... |
combine_chunk_391881 | combine.txt | 391,881 | 512 | profile data in pprof proto format.
Args:
profile_datum_generator: Generator outputting `ProfileDatum` objects.
Returns:
A proto in pprof format.
"""
pprof_profile = profile_pb2.Profile()
samples = Samples(self._string_table)
for datum in profile_datum_generator:
if not dat... |
combine_chunk_391882 | combine.txt | 391,882 | 512 | _get_profile_data_generator(self):
"""Get function that generates `ProfileDatum` objects.
Returns:
A function that generates `ProfileDatum` objects.
"""
node_to_traceback = defaultdict(list)
node_to_op_type = defaultdict(str)
for op in self._graph.get_operations():
node_to_tracebac... |
combine_chunk_391883 | combine.txt | 391,883 | 512 | directory specified, printing to stdout instead.')
print(pprof_proto)
else:
device_name = str(device).strip('/').translate(
maketrans('/:', '__'))
profile_file = output_file_template % device_name
profile_files.append(profile_file)
with gzip.open(profile_file, 'w') as output... |
combine_chunk_391884 | combine.txt | 391,884 | 512 | all ops which have implemented flops statistics.
IMPLEMENTED_OPS = set([
# Unary ops
"Reciprocal", "Square", "Rsqrt", "Log", "Neg", "AssignSub", "AssignAdd",
"L2Loss", "Softmax",
# Binary ops
"Add", "Sub", "Mul", "RealDiv", "Maximum", "Minimum", "Pow", "RsqrtGrad",
"GreaterEqual", "Greater", "L... |
combine_chunk_391885 | combine.txt | 391,885 | 512 | Compute flops for Rsqrt operation."""
# Rsqrt(x) = 1 / sqrt(x)
return _unary_op_flops(graph, node, ops_per_element=2)
@ops.RegisterStatistics("Log", "flops")
def _log_flops(graph, node):
"""Compute flops for Log operation."""
return _unary_op_flops(graph, node)
@ops.RegisterStatistics("Neg", "flops")
def _n... |
combine_chunk_391886 | combine.txt | 391,886 | 512 | Statistics("Add", "flops")
@ops.RegisterStatistics("AddV2", "flops")
def _add_flops(graph, node):
"""Compute flops for Add operation."""
return _binary_per_element_op_flops(graph, node)
@ops.RegisterStatistics("Sub", "flops")
def _sub_flops(graph, node):
"""Compute flops for Sub operation."""
return _binary_p... |
combine_chunk_391887 | combine.txt | 391,887 | 512 | ):
"""Compute flops for Less operation."""
return _binary_per_element_op_flops(graph, node)
@ops.RegisterStatistics("Equal", "flops")
def _equal_flops(graph, node):
"""Compute flops for Equal operation."""
return _binary_per_element_op_flops(graph, node)
@ops.RegisterStatistics("NotEqual", "flops")
def _not... |
combine_chunk_391888 | combine.txt | 391,888 | 512 | arg_min_flops(graph, node):
"""Compute flops for ArgMin operation."""
# reduction - comparison, no finalization
return _reduction_op_flops(graph, node, reduce_flops=1, finalize_flops=0)
@ops.RegisterStatistics("BiasAddGrad", "flops")
def _bias_add_grad_flops(graph, node):
"""Compute flops for BiasAddGrad oper... |
combine_chunk_391889 | combine.txt | 391,889 | 512 | (graph, node):
"""Compute flops for AvgPoolGrad operation."""
_verify_conv_data_format(node)
# Pooling gradient implementation:
out_backprop_shape = graph_util.tensor_shape_from_node_def_name(graph,
node.input[1])
out_backprop_shape.assert_is_f... |
combine_chunk_391890 | combine.txt | 391,890 | 512 | #
# Where:
# image_x_dim, image_y_dim and input_depth --- size of input to source (no
# backprop) convolution, in other words they are sizes of backprop output.
# output_depth --- number of filters in the original convolution, thus
# depth of backprop input.
# kernel_x_dim and kernel_y_dim --- sizes of... |
combine_chunk_391891 | combine.txt | 391,891 | 512 | * strides_shape[2]
return ops.OpStats("flops",
(2 * image_shape.num_elements()
* kernel_shape.num_elements()
/ (image_shape.dims[-1].value * strides_product)))
################################################################################
# Other op... |
combine_chunk_391892 | combine.txt | 391,892 | 512 | _analyzer_testlib.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unles... |
combine_chunk_391893 | combine.txt | 391,893 | 512 | FullModel():
"""Build the full model with conv,rnn,opt."""
seq = []
for i in range(4):
with variable_scope.variable_scope('inp_%d' % i):
seq.append(array_ops.reshape(BuildSmallModel(), [2, 1, -1]))
cell = rnn_cell.BasicRNNCell(16)
out = rnn.dynamic_rnn(
cell, array_ops.concat(seq, axis=1), dt... |
combine_chunk_391894 | combine.txt | 391,894 | 512 | return profile[start_pos + 9:]
<|file|>tensorflow/tensorflow/python/profiler/internal/_pywrap_traceme.pyi
# Copyright 2023 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obta... |
combine_chunk_391895 | combine.txt | 391,895 | 512 | .
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the ... |
combine_chunk_391896 | combine.txt | 391,896 | 512 | arguments fail validation checks.
UnavailableError: If no trace event was collected.
Example usage (CPU/GPU):
```python
# Start a profiler server before your model runs.
tf.profiler.experimental.server.start(6009)
# (Model code goes here).
# Send gRPC request to the profiler server to collect... |
combine_chunk_391897 | combine.txt | 391,897 | 512 | :8466',
'gs://your_tb_dir',
2000,
'10.0.0.2:8466,10.0.0.3:8466,10.0.0.4:8466')
```
Launch TensorBoard and point it to the same logdir you provided to this API.
```shell
# logdir can be gs://your_tb_dir as in the above examples.
$ tensorboard --logdir=/tmp/tb_log
```
Open you... |
combine_chunk_391898 | combine.txt | 391,898 | 512 | f'service_addr must be a string, but got {type(service_addr).__name__}.'
)
return _pywrap_profiler_plugin.monitor(
_strip_prefix(service_addr, _GRPC_PREFIX), duration_ms, level, True
)
def _strip_prefix(s, prefix):
return s[len(prefix):] if s.startswith(prefix) else s
def _strip_addresses(addresses... |
combine_chunk_391899 | combine.txt | 391,899 | 512 | .experimental.stop()
```
"""
def __init__(self, name, **kwargs):
"""Creates a trace event in the profiler.
Args:
name: The name of the trace event.
**kwargs: Keyword arguments added to the trace event.
Both the key and value are of types that
can be converted ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.