code stringlengths 17 6.64M |
|---|
def convert_handle_missing_print(bins, graph, verbose=False):
node_to_stage_map = {}
stage_to_gpu_map = defaultdict(set)
for (gpu_id, bin_nodes) in bins.items():
for n in bin_nodes:
n: Node
stage_to_gpu_map[n.stage_id].add(gpu_id)
node_to_stage_map[n.id] = n.sta... |
def handle_missing_stages(bins, graph, node_to_stage_map, stage_to_gpu_map):
to_check = sorted(stage_to_gpu_map.keys())
if ((to_check[0] != 0) or (to_check[(- 1)] != (len(to_check) - 1))):
print(f'-V- stages gone, stages_ids_before: {to_check} reassigning...')
stage_to_fixed = {prev_s: i for (... |
def _lworker(args):
(times, work_graph, best_objective) = lworker(*args)
return (times, work_graph.state(), best_objective)
|
def lworker(model, L, P, edge_weight_function, node_weight_function, round_limit, saved_work_graph_without_par_edges, node_mem_estimator: NodeMemoryEstimator, basic_blocks, special_blocks, depth):
work_graph = Graph.from_state(saved_work_graph_without_par_edges)
hierarchy = coarsening(model, work_graph, edge_... |
def partition_mpipe(model, graph: Graph, num_gpus: int, node_weight_function: Optional[NodeWeightFunction]=None, edge_weight_function: Optional[EdgeWeightFunction]=None, node_mem_estimator: NodeMemoryEstimator=NodeMemoryEstimator(), use_layers_graph: bool=True, round_limit=(- 1), nprocs=1, L_list=None, basic_blocks=(... |
def main():
from autopipe.autopipe.api import build_profiled_graph
import torch
from torch.nn import Sequential, Linear
IN_FEATURES = 320
OUT_FEATURES = 8
n_encoder_decoder = 12
l = []
for i in range(n_encoder_decoder):
l.append(Linear(IN_FEATURES, IN_FEATURES))
l.append(Li... |
def post_process_partition(graph: Graph, edge_weight_function=None, verbose_on_error=True, assert_output_types=False, verbose_check_outputs=False) -> Graph:
"\n process the partition and optimize it\n called as part of partition_graph method\n\n Parameters:\n ----------\n graph:\n the Graph ... |
def check_partition_outputs(graph, assert_output_types=False, edge_weight_function=None, verbose=True):
(is_valid, error) = is_output_only_tensors(graph, edge_weight_function)
if assert_output_types:
assert is_valid, error
elif ((not is_valid) and verbose):
print('Output between partitions... |
def get_problematic_partitions(graph):
' For debug when cycle are detected '
problems = []
info = []
for u in graph.nodes:
for v in u.out_edges:
if (v.stage_id < u.stage_id):
problems.append([u.stage_id, v.stage_id])
info.append([(u.id, u.stage_id, u... |
def is_output_only_tensors(graph: Graph, edge_weight_function=None):
'\n check if we only send tensors between partitions\n '
for n in graph.nodes:
if (n.value_type in {type(None), list, tuple, dict, set, int, bool, float, str, slice, torch.Size, torch.dtype}):
for o in n.out_edges:
... |
def print_all_problematic_outputs_between_partitions(graph: Graph, edge_weight_function=None):
'\n check if we only send tensors between partitions\n '
problems = []
valid_state = True
for n in graph.nodes:
if (n.value_type in {type(None), list, tuple, dict, set, int, bool, float, str, s... |
class Refiner():
def __init__(self, graph: Graph, node_weight_function: NodeWeightFunction, edge_weight_function: EdgeWeightFunction):
u = graph.unique_partitions_ids
if (None in u):
raise NotImplementedError('please remove None stage_id')
n_stages = len(u)
assert (min... |
def refine(graph: Graph, node_weight_function: NodeWeightFunction, edge_weight_function: EdgeWeightFunction, round_limit=(- 1)):
re_assign_partition_indices(graph)
refiner = Refiner(graph, node_weight_function, edge_weight_function)
rounds = 0
num_moved = 1
total_moves = 0
while ((num_moved > ... |
class RatioBlockCreator():
def __init__(self, graph: Graph, edge_weight_function: EdgeWeightFunction, node_weight_function: NodeWeightFunction, uf: UnionFind):
self.graph = graph
self.ewf = edge_weight_function
self.nwf = node_weight_function
self.cwf = CoarsenedWeightFunction(edg... |
class C1(nn.Module):
def __init__(self):
super().__init__()
self.layer1 = torch.nn.Linear(10, 10)
self.dropout = nn.Dropout(0.5, inplace=False)
self.layer2 = torch.nn.Linear(10, 10)
def forward(self, x):
x = self.layer1(x)
x = self.dropout(x)
x = self.... |
class MyTestCase(unittest.TestCase):
def test_something(self):
depth = 1000
model_args = (torch.randn((1, 10)),)
model = nn.Sequential(C1(), C1(), C1())
graph: Graph = build_profiled_graph(model, model_args=model_args, n_iter=1, max_depth=depth)
args = SimpleNamespace(bwd_... |
def calc_data_parall_comm_time_orig(num_machines, total_parameter_size, network_bandwidth):
return (((4 * (num_machines - 1)) * total_parameter_size) / (network_bandwidth * num_machines))
|
def calc_data_parall_comm_time_fixed(num_machines, total_parameter_size, network_bandwidth):
return (2 * (((4 * (num_machines - 1)) * total_parameter_size) / network_bandwidth))
|
def partition_pipedream(graph: Graph, num_gpus: int, node_weight_function: Optional[NodeWeightFunction]=None, edge_weight_function: Optional[EdgeWeightFunction]=None, use_layers_graph: bool=True, num_machines_in_first_level=None, memory_size=10000000000.0, verbose=True, force_stright_pipeline=True, node_mem_estimator... |
def calc_data_parall_comm_time_orig(num_machines, total_parameter_size, network_bandwidth):
return (((4 * (num_machines - 1)) * total_parameter_size) / (network_bandwidth * num_machines))
|
def calc_data_parall_comm_time_fixed(num_machines, total_parameter_size, network_bandwidth):
return (2 * (((4 * (num_machines - 1)) * total_parameter_size) / network_bandwidth))
|
def partition_pipedream(graph: Graph, num_gpus: int, node_weight_function: Optional[NodeWeightFunction]=None, edge_weight_function: Optional[EdgeWeightFunction]=None, use_layers_graph: bool=True, num_machines_in_first_level=None, verbose=True, force_stright_pipeline=True):
print('PipeDream Partitioning')
num_... |
def gen_stage_to_device_map(graph) -> List[int]:
'\n Args:\n graph:\n\n Returns:\n l[i] = k => stage i is on device k\n\n # HACKY lazy code copy pasta\n # TODO: can also calculate number of dummy stages per GPU.\n '
analysis_kwargs = {}
gpu_to_stages = defaultdict(set)
sta... |
def sorted_stage_to_device_map(n_partitions, stages_on_same_gpu):
pipeline_representation_stage_to_device_map = list()
for stage_id in range(n_partitions):
seen_devices = set()
if (stage_id in stages_on_same_gpu):
device_id = min(stages_on_same_gpu[stage_id])
else:
... |
def re_assign_partition_indices(graph: Graph):
out_edges = defaultdict(set)
for node in graph.non_input_nodes:
assert (node.stage_id is not None)
for o in node.out_edges:
assert (o.stage_id is not None)
out_edges[node.stage_id].add(o.stage_id)
for (i, e) in out_edge... |
def topological_sort(out_edges: Dict[(int, Set[int])]) -> List[int]:
visited = {i: False for i in out_edges}
for v in list(out_edges.values()):
for x in v:
if (x not in visited):
print(f'stage {x} is probably a sink')
visited[x] = False
out_e... |
def _topological_sort(out_edges: Dict[(int, Set[int])], v: int, visited: Dict[(int, bool)], stack: List[int]):
visited[v] = True
for i in out_edges[v]:
if (not visited[i]):
_topological_sort(out_edges, i, visited, stack)
stack.insert(0, v)
|
def has_stage_cycles(graph: Graph) -> bool:
for u in graph.non_input_nodes:
for v in u.out_edges:
if (v.stage_id < u.stage_id):
return True
return False
|
class NodeTypes(IntEnum):
'\n Enum representing the possible types of Nodes in the Graph\n '
IN = 1
BUFF_PARAM = 2
LAYER = 3
OP = 4
CONSTANT = 5
PRIMITIVE = 6
def __repr__(self):
return self.name
|
class Node():
def __init__(self, node_type: NodeTypes, idx, scope: str):
assert (scope is not None)
self.type = node_type
self.id = idx
self.scope = scope
self.scope_to_hold_to: Union[(str, None)] = None
self.topo_sort_id = idx
self.stage_id = 0
sel... |
class Graph():
def __init__(self, nodes: Optional[GraphNodes], input_kw_ids: Optional[Dict[(int, str)]], output_ids: Optional[List[int]], depth: Optional[int], basic_blocks: Optional[Tuple[(Type[nn.Module], ...)]]):
self._nodes: GraphNodes = nodes
self.input_kw_ids = input_kw_ids
self.out... |
def remove_dups(lnodes: List[Node], myself):
s = set(lnodes)
if (myself in s):
s.remove(myself)
return sorted(s, key=(lambda x: x.topo_sort_id))
|
class PreHook(abc.ABC):
'\n pre hook will be called before the node executes and should have the following signature\n\n def hook (node: Node, function: Callable, args: tuple, kwargs: dict) -> Tuple[Optional[Tuple], Optional[Dict]]:\n\n the hook can modify the args/kwargs or return None\n '
@abc.... |
class PostHook(abc.ABC):
'\n posthook will be called after the node executes and should have the following signature\n\n def hook (node: Node, function: Callable, args: tuple, kwargs: dict,outputs) ->Optional:\n\n the hook can modify the output or return None\n '
@abc.abstractmethod
def __cal... |
def pre_hook_factory(fn) -> PreHook:
class FunctionalPreHook(PreHook):
def __call__(self, *args, **kwargs):
return fn(*args, **kwargs)
return FunctionalPreHook()
|
def post_hook_factory(fn) -> PostHook:
class FunctionalPostHook(PostHook):
def __call__(self, *args, **kwargs):
return fn(*args, **kwargs)
return FunctionalPostHook()
|
def execute_graph(model: nn.Module, graph: Graph, model_args=(), model_kwargs=None, pre_hook: Optional[PreHook]=None, post_hook: Optional[PostHook]=None, enforce_out_of_place=True):
if (model_kwargs is None):
model_kwargs = dict()
if (not isinstance(model_args, tuple)):
model_args = (model_arg... |
def create_container_construct(node, args, kwargs):
if ('prim::DictConstruct' in node.scope):
return kwargs
elif ('prim::SetConstruct' in node.scope):
return set(args)
elif ('prim::ListConstruct' in node.scope):
return list(args)
elif ('prim::TupleConstruct' in node.scope):
... |
def call_function(namespaces, node, args, kwargs, pre_hook, post_hook, enforce_out_of_place=True):
(op_path, idx) = node.scope.rsplit('/', maxsplit=1)[1].rsplit('_', maxsplit=1)
(namespace, func_name) = op_path.split('::')
forced_out_of_place = (enforce_out_of_place and (node.type is NodeTypes.OP))
if... |
def fetch_args_kwargs(node, ready_expressions):
args = [ready_expressions[n] for n in node.args]
kwargs = dict()
for (n, kws) in node.kwargs.items():
for k in kws:
kwargs[k] = ready_expressions[n]
return (args, kwargs)
|
def apply_pre_hook(pre_hook):
@wraps(pre_hook)
def wrapper(node: Node, function: Callable, args: tuple, kwargs: dict):
(modified_args, modified_kwargs) = pre_hook(node, function, args, kwargs)
if (not (modified_args is None)):
args = modified_args
if (not (modified_kwargs ... |
def apply_post_hook(post_hook):
@wraps(post_hook)
def wrapper(node: Node, function: Callable, args: tuple, kwargs: dict, outputs):
modified_outputs = post_hook(node, function, args, kwargs, outputs)
if (not (modified_outputs is None)):
outputs = modified_outputs
return out... |
class IdentityPreHook(PreHook):
def __call__(self, node: Node, function: Callable, args: tuple, kwargs: dict) -> Tuple[(Optional[Tuple], Optional[Dict])]:
return (args, kwargs)
|
class IdentityPostHook(PostHook):
def __call__(self, node: Node, function: Callable, args: tuple, kwargs: Dict, outputs: Any) -> Optional:
return outputs
|
def infer_is_contiguous(graph: Graph, model: torch.nn.Module, args=None, kwargs=None):
if (args is None):
args = ()
if (kwargs is None):
kwargs = dict()
with torch.no_grad():
visitor = Visitor()
execute_graph(model, graph, model_args=args, model_kwargs=kwargs, pre_hook=pre_... |
class Visitor():
def prehook(self, node: Node, function: Callable, args: tuple, kwargs: Dict):
for (n, a) in zip(node.args, args):
n.is_contiguous = (n.is_contiguous or Visitor.is_contiguous(a))
for (n, kws) in node.kwargs.items():
v = kwargs[kws[0]]
n.is_conti... |
def infer_req_grad(graph: Graph, model: torch.nn.Module, args=None, kwargs=None):
if (args is None):
args = ()
if (kwargs is None):
kwargs = dict()
with torch.enable_grad():
visitor = Visitor()
execute_graph(model, graph, model_args=args, model_kwargs=kwargs, pre_hook=pre_h... |
class Visitor():
def prehook(self, node: Node, function: Callable, args: tuple, kwargs: Dict):
for (n, a) in zip(node.args, args):
n.req_grad = (n.req_grad or Visitor.req_grad(a))
for (n, kws) in node.kwargs.items():
v = kwargs[kws[0]]
n.req_grad = (n.req_grad ... |
def profile_network(net: nn.Module, sample_batch: tuple=(), kwargs: Optional[Dict]=None, basic_blocks: Optional[List[nn.Module]]=None, max_depth=100, n_iter=10, save_memory_mode=False, recomputation=False, force_no_recomp_scopes=None) -> Dict[(str, ExecTimes)]:
"\n profiles a network's computation time(forward... |
def _perform_forward_backward_pass(net, *sample_batch: tuple, save_memory_mode=False, **kwargs: Dict):
if save_memory_mode:
device = torch.device('cuda')
else:
device = get_device((sample_batch, kwargs))
if (device.type == 'cuda'):
torch.cuda.synchronize(device=device)
out ... |
def _wrap_profiled_layers(module: nn.Module, depth, basic_blocks: List[nn.Module], save_memory_mode=False, recomputation=False, force_no_recomp_scopes=(lambda s: False)):
layers_dict = {}
for (sub_layer, scope, parent) in traverse_model(module, depth, basic_blocks=basic_blocks):
name = scope[(scope.rf... |
def _unwrap_layers(module: nn.Module):
for (name, sub_module) in module.named_children():
if isinstance(sub_module, Wrapper):
sub_module.on_unwrap()
module.add_module(name, sub_module.layer)
else:
_unwrap_layers(sub_module)
|
class Wrapper(nn.Module):
'\n A module whose purpose is to profile a given layer\n when the wrapper performs forward propagation it records the following metrics:\n forward_time: the execution time of a forward pass of the underlying layer in milliseconds\n backward_time: the execution time of... |
def time_op(device, func, *inputs: tuple, **kwargs):
cuda_mem = 0
if (device.type == 'cuda'):
torch.cuda.reset_max_memory_allocated(device=device)
base_mem = torch.cuda.memory_allocated(device=device)
start = torch.cuda.Event(enable_timing=True)
end = torch.cuda.Event(enable_ti... |
def avg_time(times):
max_v = max(times)
return (sum([t for t in times if (t < max_v)]) / (len(times) - 1))
|
def set_req_grad_for_parameters(ts):
' For model parameters which are sent across the pipeline, grad requirements at profiling are always true\n # TODO: support freezing\n '
def f(t):
if (not isinstance(t, torch.Tensor)):
return t
req_grad = (t.requires_grad if isinstanc... |
class GraphProfiler():
def __init__(self, recomputation=False, n_iter=10, force_no_recomp_scopes=None, profile_ops=True, save_memory_mode=False):
self.profile_memory = save_memory_mode
if (not save_memory_mode):
warnings.warn('Will not profile memory (since save_memory_mode=False)')
... |
class TracedFunctions():
functions = set()
@classmethod
def register_function(cls, function, namespace):
assert hasattr(namespace, function.__name__)
traced_function = TracedFunction(namespace, function)
cls.functions.add(traced_function)
@classmethod
def enable_tracing(c... |
class ExplicitUntracedFunctions():
functions = set()
@classmethod
def register_function(cls, function, namespace):
assert hasattr(namespace, function.__name__)
traced_function = ExplicitUntracedFunction(namespace, function)
cls.functions.add(traced_function)
@classmethod
... |
class ExplicitUntracedFunction():
"\n a Wrapper of an arbitrary static function\n which will not be recorded.\n it will not record it's inputs or outputs\n "
def __init__(self, namespace, original_function):
self.namespace = namespace
self.original_function = original_function
... |
class TracedFunction():
'\n a Wrapper of an arbitrary static function\n like torch.zeros or math.sqrt which are not invoked from a traced value\n the wrapper records the function call and return a TracedValue\n '
def __init__(self, namespace, original_function):
self.namespace = namespace... |
def used_namespaces():
return {namespace.__name__ for namespace in chain(override_dict.keys(), TracedFunctions.traced_namespaces()) if (hasattr(namespace, '__name__') and inspect.ismodule(namespace))}
|
def delegate_to_traced_value(func):
@wraps(func)
def wrapper(*args):
(args, _) = record_args_and_kwargs(*args)
op_name = func.__name__
if (op_name in r_arithmetic_ops):
op_name = ('__' + op_name[3:])
args = tuple(reversed(args))
traced_self = args[0]
... |
def tracing_not_supported(func):
'a decortaor to have pretty error messages when accessing an unsupported\n __magic__ method\n '
@wraps(func)
def wrapper(*args, **kwargs):
namespace = type(args[0]._data).__name__
op = func.__name__
msg = f'tracing {namespace}::{op} is curren... |
class TracedValue(object):
'\n a wrapper that traces operations done on a value\n for Tensor values we leverage the __torch_function__ API\n for other values we trace all instance methods invoked\n and methods that are patched in enable_tracing_registered_functions\n\n functions and attributes are ... |
class TracedInstanceFunction(object):
"when we call a function what happens is obj.__getattribute__(self,func_name)(self,*args,**kwargs)\n TracedInstanceFunction is used to record the call operation and it's output\n obj.__getattribute__(self,func_name) returns a TracedInstanceFunction object\n ... |
class TracedLayer(nn.Module):
' Traced layer is a wrapper around all model layers used for tracing operations\n a traced layer can be terminal as is a layer which will be profiled according to depth and basic blocks\n and a non terminal layer which is not profiled but still traced\n\n termina... |
def is_traceable(data):
'\n predicate to check if a value can be traced\n '
return isinstance(data, (type(None), type(Ellipsis), list, tuple, dict, set, int, bool, str, float, slice, torch.device, torch.Size, torch.Tensor, torch.dtype, torch.memory_format))
|
def trace_module(module: nn.Module, args=(), kwargs=None, depth=1000, basic_blocks=()):
if (basic_blocks is None):
basic_blocks = ()
if (kwargs is None):
kwargs = dict()
reset_tracing_state()
_unwrap_layers(module)
(args, kwargs) = prepare_args_and_kwargs(args=args, kwargs=kwargs)
... |
def find_reachable_nodes(nodes, output_id, keep_tensors=False):
'do a bfs from the output on the undirected graph to find all nodes that are \n reachable from the output node this is really conservative some unused nodes will still remain\n '
open = {nodes[output_id]}
reachable = set()
while ope... |
def prepare_args_and_kwargs(args=(), kwargs=None):
if (not isinstance(args, tuple)):
args = (args,)
if (kwargs is None):
kwargs = dict()
wrapped_args = []
for (idx, a) in enumerate(args):
v = TracedValue(NodeTypes.IN, f'input{idx}')
v.set_data(a)
wrapped_args.ap... |
def register_new_traced_function(function, namespace):
TracedFunctions.register_function(function, namespace)
|
def register_new_explicit_untraced_function(function, namespace):
ExplicitUntracedFunctions.register_function(function, namespace)
|
def register_torch_functions():
for (f, namespace) in tensor_creation_ops.items():
register_new_traced_function(f, namespace=namespace)
|
def enable_tracing_registered_functions():
'enable tracing of functions registered functions\n '
register_torch_functions()
TracedFunctions.enable_tracing()
global FUNCTION_NAMESPACE
FUNCTION_NAMESPACE = {f: ns for (ns, funcs) in override_dict.items() for f in funcs}
|
def disable_tracing_registered_functions():
'revert the patching done by enable_tracing_registered_functions\n '
FUNCTION_NAMESPACE.clear()
TracedFunctions.disable_tracing()
|
def _wrap_traced_layers(module: nn.Module, depth=1000, basic_blocks=(), allow_ModuleList_ModuleDict=True):
layers_dict = dict()
layers_to_patch = dict()
patched_layers_to_scope = dict()
for (sub_layer, scope, parent, terminal) in traverse_model(module, depth=depth, basic_blocks=basic_blocks, full=True... |
def _unwrap_layers(module: nn.Module):
for (name, sub_module) in module.named_children():
if isinstance(sub_module, TracedLayer):
_unwrap_layers(sub_module._module)
module.add_module(name, sub_module._module)
else:
module.add_module(name, sub_module)
|
def reset_tracing_state():
global CURRENT_SCOPE
CURRENT_SCOPE = ''
disable_tracing_registered_functions()
ExplicitUntracedFunctions.disable()
NODES.clear()
FUNCTION_NAMESPACE.clear()
TracedValue.ID = 0
|
def duplicate_constants(nodes, output_id):
new_nodes = dict()
offset = 0
new_output_id = 0
for node in nodes.values():
if (node.id == output_id):
new_output_id = (node.id + offset)
node.id += offset
if ((node.type is NodeTypes.CONSTANT) and (len(node.out_edges) > 1)... |
def discard_unused_nodes(nodes, output_id):
new_nodes = []
while True:
changed = False
reachable_nodes = find_reachable_nodes(nodes, output_id)
for node in reversed(list(nodes.values())):
if (node.id == output_id):
new_nodes.append((node.id, node))
... |
def propagate_constant_tuple_accessors(nodes):
while True:
changed = False
for n in nodes.values():
if ('prim::TupleConstruct' in n.scope):
tuple_elements = n.in_edges
for o in n.out_edges:
if (('tuple::__getitem__' in o.scope) and (o... |
def maybe_make_constant(node, data):
can_convert = False
if (isinstance(data, torch.device) or (data == 'cpu') or (isinstance(data, str) and ('cuda' in data))):
data = torch.device(data)
can_convert = True
elif ((node.type is NodeTypes.PRIMITIVE) and all(((i.type is NodeTypes.CONSTANT) for... |
def _make_constant(nodes, predicate):
for n in nodes.values():
if predicate(n):
for i in n.in_edges:
i.remove_output(n)
n.args.clear()
n.kwargs.clear()
n.type = NodeTypes.CONSTANT
|
def set_node_indices(nodes, output_id):
new_nodes = dict()
for (idx, node) in enumerate(nodes.values()):
assert (idx <= node.id)
node.id = idx
if (node.type in [NodeTypes.OP, NodeTypes.PRIMITIVE]):
node.scope += f'_{node.id}'
new_nodes[idx] = node
return (new_no... |
def record_args_and_kwargs(*args, **kwargs):
' recording of args and kwargs input format\n this will record all literal values lists/dicts/ints etch\n and build the necessary hierarchy in the graph\n for list/tuple/set elements we record their position\n for dictionaries we record the ... |
def record_args(args, top_level):
new_args = []
new_args_id = []
for a in args:
if isinstance(a, (list, tuple, set)):
(traced_children, traced_ids) = record_args(a, top_level=False)
traced_value = TracedValue(NodeTypes.PRIMITIVE, ('/' + container_construct_op_name(type(a)))... |
def record_kwargs(kwargs, top_level):
new_kwargs = dict()
new_kwargs_ids = dict()
for (k, v) in kwargs.items():
assert isinstance(k, (int, bool, str, float, type(None))), f'unsupported kwargs {type(k)}'
if isinstance(v, (list, tuple, set)):
(traced_children, children_ids) = rec... |
def unpack_traced_args_and_kwargs(*traced_args, **traced_kwargs):
args = [a._data for a in traced_args]
kwargs = {k: v._data for (k, v) in traced_kwargs.items()}
return (args, kwargs)
|
def connect_inputs_to_output(out_id, traced_args, traced_kwargs=None):
if (traced_kwargs is None):
traced_kwargs = dict()
for a in traced_args:
record_arg(out_id, a.id)
for (k, v) in traced_kwargs.items():
record_kwarg(out_id, k, v.id)
|
@contextmanager
def record_free_floating_parameters_and_buffers(module: nn.Module):
'\n context manager that records buffers and parameters\n which are not connected to a terminal layer\n '
for (name, t) in chain(module.named_parameters(recurse=False), module.named_buffers(recurse=False)):
tr... |
def record_non_terminal_output(out):
(recorded_outs, _) = record_args((out,), top_level=True)
return recorded_outs[0]
|
def record_kwarg(node_id, kwarg, kwarg_id):
assert (kwarg_id < node_id)
NODES[kwarg_id].add_out_edge(NODES[node_id])
NODES[node_id].add_kwarg(kwarg, NODES[kwarg_id])
|
def record_arg(node_id, arg_id):
assert (arg_id < node_id)
NODES[arg_id].add_out_edge(NODES[node_id])
NODES[node_id].add_arg(NODES[arg_id])
|
def container_construct_op_name(container_cls):
container_str = {dict: 'Dict', list: 'List', tuple: 'Tuple', set: 'Set', slice: 'Slice'}[container_cls]
return f'prim::{container_str}Construct'
|
def check_is_valid_graph(nodes):
valid = True
errors = []
for (i, node) in nodes.items():
if ((node.type in [NodeTypes.CONSTANT, NodeTypes.IN, NodeTypes.BUFF_PARAM]) and len(node.in_edges)):
errors.extend(['leaf node with incoming edges', f'node id: {i}', f'node type: {node.type.__name... |
class UnionFind(object):
'Union-find disjoint sets datastructure.\n\n Union-find is a data structure that maintains disjoint set\n (called connected components or components in short) membership,\n and makes it easier to merge (union) two components, and to find\n if two elements are connected (i.e., ... |
def is_None(a):
return operator.is_(a, None)
|
def is_not_None(a):
return operator.is_not(a, None)
|
def traverse_model(module: nn.Module, depth: int, prefix: Optional[str]=None, basic_blocks: Tuple[Type[nn.Module]]=(), full: bool=False) -> Iterator[Tuple[(nn.Module, str, nn.Module, Optional[bool])]]:
'\n iterate over model layers yielding the layer,layer_scope,encasing_module\n Parameters:\n ----------... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.