code
stringlengths
17
6.64M
class Constraint(enum.Enum): MEMORY = 1 TIME = 2 def __repr__(self) -> str: return self.name
def initial_divide(graph: Graph, k: int, weights: Dict[(SimpleNode, float)]) -> Tuple[(int, ...)]: random_topo_sort = random_Khan_algorithm(graph) weights = np.asarray([weights[n] for n in random_topo_sort]) cumulative_weights = np.cumsum(weights) total_weight = cumulative_weights[(- 1)] avg_weigh...
def random_Khan_algorithm(graph: Graph): S = [] T = [] degs = dict() nodes = list(graph.nodes) random.shuffle(nodes) for n in nodes: if (len(n.in_edges) == 0): S.append(n) else: degs[n] = len(n.in_edges) while S: idx = random.randint(0, (len(...
def simple_moves(constraint: Constraint, objective: Objective, stage_volumes: Dict[(int, float)], params_per_stage: Dict[(int, float)], edge_weights: Dict[(Tuple[(SimpleNode, SimpleNode)], float)], node_weights: Dict[(SimpleNode, float)], params_per_node: Dict[(SimpleNode, float)], L_max: float, rounds: int): con...
def advanced_moves(constraint: Constraint, objective: Objective, stage_volumes: Dict[(int, float)], params_per_stage: Dict[(int, float)], edge_weights: Dict[(Tuple[(SimpleNode, SimpleNode)], float)], node_weights: Dict[(SimpleNode, float)], params_per_node: Dict[(SimpleNode, float)], L_max: float, rounds: int): c...
def global_moves(constraint: Constraint, objective: Objective, stage_volumes: Dict[(int, float)], params_per_stage: Dict[(int, float)], edge_weights: Dict[(Tuple[(SimpleNode, SimpleNode)], float)], node_weights: Dict[(SimpleNode, float)], params_per_node: Dict[(SimpleNode, float)], L_max: float, rounds: int): con...
def Fiduccia_Mattheyses_moves(constraint: Constraint, objective: Objective, stage_volumes: Dict[(int, float)], params_per_stage: Dict[(int, float)], edge_weights: Dict[(Tuple[(SimpleNode, SimpleNode)], float)], node_weights: Dict[(SimpleNode, float)], params_per_node: Dict[(SimpleNode, float)], L_max: float, rounds: ...
class PartitionState(NamedTuple): stage_volumes: Dict[(int, float)] params_per_stage: Dict[(int, float)] node_weights: Dict[(SimpleNode, float)] edge_weights: Dict[(Tuple[(SimpleNode, SimpleNode)], float)] params_per_node: Dict[(SimpleNode, float)] connections: VerticeStageConnections L_ma...
def calculate_edge_gain(v: SimpleNode, dst: int, state: PartitionState) -> float: edge_weights = state.edge_weights gain = 0 comm_deltas = defaultdict((lambda : 0)) connections = state.connections src = v.stage_id for u in v.in_edges: w = edge_weights[(u, v)] if (u.stage_id == ...
def calculate_edge_cut(edge_weights: Dict[(Tuple[(SimpleNode, SimpleNode)], float)]) -> float: edge_cut = 0 visited = set() for ((u, v), w) in edge_weights.items(): if ((u.stage_id != v.stage_id) and ((u.id, v.stage_id) not in visited)): visited.add((u.id, v.stage_id)) edge...
def calculate_stage_time_gain(v: SimpleNode, dst: int, state: PartitionState, use_mse=STAGE_TIME_MSE) -> float: node_weights = state.node_weights volumes = state.stage_volumes if (not use_mse): assert (not STAGE_TIME_MSE) prev_max = max(volumes[v.stage_id], volumes[dst]) new_max = ...
def calculate_stage_times(node_weights: Dict[(SimpleNode, float)], edge_weights: Dict[(Tuple[(SimpleNode, SimpleNode)], float)], include_comm: bool=False) -> Dict[(int, float)]: stage_times = defaultdict((lambda : 0)) for (n, w) in node_weights.items(): stage_times[n.stage_id] += w if include_...
def caclculate_comm_per_stage(edge_weights: Dict[(Tuple[(SimpleNode, SimpleNode)], float)]) -> Dict[(int, float)]: comm_per_stage = defaultdict((lambda : 0)) visited = set() for ((u, v), w) in edge_weights.items(): if ((u.stage_id != v.stage_id) and ((u.id, v.stage_id) not in visited)): ...
def calculate_params_per_node(model: Module, graph: Graph) -> Dict[(int, float)]: layers = layerDict(model, graph.depth, graph.basic_blocks) tensors = tensorDict(model) params_per_node = dict() for n in graph.nodes: if (n.scope in layers): params_per_node[n.id] = sum((t.numel() for...
def calculate_params_per_stage(params_per_node: Dict[(SimpleNode, float)]) -> Dict[(int, float)]: params_per_stage = defaultdict((lambda : 0)) for (n, p) in params_per_node.items(): params_per_stage[n.stage_id] += p return dict(params_per_stage)
def move_satisfies_time_constraint(v: SimpleNode, dst: int, state: PartitionState) -> bool: node_weights = state.node_weights volumes = state.stage_volumes return ((volumes[dst] + node_weights[v]) < state.L_max)
def move_satisifies_memory_constraint(v: SimpleNode, dst: int, state: PartitionState) -> bool: params_per_node = state.params_per_node params_per_stage = state.params_per_stage return ((params_per_stage[dst] + params_per_node[v]) < state.L_max)
def acyclic_partition(model: Module, graph: Graph, k: int, epsilon: float=0.1, node_weight_function: Optional[NodeWeightFunction]=None, edge_weight_function: Optional[EdgeWeightFunction]=None, constraint: Constraint=Constraint.TIME, objective: Objective=Objective.EDGE_CUT, meta_algorithm: META_ALGORITH=META_ALGORITH....
def worker(kwargs) -> Tuple[(Dict[(int, int)], float, float)]: graph = Graph.from_state(kwargs.pop('graph')) kwargs['graph'] = graph meta_algorithm = kwargs.pop('meta_algorithm') algorithm = kwargs['algorithm'] allocated_seconds = kwargs.pop('allocated_seconds') objective = kwargs['objective']...
def is_better_solution(solution: Tuple[(float, float)], best_solution: Tuple[(float, float)], objective: Objective) -> bool: (solution_edge_cut, solution_worst_case) = solution (best_edge_cut, best_worst_case) = best_solution better_edge_cut = (solution_edge_cut < best_edge_cut) better_worst_case = (s...
def single_level_partitioning(graph: Graph, node_weights: Dict[(SimpleNode, float)], edge_weights: Dict[(Tuple[(SimpleNode, SimpleNode)], float)], params_per_node: Dict[(SimpleNode, float)], algorithm: ALGORITHM, k: int, epsilon: float, constraint: Constraint, maximum_constraint_value: Optional[float], objective: Obj...
def multilevel_partitioning(graph: Graph, node_weights: Dict[(SimpleNode, float)], edge_weights: Dict[(Tuple[(SimpleNode, SimpleNode)], float)], params_per_node: Dict[(SimpleNode, float)], algorithm: ALGORITHM, k: int, epsilon: float, constraint: Constraint, maximum_constraint_value: Optional[float], objective: Objec...
class DefaultWeightFunction(): def __call__(self, u: SimpleNode) -> float: return 1
class DefaultEdgeWeightFunction(): def __call__(self, u: SimpleNode, v: SimpleNode) -> float: return 1
def build_dot(node, edge_weights): '\n return a graphviz representation of the graph\n Parameters\n ----------\n ' theme = {'background_color': '#FFFFFF', 'fill_color': '#E8E8E8', 'outline_color': '#000000', 'font_color': '#000000', 'font_name': 'Times', 'font_size': '10', 'margin': '0,0', 'paddin...
def show_move(node, edge_weights, file_name): dot = build_dot(node, edge_weights) dot.format = 'pdf' if os.path.exists(f'./{file_name}.pdf'): os.remove(f'./{file_name}.pdf') dot.render(file_name, directory='.', cleanup=True)
class PriorityQueue(): def __init__(self): self.heap = [] def push_task(self, gain: float, task: Any): tie_braker = random.randint(0, (2 ** 32)) priority = ((- gain), (- tie_braker)) heapq.heappush(self.heap, (priority, task)) def pop_task(self) -> Any: (priority...
class PartitionNode(): ' PartitionNode is a collection of graph nodes allocated to the same partition\n an edge exists between PartitionNodes iff they there are edges between the underlying graph nodes\n ' def __init__(self, nodes: Iterable[Node], idx: int): self.nodes: Set[Node] = set(node...
class QuotientGraph(): def __init__(self, nodes: Iterable[Node]): groups = defaultdict(list) for n in nodes: groups[n.stage_id].append(n) self._nodes: Dict[(int, PartitionNode)] = {idx: PartitionNode(group, idx) for (idx, group) in groups.items()} @property def n_stag...
class VerticeStageConnections(): def __init__(self, nodes): self._in_connections = dict() self._out_connections = dict() for n in nodes: self._in_connections[n] = defaultdict((lambda : 0)) self._out_connections[n] = defaultdict((lambda : 0)) for n in nodes:...
class Path(): def __init__(self, v): self.start = self.end = v self.length = 0 self.active = True def is_cycle(self) -> bool: return ((self.start is self.end) and (self.length > 0))
class PathSet(): def __init__(self, graph_nodes: Iterable[Node]): self.paths = {v: Path(v) for v in graph_nodes} self.next: Dict[(Node, Node)] = {v: v for v in graph_nodes} self.prev: Dict[(Node, Node)] = {v: v for v in graph_nodes} self.next_edge: Dict[(Node, Optional[Tuple[(Node...
class SimpleNode(): def __init__(self, idx, stage_id): self.id = idx self.in_edges = set() self.out_edges = set() self.stage_id = stage_id def add_in_edge(self, node): self.in_edges.add(node) def add_out_edge(self, node): self.out_edges.add(node)
class ContractedGraph(): def __init__(self, in_edges, partition, node_weights, edge_weights, params_per_node, matching): self._nodes: Dict[(int, SimpleNode)] = dict() for n in set(matching.values()): self._nodes[n] = SimpleNode(n, partition[n]) self._node_weights = defaultdict...
def coarsening(graph: Graph, node_weights: Dict[(SimpleNode, float)], edge_weights: Dict[(Tuple[(SimpleNode, SimpleNode)], float)], params_per_node: Dict[(SimpleNode, float)]) -> List[Tuple[(ContractedGraph, Dict[(int, int)], ContractedGraph)]]: g = ContractedGraph.from_Graph(graph, node_weights, edge_weights, pa...
def refine(fine_graph: ContractedGraph, coarse_graph: ContractedGraph, matching: Dict[(int, int)]): for n in fine_graph.nodes: n.stage_id = coarse_graph[matching[n.id]].stage_id
def find_max_matching(node_weights: Dict[(SimpleNode, float)], edge_weights: Dict[(Tuple[(SimpleNode, SimpleNode)], float)]) -> Tuple[(Dict[(int, int)], float)]: edges = list(edge_weights.keys()) edge_ratings = {e: edge_rating(e[0], e[1], edge_weights, node_weights) for e in edges} random.shuffle(edges) ...
def max_path_matching(unpacked_path: List[Tuple[(Node, Node)]], edge_ratings: Dict[(Tuple[(Node, Node)], float)]) -> Tuple[(List[Tuple[(Node, Node)]], float)]: k = len(unpacked_path) if (k == 1): return (list(unpacked_path), edge_ratings[unpacked_path[0]]) ratings = ([0] * k) decision = ([Fals...
def unpack_path(pathset: PathSet, path: Path) -> List[Tuple[(Node, Node)]]: assert path.active head = path.start prev = path.end next_v = None current = prev unpacked_path = [] if (prev is head): current = pathset.next_vertex(prev) unpacked_path.append(pathset.edge_to_next(...
def edge_rating(u: Node, v: Node, edge_weights: Dict[(Tuple[(Node, Node)], float)], node_weights: Dict[(Node, float)]) -> float: return ((edge_weights[(u, v)] ** 2) / (1 + (node_weights[u] * node_weights[v])))
def visualize_matching(nodes, matching, file_name: str, directory: str): '\n return a graphviz representation of the graph\n Parameters\n ----------\n ' theme = {'background_color': '#FFFFFF', 'fill_color': '#E8E8E8', 'outline_color': '#000000', 'font_color': '#000000', 'font_name': 'Times', 'font...
def partition_and_match_weights_until_last_partition_is_with_no_recomputation(graph: Graph, weights: Dict[(Node, FullExecTimes)], partitioning_method, partition_profiled_graph_fn, n_runs_limit=10, do_exhustive_search_for_last_partition=True, max_memory_usage_r=None, max_memory_usage_nr=None): print('-I- partition...
def exhustive_search_for_last_partition(saved_state, graph, history, n_runs, partition_profiled_graph_fn, weights, smallest_fp_with_zero_fp=False): if smallest_fp_with_zero_fp: cands = [] for (i, v) in history.items(): d = v['d'] if (d['fp'] > 0): continue ...
def restore_best_from_history(saved_state, history, partition_profiled_graph_fn, weights): i_min = list(history.keys())[int(np.argmin([v['d']['mistakes'] for v in history.values()]))] mistakes_min = history[i_min]['d']['mistakes'] print([history[i]['d']['mistakes'] for i in history]) print(f'Restoring...
def partition_and_check(graph, last_partition_scopes, partition_profiled_graph_fn, weights): for n in graph.nodes: if (n.scope in last_partition_scopes): n.weight = weights[n.id].no_recomputation else: n.weight = weights[n.id].recomputation graph = partition_profiled_gr...
def get_weight_functions(args, verbose=True): MULT_FACTOR = args.weight_mult_factor if args.auto_infer_node_bwd_to_fwd_ratio: node = NodeWeightFunctionWithRatioAutoInfer(MULT_FACTOR=MULT_FACTOR) else: node = NodeWeightFunction(bwd_to_fwd_ratio=args.bwd_to_fwd_ratio, MULT_FACTOR=MULT_FACTOR...
class NodeWeightFunction(): def __init__(self, bwd_to_fwd_ratio=(- 1), MULT_FACTOR=10000.0): self.ratio = bwd_to_fwd_ratio self.MULT_FACTOR = MULT_FACTOR def __call__(self, node: Node): assert isinstance(node.weight, ExecTimes) if (self.ratio < 0): return (self.MU...
class EdgeWeightFunction(): GPU_MEMORY_BW = 550 NON_CONTIGIOUS_PENATLY = True def __init__(self, bw_GBps, bwd_to_fwd_ratio=(- 1), MULT_FACTOR=10000.0, penalty=10000000.0, penalize_non_tensors=False, ensure_positive=True): self.bw = bw_GBps self.ratio = bwd_to_fwd_ratio self.MULT_F...
class NodeWeightFunctionWithRatioAutoInfer(): def __init__(self, MULT_FACTOR=10000.0): self.MULT_FACTOR = MULT_FACTOR def __call__(self, node: Node): assert isinstance(node.weight, ExecTimes) bwd = node.weight.backward_time fwd = node.weight.forward_time bwd_plus_fwd ...
class CoarsenedWeightFunction(): def __init__(self, edge_weight_function: EdgeWeightFunction, node_weight_function: NodeWeightFunction, do_critical_path=False): self.mode = 'ratio' self.do_critical_path = do_critical_path self.ewf = edge_weight_function self.nwf = node_weight_func...
class NodeMemoryEstimator(): THRESHOLD = (11 * 1000000000.0) def __init__(self, optimizer_multiply=1): self.optimizer_multiply = optimizer_multiply @staticmethod def cuda_activations_and_grads_mem(u: Node): if ((u.type is NodeTypes.LAYER) or (u.type is NodeTypes.BUFF_PARAM)): ...
def metis_partition(graph: Graph, num_partitions: int, node_weight_function: Optional[NodeWeightFunction]=None, edge_weight_function: Optional[EdgeWeightFunction]=None, use_layers_only_graph: bool=True, use_virtual_stages: bool=True, **METIS_opts: Dict) -> Graph: '\n performs METIS Kway partitioning on the giv...
def post_process_partition(graph: Graph, edge_weight_function, verbose_on_error=True, assert_output_types=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 object that was partitioned\n v...
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([v.stage_id, u.stage_id]) info.append([v.scope, u.scope]) ...
def break_partition_cycles(graph: Graph): parts = set() roots = defaultdict(set) for u in graph.nodes: parts.add(u.stage_id) for v in u.out_edges: if (u.stage_id > v.stage_id): roots[v.stage_id].add(v) n_parts = len(parts) for (idx, group) in roots.items...
def find_subtree(roots: Set[Node], graph_size: int): nodes = set() open = copy(roots) while (len(open) > 0): n = open.pop() nodes.add(n) for u in n.out_edges: if (u.stage_id == n.stage_id): nodes.add(u) open.add(u) open = copy(nodes) ...
def is_valid_partitioning(graph: Graph, edge_weight_function): '\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): '\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, slice,...
def greedy_best_fit(graph: Graph, P, node_weight_function, node_mem_estimator: NodeMemoryEstimator): bins = {i: list() for i in range(P)} bin_weights = heapdict({i: 0 for i in range(P)}) bin_memory = heapdict({i: 0 for i in range(P)}) node_to_weight = {n: node_weight_function(n) for n in graph.non_inp...
def largest_memory_first_greedy_best_fit_v1(graph: Graph, P, node_weight_function, node_mem_estimator: NodeMemoryEstimator): bins = {i: list() for i in range(P)} bin_weights = heapdict({i: 0 for i in range(P)}) bin_memory = heapdict({i: 0 for i in range(P)}) node_to_weight = {n: node_weight_function(n...
def algorithm_u(ns, m): 'taken from https://codereview.stackexchange.com/questions/1526/finding-all-k-subset-partitions\n ' def visit(n, a): ps = [[] for i in range(m)] for j in range(n): ps[a[(j + 1)]].append(ns[j]) return ps def f(mu, nu, sigma, n, a): if...
def exhustive_search(graph: Graph, P, node_weight_function, node_mem_estimator: NodeMemoryEstimator, L): all_nodes = list(graph.non_input_nodes) all_weights = np.array([node_weight_function(x) for x in all_nodes]) all_mems = np.array([node_mem_estimator(x) for x in all_nodes]) L_tag = len(all_nodes) ...
def coarsen_prefixes(model: Module, graph: Graph, node_weight_function, edge_weight_function, uf: UnionFind, basic_blocks, special_blocks, depth): prev_graph = Graph.from_other(graph) uf2 = UnionFind(elements=graph._nodes.keys()) nodes = list(graph.non_input_nodes) sb_scope_to_nodes = get_marked_nodes...
def get_marked_nodes_for_prefix_coarsening(module, nodes, basic_blocks, special_blocks, depth): sb_id_to_nodes = dict() all_sbs = [] for packed in special_traverse_model(module, depth=depth, basic_blocks=basic_blocks, special_blocks=special_blocks, full=True, mark=True): (sub_layer, scope, parent,...
def annotate_special_blocks_to_hold_to(model, graph, special_blocks, basic_blocks, depth): nodes = list(graph.non_input_nodes) sb_scope_to_nodes = get_marked_nodes_for_prefix_coarsening(module=model, nodes=nodes, basic_blocks=basic_blocks, special_blocks=special_blocks, depth=depth) scopes_to_hold_to = li...
def stochastic_centers_matching(graph: Graph, node_weight_function: NodeWeightFunction, edge_weight_function: EdgeWeightFunction, L, P, uf: UnionFind, verbose=False, record_history=False, special_blocks=None, sb_names=None): print('stochastic_centers_matching') prev_graph = Graph.from_other(graph) uf2 = U...
def check_cycle2(g: Graph, a: Node, b: Node, nms=NodeMemoryEstimator()): '\n Checks if contracting (merging) (a,b) breaks topo order\n Args:\n g: topo-sorted graph\n a: start: first node in edge (a,b)\n b: end: second node in edge (a,b)\n\n Returns:\n True if contracting woul...
def check_cycle_given_topo_sort(g: Graph, a: Node, b: Node): '\n # TODO: Requires topological order. (e.g dyanamic topo order)\n Checks if merging (a,b) breaks topo order\n Args:\n g: topo-sorted graph\n a: start: first node in edge (a,b)\n b: end: second node in edge (a,b)\n Ret...
def coarsening(model, graph, edge_weight_function: EdgeWeightFunction, node_weight_function: NodeWeightFunction, L, P, basic_blocks, special_blocks, depth) -> List[Tuple[(Graph, List[List[Node]], Graph, UnionFind)]]: print(f'-I- Coarsening: got graph with {graph.num_nodes} nodes') mgr = CoarseningMgr(model, g...
class CoarseningMgr(): def __init__(self, model, graph: Graph, edge_weight_function: EdgeWeightFunction, node_weight_function: NodeWeightFunction, L, P, basic_blocks, special_blocks, depth): self.model = model self.graph = graph self.edge_weight_function = edge_weight_function sel...
def contract(graph: Graph, matching: List[List[Node]], edge_weight_function: EdgeWeightFunction, uf: Optional[UnionFind]=None) -> Graph: new_graph = Graph.from_other(graph) for m in sorted(matching, key=(lambda x: x[0].id), reverse=True): root = m[0] for i in m[1:]: new_graph.merge...
def penalty_edges_matching(graph: Graph, edge_weight_function: EdgeWeightFunction): "Penalized edges are for disallowing sending weird stuff which MPI and the like can't handle.\n # TODO: if this creates a cycle we have nothing to do, but manually wrap it and disallow communication of weird stuff\n " ...
def code_analysis_matching(graph: Graph): pass
def adjacent_and_same_size_matching(graph: Graph): pass
def systematic_comm_comp_ratio_matching(graph: Graph, node_weight_function, edge_weight_function, L, uf: UnionFind, verbose=False): prev_graph = Graph.from_other(graph) rbc = RatioBlockCreator(graph, edge_weight_function=edge_weight_function, node_weight_function=node_weight_function, uf=uf) rbc.apply(L, ...
def online_smallest_comp_node_matching(graph: Graph, node_weight_function, edge_weight_function, L, uf: UnionFind, verbose=False, record_history=False): prev_graph = Graph.from_other(graph) uf2 = UnionFind(elements=graph._nodes.keys()) hd = ValueSortedDict({n: node_weight_function(n) for n in graph.non_in...
def nodes_leq_threshold_matching(graph: Graph, node_weight_function, edge_weight_function, L, uf: UnionFind, verbose=False, record_history=False, threshold=0): prev_graph = Graph.from_other(graph) uf2 = UnionFind(elements=graph._nodes.keys()) hd = ValueSortedDict({n: node_weight_function(n) for n in graph...
def ofline_smallest_comp_node_matching(graph: Graph, node_weight_function): matching = [] matched = set() for u in sorted(graph.non_input_nodes, key=(lambda n: node_weight_function(n))): if (u in matched): continue for v in sorted(u.out_edges, key=(lambda n: node_weight_functio...
def online_heavy_edge_matching(graph: Graph, node_weight_function, edge_weight_function, L, uf: UnionFind, verbose=False, record_history=False, pecentile_to_filter=0.9): prev_graph = Graph.from_other(graph) uf2 = UnionFind(elements=graph._nodes.keys()) rbc = RatioBlockCreator(graph, edge_weight_function=e...
def full_alg(graph, P, L, node_weight_function, edge_weight_function, uf, rtol=0.002): history = get_rep_analysis_history_with_online_smallest_comp_node_matching(graph, node_weight_function=node_weight_function, edge_weight_function=edge_weight_function, L=L, uf=uf, rtol=rtol, verbose=False) torch.save(histor...
def repetitive_adjacent_analysis(history: List[List[Set[Node]]], L, P): for (i, found_sets) in enumerate(history): lengths = [len(x) for x in found_sets] print(f'-I- merge {i} Found set lengths {lengths}') for l in lengths: if ((l % P) == 0): k = (l // P) ...
def record_repetitive_adjacent(graph, node_weight_function, rtol=0.002, do_topo_sort=True): if do_topo_sort: graph.topo_sort(change_graph=False) topo_sorted_nodes_to_weight = SortedDict({n.topo_sort_id: node_weight_function(n) for n in graph.non_input_nodes}) found_sets = [] cur = None rsu...
def get_rep_analysis_history_with_online_smallest_comp_node_matching(graph: Graph, node_weight_function, edge_weight_function, L, uf: UnionFind, verbose=True, rtol=0.002): prev_graph = Graph.from_other(graph) (graph, prev_graph) = (prev_graph, graph) uf = deepcopy(uf) hd = ValueSortedDict({n: node_wei...
def doc(s): if hasattr(s, '__call__'): s = s.__doc__ def f(g): g.__doc__ = s return g return f
class heapdict(MutableMapping): __marker = object() def __init__(self, *args, **kw): self.heap = [] self.d = {} self.update(*args, **kw) @doc(dict.clear) def clear(self): del self.heap[:] self.d.clear() @doc(dict.__setitem__) def __setitem__(self, key...
class ReminderPolicy(Enum): ToLast = 'last' ToMin = 'min'
class SecondAndOnClusterPolicy(Enum): BestFitBinPacking = 'best_fit' InOrder = 'order' Reversed = 'reversed'
def maketree(n, iterable): d = deque(iterable) res = [] while d: pair = [d.popleft() for _ in range(n)] res.append(pair) return res
def flatten_subsplit(subsplit): to_add = [] for i in subsplit: if isinstance(i, list): to_add.extend(i) else: to_add.append(i) return to_add
def sum_subsplit_weight(subsplit): return sum((i.weight for i in flatten_subsplit(subsplit)))
def get_all_splits(K: int, clusters, id_to_node: Dict[(int, Node)], to_unify: Dict[(int, List[Union[(List, Any)]])], C: int, reminder_policy: ReminderPolicy=ReminderPolicy.ToLast): all_splits = [] assert (len(clusters.cluster.unique()) == C) clusters = [list(clusters.groupby('cluster').get_group(c).sort_v...
def get_unified_clusters(clusters, to_unify): def to_set(v, s): if (not isinstance(v, list)): s.add(v) return for x in v: to_set(x, s) (A, B) = (set(), set()) to_set(clusters, A) new_clusters = [] for (c_i, cluster) in enumerate(clusters): ...
def make_clusters(graph: Graph, nodes: List[Node], node_weight_function, C: int, THRESHOLD=0): def node_to_record(node): return {'id': node.id, 'weight': node_weight_function(node)} records = [node_to_record(node) for node in nodes] X = pd.DataFrame.from_records(data=records, index='id') node...
def best_Fit_cluster(K: int, clusters, id_to_node: Dict[(int, Node)], to_unify: Dict[(int, List[Union[(List, Any)]])], C: int, second_and_on_cluster_policy: SecondAndOnClusterPolicy=SecondAndOnClusterPolicy.BestFitBinPacking, reminder_policy: ReminderPolicy=ReminderPolicy.ToLast): bins = defaultdict(list) bin...
def stages_from_bins(graph: Graph, bins: Dict[(int, List[Node])], id_to_node_worked_on: Dict[(int, Node)], verbose=False, assert_missing_in_bins=False, convert_id_to_node_to_topo=False): if convert_id_to_node_to_topo: tmp = dict() for (i, v) in id_to_node_worked_on.items(): tmp[v.topo_...
def break_ccs_on_same_gpu_to_stages(graph, id_to_node_worked_on, unbroken_stages, bins_to_id, assert_missing_in_bins=False): broken_stages = [] for unbroken_stage in unbroken_stages: broken_stages_for_unbroken_stage = [] cur_set = list() unbroken_stage = deque(sorted(unbroken_stage)) ...
def ccs_on_same_gpu_has_path_via_missing_nodes(cur_set, graph, id_to_node_worked_on, prev_topo_sort_id, topo_sort_id, unbroken_stage): missing_topo_sort_ids = list(range((prev_topo_sort_id + 1), topo_sort_id)) is_ok = True for missing_topo_sort_id in missing_topo_sort_ids: if (missing_topo_sort_id...
def get_ccs_on_same_gpu(bins_to_id, gpu_id, nodes_in_bin, nodes_with_in_edges_from_different_gpu, nodes_with_out_edges_to_different_gpu): uf = UnionFind(elements=bins_to_id[gpu_id]) open = deque(sorted(nodes_in_bin, key=(lambda x: x.topo_sort_id))) while open: x = open.popleft() x: Node ...
def analyze_n_clusters(nodes: List[Node], node_weight_function, max_k=10, THRESHOLD=0, manual_choose_n_clusters=True): ' utility to help determine number of clusters for partition_2dbin_pack' def node_to_record(node): return {'id': node.id, 'weight': node_weight_function(node)} records = [node_to...
def partition_2dbin_pack(graph: Graph, num_gpus: int, n_clusters: int, node_weight_function: Optional[NodeWeightFunction]=None, use_layers_graph: bool=True, THRESHOLD=0, second_and_on_cluster_policy: SecondAndOnClusterPolicy=SecondAndOnClusterPolicy.BestFitBinPacking, reminder_policy: ReminderPolicy=ReminderPolicy.To...