code stringlengths 17 6.64M |
|---|
def rounddict(d: Dict[(Any, float)], x=2):
return {k: round(number=v, ndigits=x) for (k, v) in d.items()}
|
def run_analysis(sample, graph, config: AnalysisPipelineConfig, n_iter, recomputation=True, bw_GBps=12, verbose=True, async_pipeline=False, add_comm_times_to_balance=True, sequential_model=None, stages_on_same_gpu: Optional[List[Set[int]]]=None, PRINT_THEORETICAL=False, PRINT_MIN_MAX_BALANCE=False, PRINT_VAR_STD=Fals... |
def data_parallel_analysis(TRY_ASGD_ANALYSIS, TRY_SSGD_ANALYSIS, bw_GBps, expected_speedup, num_real_stages, sample, sequential_model, verbose, config: AnalysisPipelineConfig):
if (TRY_SSGD_ANALYSIS and torch.cuda.is_available() and (sequential_model is not None)):
n_workers = num_real_stages
mode... |
def first_arg_cache(function):
memo = {}
@wraps(function)
def wrapper(*args):
try:
return memo[id(args[0])]
except KeyError:
rv = function(*args)
memo[id(args[0])] = rv
return rv
return wrapper
|
def computation_communication_ratio(comp_times, comm_times):
assert (len(comp_times) == len(comm_times))
ratio = {k: (comp_times[k] / (comm_times[k] + comp_times[k])) for k in comp_times}
return ratio
|
def utilization(times, comp_fraction):
worst = max(times.values())
base_util = {k: round((v / worst), 2) for (k, v) in times.items()}
comp_util = {k: (base_util[k] * comp_fraction[k]) for k in comp_fraction}
return comp_util
|
def slowdown(times, times_wo_comm):
worst = max(times.values())
n_partitions = len(times)
ideal = sum(times_wo_comm.values())
actual = (n_partitions * worst)
model_parallel_and_partitioning_slowdown = (actual / ideal)
return model_parallel_and_partitioning_slowdown
|
def imbbalance_slowdown(times):
worst = max(times.values())
n_partitions = len(times)
total = sum(times.values())
actual = (n_partitions * worst)
partitioning_slowdown = (actual / total)
return partitioning_slowdown
|
def expected_speedup_after_partitioning(fwd_times, bwd_times, fwd_times_wo_comm, bwd_times_wo_comm):
n_partitions = len(fwd_times)
assert (len(fwd_times) == len(bwd_times))
fwd_slowdown = slowdown(fwd_times, fwd_times_wo_comm)
bwd_slowdown = slowdown(bwd_times, bwd_times_wo_comm)
worst_fwd = max(f... |
def expected_speedup_compared_to_seq(pipe_times, seq_times: ProfileResult):
def extract_seq_stuff(seq_times):
nocomm_real_b_times = seq_times.nocommb_times_mean
nocomm_real_f_times = seq_times.nocommf_times_mean
real_b_times = seq_times.b_times_mean
real_f_times = seq_times.f_time... |
def parameter_count(partition_config: AnalysisPipelineConfig):
n_partitions = partition_config.n_stages
d = {}
for i in range(n_partitions):
model = partition_config.stage_to_model[i]
n_params = sum((p.numel() for p in model.parameters()))
d[i] = n_params
total = sum(d.values()... |
def same_gpu_parameter_count(stage_param_count: Dict[(Union[(int, str)], int)], stages_on_same_gpu: Dict[(int, Set[int])]):
def set_to_hashable(s: Set[int]):
return tuple(sorted(s))[0]
gpu_to_params = defaultdict(int)
for (stage_id, v) in stages_on_same_gpu.items():
k = set_to_hashable(v)... |
@dataclass
class ProfileResult():
f_times_mean: Dict[(int, float)]
f_times_std: Dict[(int, float)]
b_times_mean: Dict[(int, float)]
b_times_std: Dict[(int, float)]
communication_stats: Dict[(int, Dict[(str, float)])]
nocommf_times_mean: Dict[(int, float)]
nocommf_times_std: Dict[(int, floa... |
def profile_execution(model_inputs, partition_config: AnalysisPipelineConfig, n_iters: int, recomputation=True, bw_GBps=12, async_pipeline=False, add_comm_times_to_balance=True, stages_on_same_gpu: Optional[Dict[(int, Set[int])]]=None, parallel_comm_and_comp_ratio=0, different_links_between_accelerators=False) -> Pro... |
def run_and_profile_partitions(activations, add_comm_times_to_balance, async_pipeline, b_times, bw_GBps, communication_stats, current_iteration_num, different_links_between_accelerators, f_times, is_parameter, nocommb_times, nocommf_times, parallel_comm_and_comp_ratio, partition_config, parts, recomputation, stages_o... |
@contextmanager
def force_out_of_place(model: torch.nn.Module):
state = dict()
for m in model.modules():
if (hasattr(m, 'inplace') and isinstance(m.inplace, bool)):
state[m] = m.inplace
m.inplace = False
(yield)
for (m, s) in state.items():
m.inplace = s
|
def mean_std(times, drop=1):
means = dict()
stds = dict()
for (i, ts) in times.items():
for _ in range(drop):
max_v = max(ts)
vs_cand = [t for t in ts if (t < max_v)]
if (len(vs_cand) == 0):
break
ts = vs_cand
arr = np.array(t... |
def cuda_time(partition, inputs, recomputation=True, inputs_requires_grad=False):
partition = partition.to('cuda')
partition.device = 'cuda'
b_time = cuda_backward(partition, inputs, recomputation=recomputation, inputs_requires_grad=inputs_requires_grad)
for p in partition.parameters():
p.grad... |
def move_and_detach(ts, device):
def f(t):
if isinstance(t, torch.Tensor):
return t.detach().to(device)
return t
return nested_map(f, ts)
|
def tensor_sizes(ts):
def f(t):
if isinstance(t, torch.Tensor):
return (t.nelement() * t.element_size())
return 1
return sum(map(f, flatten(ts)))
|
def set_req_grad(ts, inputs_requires_grad):
if isinstance(inputs_requires_grad, bool):
it = itertools.cycle([inputs_requires_grad])
elif isinstance(inputs_requires_grad, (tuple, list)):
it = iter(inputs_requires_grad)
else:
raise NotImplementedError()
def f(t):
if isin... |
def get_grad_tensors(flattened_outputs):
'Infer grad_tensors to be used with:\n torch.autograd.backward(tensors=flattened_outputs, grad_tensors=grad_tensors)\n '
grad_tensors = []
for out in flattened_outputs:
if (isinstance(out, torch.Tensor) and out.requires_grad):
grad... |
def infer_grad_tensors_for_partition(partition, inputs):
outputs = partition(*inputs)
flattened_outputs = flatten(outputs)
grad_tensors = get_grad_tensors(flattened_outputs)
return grad_tensors
|
def cuda_backward(partition, inputs, recomputation=True, inputs_requires_grad=False):
'Measure forward/backward time of a partition on the GPU\n '
inputs = set_req_grad(move_and_detach(inputs, 'cuda'), inputs_requires_grad)
grad_tensors = infer_grad_tensors_for_partition(partition, inputs)
start = ... |
def cuda_forward(partition, inputs, recomputation=True):
inputs = move_tensors(inputs, 'cuda')
start = torch.cuda.Event(enable_timing=True)
end = torch.cuda.Event(enable_timing=True)
torch.cuda.synchronize(device='cuda')
with torch.set_grad_enabled((not recomputation)):
start.record()
... |
def cpu_time(partition, inputs, recomputation=True, inputs_requires_grad=False):
' measure forward/backward time of a partition on the CPU\n '
partition = partition.to('cpu')
partition.device = 'cpu'
b_time = cpu_backward(partition, inputs, recomputation=recomputation, inputs_requires_grad=inputs_r... |
def cpu_forward(partition, inputs, recomputation=True):
inputs = move_tensors(inputs, 'cpu')
with torch.set_grad_enabled((not recomputation)):
start = time.time()
outputs = partition(*inputs)
end = time.time()
f_time = (1000 * (end - start))
return (f_time, outputs)
|
def cpu_backward(partition, inputs, recomputation=True, inputs_requires_grad=False):
inputs = set_req_grad(move_and_detach(inputs, 'cpu'), inputs_requires_grad)
grad_tensors = infer_grad_tensors_for_partition(partition, inputs)
start = time.time()
outputs = partition(*inputs)
flattened_outputs = f... |
def cuda_computation_times(model, inputs):
' measure forward/backward time of a partition on the GPU\n '
if (not isinstance(inputs, (tuple, list, dict))):
inputs = (inputs,)
model.cuda()
inputs = move_tensors(inputs, 'cuda')
start = torch.cuda.Event(enable_timing=True)
end = torch.c... |
def run_analysis(sample, model, n_workers, bw_GBps=12, verbose=True):
send_mb = (sum([(p.nelement() * p.element_size()) for p in model.parameters()]) / 1000000.0)
single_send_time = (send_mb / bw_GBps)
num_sends = (n_workers * math.log2(n_workers))
total_send_time = (num_sends * single_send_time)
... |
def pipe_model(model: nn.Module, batch_dim: int, model_args: tuple=(), model_kwargs: Optional[Dict]=None, n_iter: int=10, nparts: int=4, depth: int=1000, basic_blocks: Optional[Union[(List[nn.Module], Tuple[nn.Module])]]=None, node_weight_function: Optional[NodeWeightFunction]=None, edge_weight_function: Optional[Edg... |
def partition_model(model: nn.Module, model_args: tuple=(), model_kwargs: Optional[Dict]=None, n_iter: int=10, nparts: int=4, max_depth: int=100, basic_blocks: Optional[Union[(List[nn.Module], Tuple[nn.Module])]]=None, node_weight_function: Optional[NodeWeightFunction]=None, edge_weight_function: Optional[EdgeWeightF... |
def get_full_profiles(graph, model, model_args, model_kwargs, n_iter, profile_ops, max_depth, basic_blocks, force_no_recomp_scopes, save_memory_mode, use_graph_profiler, use_network_profiler):
print('-I- profiling model (recomp)')
(recomputation_times, max_mem_usage_bytes_r) = get_profiles(graph, model, model... |
def partition_profiled_graph(graph, model, nparts, partitioning_method, node_weight_function, edge_weight_function, use_virtual_stages, use_layers_only_graph, METIS_opt, acyclic_opt, binpack_opt, mpipe_opt):
partitioning_method = partitioning_method.lower()
if (partitioning_method == 'metis'):
print('... |
def build_profiled_graph(model: nn.Module, model_args: tuple=(), model_kwargs: Optional[Dict]=None, use_network_profiler: bool=False, use_graph_profiler: bool=True, save_memory_mode: bool=False, trace_on_gpu=False, profile_ops: bool=True, recomputation: bool=False, n_iter: int=10, max_depth: int=1000, basic_blocks: O... |
def build_graph_with_nparams_and_grad_reqs(model, model_args, model_kwargs, max_depth, basic_blocks, save_memory_mode, trace_on_gpu, res_cache_name=None) -> Graph:
if res_cache_name:
return compute_and_cache(build_graph_with_nparams_and_grad_reqs, res_cache_name, model, model_args, model_kwargs, max_depth... |
def get_profiles(graph: Graph, model: nn.Module, model_args: tuple=(), model_kwargs: Optional[Dict]=None, use_network_profiler: bool=False, use_graph_profiler: bool=True, save_memory_mode: bool=False, profile_ops: bool=True, recomputation: bool=False, n_iter: int=10, max_depth: int=1000, basic_blocks: Optional[List[n... |
class TorchCache():
def __init__(self, cache_name, overwrite=False):
self.cache_name = cache_name
self.exists = os.path.exists(cache_name)
self.overwrite = overwrite
self.v = None
def __enter__(self):
if self.exists:
print(f'loading from cache: {self.cache... |
class PickleCache():
def __init__(self, cache_name, overwrite=False):
self.cache_name = cache_name
self.exists = os.path.exists(cache_name)
self.overwrite = overwrite
self.v = None
def __enter__(self):
if self.exists:
print(f'loading from cache: {self.cach... |
class GraphCache():
def __init__(self, cache_name, overwrite=False):
self.cache_name = cache_name
self.exists = os.path.exists(cache_name)
self.overwrite = overwrite
self.v = None
self.compute_anyway = False
def __enter__(self):
if self.exists:
try... |
def compute_and_cache(compute_function, cache_name, *args, _cache_cls_to_use=TorchCache, **kw):
'\n Compute or load from cache, optionally save results to cache.\n Return computed value\n Examples:\n # compute big\n # compute_and_cache(lambda: torch.ones(10), "big")\n # compute big, ... |
def compute_and_maybe_cache(compute_function, cache_name, *args, _cache_cls_to_use=TorchCache, **kw):
if cache_name:
return compute_and_cache(compute_function, cache_name, *args, _cache_cls_to_use=_cache_cls_to_use, **kw)
else:
return compute_function(*args, **kw)
|
def compile_partitioned_model(graph: Graph, model: Module, batch_dim: int, generate_explicit_del: bool=False, generate_activation_propagation: bool=True, output_file: Optional[str]=None):
'\n generates the code for the partitioned model.\n The partitions can be consumed using the `create_pipeline_configu... |
def group_nodes_by_stage_id(nodes: Iterable[Node]) -> Dict[(int, List[Node])]:
'\n Groups nodes by their stage_id\n '
ids = {n.stage_id for n in nodes}
stages = OrderedDict()
for i in sorted(ids):
stages[i] = []
for n in nodes:
stages[n.stage_id].append(n)
return stages
|
def generate_imports(layer_classes: Dict[(str, Module)]) -> List[str]:
'\n generates imports to torch torch.nn, torch.nn.functionl as F and torch.Tensor,\n and to every layer used and various other small things\n '
imports = [f'import {namespace}' for namespace in used_namespaces()]
imports.ex... |
def generate_help_functions() -> str:
'generates traverse_model, layerDict, traverse_params_buffs, tensorDict functions,\n to be used in the create_pipeline_configuration function and\n parameters,named_parameters,buffers,named_buffers,cpu,cuda,to,state_dict,load_state_dict\n to be used by the partitions... |
def stage_connections_str(graph: Graph) -> str:
'creates a diagram that illustrates the connectivity between partitions,\n to be embedded in the generated file\n '
(adj_matrix, num_partitions) = stages_adj_lists(graph)
lines = ['# partition adjacency', f"# model inputs {adj_matrix[0]['outputs']}"]
... |
def stages_adj_lists(graph):
num_partitions = graph.num_partitions
adj_matrix = [{'inputs': set(), 'outputs': set()} for i in range((num_partitions + 2))]
for node in graph.nodes:
if (node.type is NodeTypes.IN):
for n in node.out_edges:
adj_matrix[(n.stage_id + 1)]['inp... |
def dict_stages_adj_lists(graph):
(adj_matrix, num_partitions) = stages_adj_lists(graph)
dict_adj_matrix = {}
keys = ((['model_inputs'] + list(range(num_partitions))) + ['model_outputs'])
for (key, v) in zip(keys, adj_matrix):
dict_adj_matrix[key] = v
return (dict_adj_matrix, num_partition... |
def get_stages_depth_from_end(graph) -> Dict[(int, int)]:
(dict_adj_matrix, num_partitions) = dict_stages_adj_lists(graph)
edges = set()
for (i, d) in dict_adj_matrix.items():
if (i in {'model_inputs', 'model_outputs'}):
continue
for x in d['inputs']:
edges.add((i, ... |
def create_pipeline_configuration(graph: Graph, ios: Dict[(int, Dict[(str, List[str])])], model_blocks: Dict[(str, Module)], batch_dim: int, generate_activation_propagation: bool) -> Tuple[(str, Dict)]:
'Generates the create_pipeline_configuration method which given a model creates his partitioned counterpart\n ... |
def create_stages_config(ios: Dict, is_batched: Callable[([torch.Size], bool)], stage_to_device_map=None) -> Dict:
'generates the stages portion of the config\n stages:\n id\n stage_cls\n stage_inputs\n id\n shape\n dtype\n ... |
def create_model_in_out_config(graph: Graph, is_batched: Callable[([torch.Size], bool)]) -> Tuple[(Dict, Dict)]:
'create the config of model inputs and outputs\n model_inputs\n id\n shape\n dtype\n is_batched\n used_by\n model_ou... |
def generate_switch_batch_size():
s = "batch_dim = config['batch_dim']\n for d in chain(config['model_inputs'].values(),config['model_outputs'].values()):\n if d['is_batched']:\n shape = d['shape']\n d['shape'] = torch.Size(shape[:batch_dim] + (batch_size,) + shape[batch_dim+1:])\n... |
def generate_config_without_nested(dict_config: Dict) -> Dict:
config_without_nested = deepcopy(dict_config)
new_model_inputs = dict()
for (input_id, input_cfg) in config_without_nested['model_inputs'].items():
if (not isinstance(input_cfg['is_batched'], bool)):
flattened_is_batched = ... |
def generate_config_with_input_propagation(dict_config: Dict) -> Dict:
new_config = deepcopy(dict_config)
new_model_outputs = new_config['model_outputs']
for (name, cfg) in dict_config['model_outputs'].items():
old_src = cfg['created_by']
used_by = dict_config['stages'][old_src]['outputs']... |
def generate_forward_method(stage_id: int, graph: Graph, partition_nodes: List[Node], model_outputs: List[Node], partition_fields: Dict[(Node, str)], stage_depth_from_end: int, generate_explicit_del=False, generate_activation_propagation=True, move_tensors=False) -> Tuple[(List[str], Dict[(str, List)])]:
'Generat... |
def get_output_destination_stages(graph, outputs):
output_destinations = []
for n in outputs:
destinations = []
if (n.id in graph.output_ids):
destinations.append((- 1))
destinations.extend((o.stage_id for o in n.out_edges))
destinations = set(destinations)
... |
def get_input_source_stages(inputs):
input_sources = []
for n in inputs:
if (n.type is NodeTypes.IN):
input_sources.append((- 1))
else:
input_sources.append(n.stage_id)
return input_sources
|
def generate_declaration(input_ids: List[str], partition_fields: Dict[(Node, str)], input_args: Dict[(Node, str)], move_tensors=False) -> str:
'Generates the forward function declaration and the variable map of inputs and layers\n '
lines = [(tab + f'''def forward(self, *args):
''')]
for (node, field) ... |
def generate_body(outputs: List[Node], partition: List[Node], partition_layer_nodes_to_field_id: Dict[(Node, str)], ready_expressions: Dict[(Node, str)]) -> List[str]:
'Generates the forward function body and return statement\n '
uses = node_uses(partition, set(outputs))
for e in ready_expressions:
... |
def generate_statements(partition_nodes: List[Node], partition_layer_nodes_to_field_id: Dict[(Node, str)], ready_expressions: Dict[(Node, str)], uses: Dict[(Node, int)]) -> List[str]:
' Generate statements according to topological ordering of the partition\n constants will be inlined, variable names will b... |
def allocate_variable(node, ready_expressions, uses, available_names, variable_name_generator):
for i in node.in_edges:
uses[i] -= 1
if (uses[i] == 0):
available_names.append(ready_expressions[i])
if (len(available_names) > 0):
return available_names.pop()
else:
... |
def generate_container_construct(ready_expressions, node, variable_name):
'generate a dict/list/tuple/set/etc. object which has special syntax\n '
if ('prim::DictConstruct' in node.scope):
kwargs = []
for (a, kws) in node.kwargs.items():
for k in kws:
kwargs.appe... |
def generate_constant(node):
assert (node.type is NodeTypes.CONSTANT)
v = node.constant_value
if (isinstance(v, torch.device) or (v == 'cpu') or (isinstance(v, str) and ('cuda' in v))):
return 'self.device'
elif (isinstance(v, str) and ('__getattribute__' not in list(node.out_edges)[0].scope))... |
def generate_magic(variable_name, self_arg, func_name, param_list):
if (func_name == '__getattribute__'):
statement = [f'{variable_name} = {self_arg}.{param_list[1]}']
elif (func_name == '__getitem__'):
statement = [f'{variable_name} = {self_arg}[{param_list[1]}]']
elif (func_name == '__se... |
def generate_parameter_list(node_args, node_kwargs, ready_expressions, should_inject_device=False, string=True):
has_device_arg = any(((a.value_type is torch.device) for a in node_args))
has_device_arg |= any(((a.value_type is torch.device) for a in node_kwargs.keys()))
args = [ready_expressions[a] for a ... |
def generate_return_statement(output_nodes: List[Node], ready_expressions: Dict[(Node, str)]):
' generate the return statement and descriptive comment\n '
scope_comment = f'''
{dtab}# '''.join(map((lambda n: n.scope), output_nodes))
comment = f'''# Returning:
{dtab}# {scope_comment}'''
if (len(outp... |
def add_del_statements(statements: List[str]) -> Iterator[str]:
'\n perform liveliness analysis and insert delete variables when they are no longer used\n '
new_statements = [statements[(- 1)]]
variable_name_matcher = re.compile('t_[0-9]+|x[0-9]+')
inplace_arithmetic_matcher = re.compile('\\d \\... |
def node_uses(partition: List[Node], outputs: Set[Node]) -> Dict[(Node, int)]:
uses = defaultdict((lambda : 0))
for node in partition:
if (node in outputs):
uses[node] += 1
uses[node] += len(list(filter((lambda n: (n.stage_id == node.stage_id)), node.out_edges)))
if (node.t... |
def variableNameGenerator() -> Iterator[str]:
'return an infinite generator yielding\n names t_0 , t_1,...\n '
def f():
temp_idx = (- 1)
while True:
temp_idx += 1
(yield f't_{temp_idx}')
return iter(f())
|
def enforce_out_of_place_for_partition_inputs(partition: List[Node], partition_inputs: List[Node], warn=True):
for n in partition:
if ((n.type != NodeTypes.OP) or (n.value_type != torch.Tensor)):
continue
(op_path, idx) = n.scope.rsplit('/', maxsplit=1)[1].rsplit('_', maxsplit=1)
... |
def apply_input_propagation(stage_id: int, outputs: List[Node], inputs: List[Node]) -> Set[Node]:
for i in inputs:
if (i.type != NodeTypes.IN):
destinations = {o.stage_id for o in i.out_edges}
if (stage_id < max(destinations)):
outputs.append(i)
return set(outpu... |
def generate_init_method(graph: Graph, nodes: List[Node], class_name: str, layers: List[Node], is_param_dict: Dict[(str, bool)], buffs_and_params: List[Node]) -> Tuple[(str, Dict[(Node, str)])]:
'creates the partition constructor and the mapping between layers and field ids\n '
device_id = re.search('\\d+$... |
def generate_layer_and_tensor_scopes(layers: List[Node], buffs_and_params: List[Node]):
scope_field = ['LAYER_SCOPES = [']
for n in layers:
scope_field.append(f"{tab}'{n.scope}',")
scope_field.append(']')
scope_field = (tab + f'''
{dtab}'''.join(scope_field))
tensor_field = ['TENSORS = [']... |
def generate__init__layer_statements(layers: List[Node]) -> Tuple[(str, Dict[(Node, str)])]:
' Generates partition field initialization statements\n and save the layer scopes in the self.scopes field\n '
statements = ['# Initialize partition layers', 'for idx, layer_scope in enumerate(self.LAYER_SCO... |
def generate__init__buff_and_param_statements(buffers: List[Node], parameters: List[Node]) -> Tuple[(str, Dict[(Node, str)])]:
' Generate the init statements to initialize the partitions free floating buffers and parameters\n free floating means that those tensors are not part of any layer in this partitio... |
def generate_lookup(layers_to_id: Dict[(Node, str)], tensors_to_id: Dict[(Node, str)]) -> str:
lookup = []
for (field_node, field_id) in chain(layers_to_id.items(), tensors_to_id.items()):
fields = re.findall('\\[[a-zA-Z0-9_]*\\]', field_node.scope)
fields = map((lambda s: s[1:(- 1)]), fields)... |
def generate_partition_state_methods() -> str:
' generate partition methods state_dict() load_state_dict() named_buffers() and named_parameters()\n our custom implementation guarantees 100% compatibility with the original model same names will be used\n '
state_dict = generate_state_dict_method()
... |
def generate_state_dict_method() -> str:
'Generates the state_dict method\n ensuring same keys are used as in the base model\n '
state_dict_method = ['def state_dict(self, *args, **kwargs):', '# we return the state dict of this part as it should be in the original model', 'return state_dict(self, *a... |
def generate_named_parameters_method() -> str:
'Generates the named_parameters method\n ensuring we use the names given to the parameters in the un-partitioned model\n '
named_parameters_method = ['def named_parameters(self, *args, **kwargs):', '# we return the named parameters of this part as it sh... |
def generate_named_buffers_method() -> str:
'Generates the named_buffers method\n ensuring we use the names given to the buffers in the un-partitioned model\n '
named_buffers_method = ['def named_buffers(self, *args, **kwargs):', f'# we return the named buffers of this part as it should be in the or... |
def generate_load_state_dict_method() -> str:
'Generates the load_state_dict method\n ensuring that weights will be assigned to their correct counterparts inside the partition\n '
func = ['def load_state_dict(self, *args, **kwargs):', 'return load_state_dict(self, *args, **kwargs)']
return (f'''... |
def generate_cpu_cuda_to_methods() -> Tuple[(str, str, str)]:
'generates the cpu cuda and to methods of the partitions\n the generated code keeps track of on which device the partition is placed\n\n Returns:\n Tuple[str, str, str] the generated code\n '
cpu = f'''
{tab}def cpu(self):
{dtab}... |
def get_state_methods():
return [state_dict, load_state_dict, named_buffers, named_parameters, cpu, cuda, to]
|
def state_dict(partition, *args, **kwargs):
state = nn.Module.state_dict(partition, *args, **kwargs)
lookup = partition.lookup
result = dict()
for (k, v) in state.items():
if (k in lookup):
result[lookup[k]] = v
else:
assert ('.' in k)
split_idx = k.... |
def load_state_dict(partition, state_dict, strict=True):
reverse_lookup = {v: k for (k, v) in partition.lookup.items()}
device = partition.device
keys = list(partition.state_dict(None).keys())
new_state = dict()
for k in keys:
if (k in reverse_lookup):
new_state[reverse_lookup[... |
def named_parameters(partition, prefix='', recurse=True):
params = nn.Module.named_parameters(partition, prefix=prefix, recurse=recurse)
lookup = partition.lookup
for (k, v) in params:
if (k in lookup):
(yield (lookup[k], v))
else:
assert ('.' in k)
spli... |
def named_buffers(partition, prefix='', recurse=True):
params = nn.Module.named_buffers(partition, prefix=prefix, recurse=recurse)
lookup = partition.lookup
for (k, v) in params:
if (k in lookup):
(yield (lookup[k], v))
else:
assert ('.' in k)
split_idx ... |
def cpu(partition):
partition.device = torch.device('cpu')
return nn.Module.cpu(partition)
|
def cuda(partition, device=None):
if (device is None):
device = torch.cuda.current_device()
partition.device = torch.device(device)
return nn.Module.cuda(partition, partition.device)
|
def to(partition, *args, **kwargs):
device = None
if ('device' in kwargs):
device = kwargs['device']
elif ('tensor' in kwargs):
device = kwargs['tensor'].device
if args:
if isinstance(args[0], (torch.device, int, str)):
device = args[0]
if torch.is_tensor(ar... |
def pretty_format_obj(obj, dict_prefix=dtab) -> str:
if isinstance(obj, torch.Size):
return str(obj)
elif isinstance(obj, (list, tuple, set)):
elements = [pretty_format_obj(t) for t in obj]
if ((len(elements) == 1) and isinstance(obj, tuple)):
elements[0] += ','
ele... |
def get_sorted_partition_inputs(graph: Graph, partition: List[Node]) -> List[Node]:
'return a list of all nodes that are input to this partition\n\n sorted by id\n '
inputs = set()
for node in partition:
if (node.type is NodeTypes.IN):
inputs.add(node)
inputs.update([n... |
def get_partition_outputs(partition: List[Node], model_outputs: List[Node]) -> List[Node]:
' return all nodes that are outputs of the partition\n\n '
def is_output(n):
part_output = ((n.type != NodeTypes.IN) and any(((o.stage_id != n.stage_id) for o in n.out_edges)))
return (part_output or... |
def ensure_inputs_are_used(graph: Graph, assert_same_stages=True):
if assert_same_stages:
n2 = graph.num_partitions
b4 = {n.stage_id for n in graph.nodes}
for n in graph.nodes:
if (n.type != NodeTypes.IN):
continue
assert (len(n.out_edges) > 0), 'inputs must be used... |
def ensure_no_unnecessary_tuple_sends(graph: Graph, assert_same_stages=True):
if assert_same_stages:
n2 = graph.num_partitions
b4allstages = {n.stage_id for n in graph.nodes}
for n in graph.nodes:
if ((n.type != NodeTypes.OP) or ('tuple::__getitem__' not in n.scope)):
conti... |
class META_ALGORITH(enum.Enum):
SINGLE_LEVEL = 1
MULTI_LEVEL = 2
def __repr__(self):
return self.name
|
class ALGORITHM(enum.Enum):
SIMPLE_MOVES = 1
ADVANCED_MOVES = 2
GLOBAL_MOVES = 3
FIDUCCIA_MATTHEYSES_MOVES = 4
def __repr__(self) -> str:
return self.name
|
class Objective(enum.Enum):
EDGE_CUT = 1
STAGE_TIME = 2
def __repr__(self) -> str:
return self.name
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.