Skip to content

llmcompressor.pipelines.sequential.helpers

Classes:

  • Subgraph –

    Dataclass specifying an executable subgraph of a model graph

Functions:

  • handle_sequential_oom –

    Catch ooms and suggest changing sequential targets

  • trace_subgraphs –

    Trace a model to produce subgraphs, where each sequential target belongs to exactly

SequentialTracer

SequentialTracer(ancestors: set[Module])

Bases: HFTracer

Get a tracer specialized for the given model. The resulting tracer will not trace inside of sequential targets, nor any modules which are not call graph ancestors of sequential targets

Modules which run while a node is executed on meta tensors (e.g. inside wrapped functions) are recorded on node.meta[INVOKED_SUBMODULES_META_KEY] so that Subgraph.submodules can attribute them to a subgraph

Parameters:

  • ancestors (set[Module]) –

    modules which are ancestors of sequential targets

Methods:

  • call_module –

    Record module if it is being executed on meta tensors by create_proxy

  • create_proxy –

    Create a node and record the modules which run while HFTracer executes it on

Source code in src/llmcompressor/pipelines/sequential/helpers.py
def __init__(self, ancestors: set[Module]):
    self.ancestors = ancestors
    self._invoked: list[str] | None = None

    # skip any mask creation functions not already caught by the autowrapper
    super().__init__(autowrap_functions=_get_autowrap_functions())

call_module

call_module(module: Module, forward, args, kwargs)

Record module if it is being executed on meta tensors by create_proxy (_disable_call_module is only set in that window). Names come from submodule_paths rather than path_of_module, which would insert modules constructed inside forward (e.g. nn.Softmax) as new root submodules

Source code in src/llmcompressor/pipelines/sequential/helpers.py
def call_module(self, module: Module, forward, args, kwargs):
    """
    Record `module` if it is being executed on meta tensors by `create_proxy`
    (`_disable_call_module` is only set in that window). Names come from
    `submodule_paths` rather than `path_of_module`, which would insert modules
    constructed inside `forward` (e.g. `nn.Softmax`) as new root submodules
    """
    if getattr(self, "_disable_call_module", False):
        name = self.submodule_paths.get(module)
        if name is not None:
            self._invoked.append(name)
    return super().call_module(module, forward, args, kwargs)

create_proxy

create_proxy(
    kind, target, args, kwargs, *extra_args, **extra_kwargs
)

Create a node and record the modules which run while HFTracer executes it on meta tensors, so Subgraph.submodules can see modules called inside wrapped functions. call_module nodes are skipped because they already own their descendants via recurse

Source code in src/llmcompressor/pipelines/sequential/helpers.py
def create_proxy(self, kind, target, args, kwargs, *extra_args, **extra_kwargs):
    """
    Create a node and record the modules which run while HFTracer executes it on
    meta tensors, so `Subgraph.submodules` can see modules called inside wrapped
    functions. `call_module` nodes are skipped because they already own their
    descendants via `recurse`
    """
    outer, self._invoked = self._invoked, []
    try:
        proxy = super().create_proxy(
            kind, target, args, kwargs, *extra_args, **extra_kwargs
        )
        if self._invoked and kind != "call_module":
            proxy.node.meta[INVOKED_SUBMODULES_META_KEY] = list(
                dict.fromkeys(self._invoked)
            )
        return proxy
    finally:
        self._invoked = outer

Subgraph dataclass

Subgraph(
    graph: Graph,
    input_names: set[str],
    consumed_names: set[str],
    _code: PythonCode | None = None,
)

Dataclass specifying an executable subgraph of a model graph

Parameters:

  • graph (Graph) –

    subgraph of model graph

  • input_names (set[str]) –

    argument names of the compiled forward function

  • consumed_names (set[str]) –

    argument names which are not used by any subsequent subgraphs and can therefore be deleted from the intermediates cache

Methods:

  • forward –

    Execute the operations within the subgraph

  • submodule_dict –

    Return subgraph modules keyed by their fully qualified model names.

forward

forward(*args, **kwargs) -> dict[str, Any]

Execute the operations within the subgraph

Parameters:

  • \*args –

    argument inputs to subgraph forward function

  • \**kwargs –

    keyword inputs to subgraph forward function

Returns:

  • dict[str, Any] –
Source code in src/llmcompressor/pipelines/sequential/helpers.py
def forward(self, *args, **kwargs) -> dict[str, Any]:
    """
    Execute the operations within the subgraph

    :param \\*args: argument inputs to subgraph forward function
    :param \\**kwargs: keyword inputs to subgraph forward function
    :return keyword outputs of subgraph forward function (non-consumed variables):
    """
    if self._code is None:
        self._code = self.graph.python_code("self")
        exec(self._code.src, self._code.globals)

    forward_fn = self._code.globals.get("forward")

    with append_autowrap_source_on_fail():
        return forward_fn(*args, **kwargs)

submodule_dict

submodule_dict(
    model: Module, recurse: bool = True
) -> dict[str, Module]

Return subgraph modules keyed by their fully qualified model names.

Source code in src/llmcompressor/pipelines/sequential/helpers.py
def submodule_dict(self, model: Module, recurse: bool = True) -> dict[str, Module]:
    """Return subgraph modules keyed by their fully qualified model names."""
    return {
        name: model.get_submodule(name)
        for name in self._subgraph_module_names(model, recurse=recurse)
    }

collect_subgraph_modules

collect_subgraph_modules(
    model: Module,
    subgraphs: list[Subgraph],
    recurse: bool = True,
) -> dict[str, Module]

Return the union of all modules owned by the traced subgraphs.

Source code in src/llmcompressor/pipelines/sequential/helpers.py
def collect_subgraph_modules(
    model: Module, subgraphs: list[Subgraph], recurse: bool = True
) -> dict[str, Module]:
    """Return the union of all modules owned by the traced subgraphs."""
    modules: dict[str, Module] = {}
    for subgraph in subgraphs:
        modules.update(subgraph.submodule_dict(model, recurse=recurse))
    return modules

compress_subgraph_modules

compress_subgraph_modules(modules: list[Module]) -> None

Compress quantized modules owned by one subgraph.

Source code in src/llmcompressor/pipelines/sequential/helpers.py
def compress_subgraph_modules(modules: list[Module]) -> None:
    """Compress quantized modules owned by one subgraph."""
    quantized_modules = [module for module in modules if is_module_quantized(module)]
    if is_distributed():
        replace_module_parallel(
            quantized_modules, compress_module, desc="Compressing modules"
        )
    else:
        for module in tqdm(quantized_modules, desc="Compressing modules"):
            compress_module(module)

decompress_subgraph_modules

decompress_subgraph_modules(modules: list[Module]) -> None

Decompress quantized modules owned by one subgraph.

Source code in src/llmcompressor/pipelines/sequential/helpers.py
def decompress_subgraph_modules(modules: list[Module]) -> None:
    """Decompress quantized modules owned by one subgraph."""
    compressed_modules = [module for module in modules if is_module_quantized(module)]
    for module in tqdm(compressed_modules, desc="Decompressing modules"):
        decompress_module(module, leave_decompressed=False)

find_modules_outside_graph

find_modules_outside_graph(
    model: Module, graph: GraphModule
) -> dict[str, Module]

Return modules that no node of a traced graph calls. These are the same modules as find_modules_outside_subgraphs returns for any partition of the graph, so they can be found before the graph is partitioned

Source code in src/llmcompressor/pipelines/sequential/helpers.py
def find_modules_outside_graph(model: Module, graph: GraphModule) -> dict[str, Module]:
    """
    Return modules that no node of a traced graph calls. These are the same modules as
    `find_modules_outside_subgraphs` returns for any partition of the graph, so they
    can be found before the graph is partitioned
    """
    whole_graph = Subgraph(graph=graph.graph, input_names=set(), consumed_names=set())
    return find_modules_outside_subgraphs(model, [whole_graph])

find_modules_outside_subgraphs

find_modules_outside_subgraphs(
    model: Module,
    subgraphs: list[Subgraph],
    recurse: bool = True,
) -> dict[str, Module]

Return modules that were traced but do not belong to any subgraph.

Source code in src/llmcompressor/pipelines/sequential/helpers.py
def find_modules_outside_subgraphs(
    model: Module, subgraphs: list[Subgraph], recurse: bool = True
) -> dict[str, Module]:
    """Return modules that were traced but do not belong to any subgraph."""
    subgraph_modules = collect_subgraph_modules(model, subgraphs, recurse=recurse)
    return {
        name: module
        for name, module in model.named_modules()
        if name and name not in subgraph_modules
    }

find_target_nodes

find_target_nodes(
    graph: GraphModule, targets: set[Module]
) -> set[Node]

Find all nodes whose execution is equivalent to executing the target modules. Note that these nodes are guaranteed to be treated as leaf nodes by SequentialTracer

Parameters:

  • graph (GraphModule) –

    graph containing target nodes

  • targets (set[Module]) –

    modules whose nodes are being searched for

Returns:

  • set[Node] –

    set of all nodes which call the target modules

Source code in src/llmcompressor/pipelines/sequential/helpers.py
def find_target_nodes(graph: GraphModule, targets: set[Module]) -> set[Node]:
    """
    Find all nodes whose execution is equivalent to executing the target modules.
    Note that these nodes are guaranteed to be treated as leaf nodes by SequentialTracer

    :param graph: graph containing target nodes
    :param targets: modules whose nodes are being searched for
    :return: set of all nodes which call the target modules
    """
    return set(
        node
        for node in graph.graph.nodes
        if node.op == "call_module" and graph.get_submodule(node.target) in targets
    )

get_node_modules

get_node_modules(model: Module, node: Node) -> list[str]

Get the modules a node onloads when its subgraph runs: its roots (see get_node_roots) and their submodules

Parameters:

  • model (Module) –

    model which owns the graph

  • node (Node) –

    node of the traced graph

Returns:

  • list[str] –

    module names

Source code in src/llmcompressor/pipelines/sequential/helpers.py
def get_node_modules(model: Module, node: Node) -> list[str]:
    """
    Get the modules a node onloads when its subgraph runs: its roots (see
    `get_node_roots`) and their submodules

    :param model: model which owns the graph
    :param node: node of the traced graph
    :return: module names
    """
    names = []
    for root in get_node_roots(node):
        for relative_name, _ in model.get_submodule(root).named_modules():
            names.append(f"{root}.{relative_name}" if relative_name else root)

    return names

get_node_roots

get_node_roots(node: Node) -> list[str]

Parameters:

  • node (Node) –

    node of a traced graph

Returns:

  • list[str] –

    names of the module a node calls and of the modules recorded as run inside it (see INVOKED_SUBMODULES_META_KEY), not including their descendants

Source code in src/llmcompressor/pipelines/sequential/helpers.py
def get_node_roots(node: Node) -> list[str]:
    """
    :param node: node of a traced graph
    :return: names of the module a node calls and of the modules recorded as run
        inside it (see `INVOKED_SUBMODULES_META_KEY`), not including their descendants
    """
    roots = [node.target] if node.op == "call_module" else []
    return roots + list(node.meta.get(INVOKED_SUBMODULES_META_KEY, ()))

get_sequential_ancestors

get_sequential_ancestors(
    model: Module, targets: set[Module]
) -> set[Module]

Find modules which are call graph ancestors of the given sequential targets

Parameters:

  • model (Module) –

    model containing sequential targets

  • targets (set[Module]) –

    sequential targets to find ancestors of

Returns:

  • set[Module] –

    call graph ancestors of sequential targets

Source code in src/llmcompressor/pipelines/sequential/helpers.py
def get_sequential_ancestors(model: Module, targets: set[Module]) -> set[Module]:
    """
    Find modules which are call graph ancestors of the given sequential targets

    :param model: model containing sequential targets
    :param targets: sequential targets to find ancestors of
    :return: call graph ancestors of sequential targets
    """
    ancestors = set()

    def is_ancestor(module: Module) -> bool:
        if module in ancestors or module in targets:
            return True

        # eagerly compute list in order to avoid early stopping and :. missing ancestors
        _is_ancestor = any([is_ancestor(child) for child in module.children()])
        if _is_ancestor:
            ancestors.add(module)

        return _is_ancestor

    is_ancestor(model)
    return ancestors

graph_is_well_formed

graph_is_well_formed(graph: Graph) -> bool

A graph is well formed if and only if nodeA in NodeB.users <=> nodeB in Node.A.all_input_nodes

Parameters:

  • graph (Graph) –

    graph being checked

Returns:

  • bool –

    True if the graph is well formed, False otherwise

Source code in src/llmcompressor/pipelines/sequential/helpers.py
def graph_is_well_formed(graph: Graph) -> bool:
    """
    A graph is well formed if and only if
    `nodeA in NodeB.users <=> nodeB in Node.A.all_input_nodes`

    :param graph: graph being checked
    :return: True if the graph is well formed, False otherwise
    """
    for node in graph.nodes:
        for user in node.users:
            if node not in user.all_input_nodes:
                return False

        for input_node in node.all_input_nodes:
            if node not in input_node.users:
                return False

        if len(node.users) != len(set(node.users)) or len(node.all_input_nodes) != len(
            set(node.all_input_nodes)
        ):
            return False

    return True

handle_sequential_oom

handle_sequential_oom(func)

Catch ooms and suggest changing sequential targets

Source code in src/llmcompressor/pipelines/sequential/helpers.py
def handle_sequential_oom(func):
    """Catch ooms and suggest changing sequential targets"""

    @wraps(func)
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except torch.OutOfMemoryError as e:
            dataset_args = kwargs.get(
                "dataset_args", args[2] if len(args) > 2 else None
            )
            targets_per_subgraph = getattr(
                dataset_args, "sequential_targets_per_subgraph", None
            )
            if targets_per_subgraph == "auto":
                grouping_hint = (
                    "sequential_targets_per_subgraph='auto' estimates how many targets "
                    "fit in free memory; lowering `gpu_memory_utilization` leaves more "
                    "headroom for what the estimate misses. "
                )
            elif isinstance(targets_per_subgraph, int) and targets_per_subgraph > 1:
                grouping_hint = (
                    "sequential_targets_per_subgraph='auto' chooses as many targets "
                    "per subgraph as fit in free memory. "
                )
            else:
                # "auto" never puts fewer than one target in a subgraph, so it cannot
                # use less memory than one target per subgraph
                grouping_hint = ""

            raise torch.OutOfMemoryError(
                "Sequential pipeline ran out of memory. "
                "Please consider choosing a smaller module for `sequential_targets`, "
                "ex. 'Linear' for dense models. "
                "For MoE models with untraceable attention, "
                "use the attention module and individual expert class instead, "
                "ex. sequential_targets=['AttentionClass', 'ExpertClass'] with "
                "sequential_targets_per_subgraph set to batch multiple experts per "
                "subgraph and reduce memory overhead. "
                f"{grouping_hint}Choosing a smaller "
                "calibration dataset can also help: reduce `max_seq_length` "
                "(when unset, calibration samples are not truncated, so a few "
                "long samples can dominate memory) or `num_calibration_samples` "
                "(memory scales with sample count for modifiers that cache "
                "activations, such as AWQ)."
            ) from e

    return wrapper

partition_graph

partition_graph(
    model: Module, partitions: list[list[Node]]
) -> list[Subgraph]

Convert each partition into a Subgraph. Each Subgraph returns a dictionary mapping of output node names to their computed values. Note that the consumed_names attribute of each Subgraph remains empty, to be later populated by trace_consumed_names

Parameters:

  • model (Module) –

    model which owns the produced Subgraphs

  • partitions (list[list[Node]]) –

    list of partitions, where each partition is a list of nodes belonging to that partition

Returns:

  • list[Subgraph] –

    list of subgraphs in order of execution

Source code in src/llmcompressor/pipelines/sequential/helpers.py
def partition_graph(model: Module, partitions: list[list[Node]]) -> list[Subgraph]:
    """
    Convert each partition into a Subgraph. Each Subgraph returns a dictionary mapping
    of output node names to their computed values. Note that the `consumed_names`
    attribute of each Subgraph remains empty, to be later populated by
    `trace_consumed_names`

    :param model: model which owns the produced Subgraphs
    :param partitions: list of partitions, where each partition is a list of nodes
        belonging to that partition
    :return: list of subgraphs in order of execution
    """
    subgraphs = []

    # create subgraphs
    for partition_nodes in partitions:
        partition_set = set(partition_nodes)

        # create a new graph for the partition
        graph = Graph(model)
        node_map = {}

        # add placeholders for inputs not in this subgraph. use set to deduplicate
        new_input_nodes = {
            input_node
            for node in partition_nodes
            for input_node in node.all_input_nodes
            if input_node not in partition_set and input_node.op
        }
        for input_node in new_input_nodes:
            node_map[input_node] = graph.placeholder(input_node.name)

        # add the nodes to subgraph
        for node in partition_nodes:
            node_map[node] = graph.node_copy(node, lambda n: node_map[n])

        # add an output node to collect all subgraph outputs into a dictionary
        if len(graph.find_nodes(op="output")) <= 0:
            output_dict = {
                node.name: node_map[node]
                for node in partition_nodes
                if any(user not in partition_set for user in node.users.keys())
            }
            graph.output(output_dict)

        # save the subgraph for this partition
        graph.lint()
        input_names = set(node.name for node in graph.nodes if node.op == "placeholder")
        subgraphs.append(
            Subgraph(
                graph=graph,
                input_names=input_names,
                consumed_names=set(),  # populated later
            )
        )

        assert graph_is_well_formed(graph)

    return subgraphs

partition_subgraphs

partition_subgraphs(
    model: Module,
    graph: GraphModule,
    targets: set[Module],
    targets_per_subgraph: int | str = 1,
    dataloader: DataLoader | None = None,
    modifiers: list[Modifier] | None = None,
    dataset_args: DatasetArguments | None = None,
) -> list[Subgraph]

Partition a traced graph into subgraphs, where each sequential target belongs to exactly one subgraph and where executing each subgraph in order is equivalent to executing the original model

Parameters:

  • model (Module) –

    model which owns the produced Subgraphs

  • graph (GraphModule) –

    graph produced by trace_graph

  • targets (set[Module]) –

    sequential target modules produced by trace_graph

  • targets_per_subgraph (int | str, default: 1 ) –

    number of targets to include per subgraph, or "auto" to group as many consecutive targets as fit in device memory

  • dataloader (DataLoader | None, default: None ) –

    with "auto", the calibration data

  • modifiers (list[Modifier] | None, default: None ) –

    with "auto", the modifiers which will calibrate the subgraphs

  • dataset_args (DatasetArguments | None, default: None ) –

    with "auto", the arguments which set the memory budget

Returns:

  • list[Subgraph] –

    a list of Subgraphs in order of execution

Source code in src/llmcompressor/pipelines/sequential/helpers.py
def partition_subgraphs(
    model: Module,
    graph: GraphModule,
    targets: set[Module],
    targets_per_subgraph: int | str = 1,
    dataloader: "DataLoader | None" = None,
    modifiers: list["Modifier"] | None = None,
    dataset_args: "DatasetArguments | None" = None,
) -> list[Subgraph]:
    """
    Partition a traced graph into subgraphs, where each sequential target belongs to
    exactly one subgraph and where executing each subgraph in order is equivalent to
    executing the original model

    :param model: model which owns the produced Subgraphs
    :param graph: graph produced by `trace_graph`
    :param targets: sequential target modules produced by `trace_graph`
    :param targets_per_subgraph: number of targets to include per subgraph, or "auto"
        to group as many consecutive targets as fit in device memory
    :param dataloader: with "auto", the calibration data
    :param modifiers: with "auto", the modifiers which will calibrate the subgraphs
    :param dataset_args: with "auto", the arguments which set the memory budget
    :return: a list of Subgraphs in order of execution
    """
    if targets == {model}:
        # the root owns every module, see `trace_graph`
        return [
            Subgraph(
                graph=graph.graph, input_names=graph.input_names, consumed_names=set()
            )
        ]

    target_nodes = find_target_nodes(graph, targets)
    num_target_nodes = len(target_nodes)
    if num_target_nodes != len(targets):
        logger.warning(
            f"Expected {len(targets)} sequential targets in the traced graph, but "
            f"found {num_target_nodes}. This is likely due to having wrapped code "
            "which calls sequential targets"
        )

    node_memory, max_memory = None, None
    if targets_per_subgraph == "auto":
        if dataloader is None or modifiers is None or dataset_args is None:
            raise ValueError(
                'sequential_targets_per_subgraph="auto" requires the dataloader, '
                "modifiers and dataset arguments to estimate memory"
            )

        node_modules = {
            node: get_node_modules(model, node) for node in graph.graph.nodes
        }
        plan = plan_subgraph_memory(
            model, node_modules, dataloader, modifiers, dataset_args, targets
        )
        if plan is None:
            targets_per_subgraph = 1
        else:
            node_memory, max_memory = plan

    # As currently implemented, `topological_partition` generates an extra subgraph at
    # the beginning which does not contain a target. This adds a little more runtime,
    # and could be folded into the first subgraph in the future
    partitions = topological_partition(
        graph, targets, targets_per_subgraph, node_memory, max_memory
    )
    if node_memory is not None:
        log_partitions(partitions, target_nodes, node_memory, max_memory)

    subgraphs = partition_graph(model, partitions)
    trace_consumed_names(subgraphs)

    return subgraphs

populate_concrete_args

populate_concrete_args(
    model: Module, sample_input: dict
) -> dict

Creates concrete args which, unlike the equivalent function provided by transformers.utils.fx, creates default values for variadic arguments, which are needed by some models.

Parameters:

  • model (Module) –

    model being traced

  • sample_input (dict) –

    values used to symbolically trace the model. All arguments to the model.forward function which are not in the sample_input are considered concrete args

Returns:

  • dict –

    dictionary mapping concrete argument names to their default values

Source code in src/llmcompressor/pipelines/sequential/helpers.py
def populate_concrete_args(model: Module, sample_input: dict) -> dict:
    """
    Creates concrete args which, unlike the equivalent function provided by
    transformers.utils.fx, creates default values for variadic arguments, which are
    needed by some models.

    :param model: model being traced
    :param sample_input: values used to symbolically trace the model. All arguments
        to the model.forward function which are not in the sample_input are considered
        concrete args
    :return: dictionary mapping concrete argument names to their default values
    """
    sig = inspect.signature(model.forward)

    concrete_args = {}
    for parameter in sig.parameters.values():
        if parameter.name in sample_input:
            continue
        if parameter.kind == inspect._ParameterKind.VAR_POSITIONAL:
            value = list()
        elif parameter.kind == inspect._ParameterKind.VAR_KEYWORD:
            value = dict()
        elif parameter.name == "use_cache":
            value = False
        else:
            value = parameter.default

        concrete_args[parameter.name] = value

    return concrete_args

topological_partition

topological_partition(
    graph: GraphModule,
    targets: set[Module],
    targets_per_subgraph: int | str = 1,
    node_memory: dict[Node, int] | None = None,
    max_memory: int | None = None,
) -> list[list[Node]]

Partition the graph into partitions such that each target belongs to exactly one partition and executing each partition depends only on intermediate values produced by executing the partitions before it.

Parameters:

  • graph (GraphModule) –

    graph being partitioned

  • targets (set[Module]) –

    target modules which will be assigned to disjoint partitions

  • targets_per_subgraph (int | str, default: 1 ) –

    number of targets to include per subgraph, or "auto" to fill each partition until its nodes' memory would exceed max_memory. A partition is only cut once it holds a target, so only the nodes before the first target or after the last one can end up in a partition without one

  • node_memory (dict[Node, int] | None, default: None ) –

    with "auto", the memory each node onloads and holds

  • max_memory (int | None, default: None ) –

    with "auto", the memory available to each partition

Returns:

  • list[list[Node]] –

    list of partitions, where each partition is a list of nodes belonging to that partition

Source code in src/llmcompressor/pipelines/sequential/helpers.py
def topological_partition(
    graph: GraphModule,
    targets: set[Module],
    targets_per_subgraph: int | str = 1,
    node_memory: dict[Node, int] | None = None,
    max_memory: int | None = None,
) -> list[list[Node]]:
    """
    Partition the graph into partitions such that each `target` belongs to exactly one
    partition and executing each partition depends only on intermediate values produced
    by executing the partitions before it.

    :param graph: graph being partitioned
    :param targets: target modules which will be assigned to disjoint partitions
    :param targets_per_subgraph: number of targets to include per subgraph, or "auto"
        to fill each partition until its nodes' memory would exceed `max_memory`. A
        partition is only cut once it holds a target, so only the nodes before the
        first target or after the last one can end up in a partition without one
    :param node_memory: with "auto", the memory each node onloads and holds
    :param max_memory: with "auto", the memory available to each partition
    :return: list of partitions, where each partition is a list of nodes belonging to
        that partition
    """
    assert graph_is_well_formed(graph.graph)
    target_nodes = find_target_nodes(graph, targets)

    use_memory = targets_per_subgraph == "auto"
    if use_memory and (node_memory is None or max_memory is None):
        raise ValueError(
            'targets_per_subgraph="auto" requires node_memory and max_memory'
        )
    if not use_memory and targets_per_subgraph <= 0:
        raise ValueError(
            "targets_per_subgraph is required to be greater than or equal to one"
        )

    partitions: list[list[Node]] = [[]]
    node_to_partition: dict[Node, int] = {}
    remaining_indegrees = {
        node: sum(1 for inp in node.all_input_nodes if inp.op != "get_attr")
        for node in graph.graph.nodes
    }
    partition_index = 0  # global counter
    targets_seen = 0  # number of targets encountered so far
    partition_memory = 0  # memory of the partition being filled, with "auto"

    # start with graph input nodes,
    # but delay the `get_attr` nodes as long as possible
    queue = deque(
        node
        for node in graph.graph.nodes
        if remaining_indegrees[node] == 0 and node.op != "get_attr"
    )
    while len(queue) > 0:
        node = queue.popleft()

        is_target = node in target_nodes
        cost = node_memory.get(node, 0) if use_memory else 0

        # put all nodes prior to first target into separate subgraph
        is_head = is_target and partition_index == 0 and len(partitions[0]) > 0

        if use_memory:
            # finish creating subgraph when this node would not fit in memory, once
            # the subgraph holds a target. Nodes which onload nothing stay in the
            # subgraph of the node before them
            is_complete = (
                cost > 0 and targets_seen > 0 and partition_memory + cost > max_memory
            )
        else:
            # finish creating subgraph when number of targets has been seen
            is_complete = is_target and targets_seen >= targets_per_subgraph

        if is_head or is_complete:
            partition_index += 1
            partitions.append([])
            targets_seen = 0
            partition_memory = 0

        # assign to partition
        partitions[partition_index].append(node)
        node_to_partition[node] = partition_index
        partition_memory += cost

        # increment after assignment so is_complete fires after the target is placed
        if is_target:
            targets_seen += 1

        # recurse on last indegree only in order to guarantee that
        # the node is assigned to maximal partition
        for user in node.users:
            remaining_indegrees[user] -= 1
            if remaining_indegrees[user] == 0:
                queue.append(user)

    # an ideal implementation would involve implicitly consolidating partition indices
    # so that each node is assigned to the maximum partition possible (in order to delay
    # execution as long as possible), but saving these nodes for last covers the most
    # common and costly case (get_attr)
    for node in graph.graph.find_nodes(op="get_attr"):
        user_partitions = []
        for user in node.users:
            if user in node_to_partition:
                user_partitions.append(node_to_partition[user])

        # workaround
        if len(user_partitions):
            partition_index = min(user_partitions)
            partitions[partition_index].insert(0, node)
            node_to_partition[node] = partition_index

    return partitions

trace_consumed_names

trace_consumed_names(subgraphs: list[Subgraph])

Populate the consumed_names attribute of each Subgraph according to when inputs are last used in order to vacate the intermediates cache and save memory

Parameters:

  • subgraphs (list[Subgraph]) –

    list of subgraphs with empty consumed_names attributes

Source code in src/llmcompressor/pipelines/sequential/helpers.py
def trace_consumed_names(subgraphs: list[Subgraph]):
    """
    Populate the `consumed_names` attribute of each Subgraph according to when inputs
    are last used in order to vacate the `intermediates` cache and save memory

    :param subgraphs: list of subgraphs with empty `consumed_names` attributes
    """
    # The first occurrence in reverse order is the final use in execution order.
    seen_names: set[str] = set()
    for subgraph in reversed(subgraphs):
        subgraph.consumed_names.update(subgraph.input_names - seen_names)
        seen_names.update(subgraph.input_names)

trace_graph

trace_graph(
    model: PreTrainedModel,
    sample_input: dict[str, Any],
    sequential_targets: list[str],
    ignore: list[str],
    eager_attention: bool = False,
) -> tuple[GraphModule, set[Module]]

Trace a model into a graph in which each sequential target is a leaf node. Tracing is the expensive step, so the returned graph can be partitioned more than once, for example with different numbers of targets per subgraph

Parameters:

  • model (PreTrainedModel) –

    model being traced

  • sample_input (dict[str, Any]) –

    inputs whose values will change during execution but whose len, bool, and contains values are assumed constant across batches

  • sequential_targets (list[str]) –

    list of patterns matching sequential targets. Detected attention modules are also used as targets when not contained by a requested target.

  • ignore (list[str]) –

    function and method names to skip during tracing

  • eager_attention (bool, default: False ) –

    whether to force eager attention while tracing

Returns:

  • tuple[GraphModule, set[Module]] –

    the traced graph and the set of sequential target modules

Source code in src/llmcompressor/pipelines/sequential/helpers.py
def trace_graph(
    model: PreTrainedModel,
    sample_input: dict[str, Any],
    sequential_targets: list[str],
    ignore: list[str],
    eager_attention: bool = False,
) -> tuple[GraphModule, set[Module]]:
    """
    Trace a model into a graph in which each sequential target is a leaf node.
    Tracing is the expensive step, so the returned graph can be partitioned more than
    once, for example with different numbers of targets per subgraph

    :param model: model being traced
    :param sample_input: inputs whose values will change during execution but whose
        __len__, __bool__, and __contains__ values are assumed constant across batches
    :param sequential_targets: list of patterns matching sequential targets. Detected
        attention modules are also used as targets when not contained by a requested
        target.
    :param ignore: function and method names to skip during tracing
    :param eager_attention: whether to force eager attention while tracing
    :return: the traced graph and the set of sequential target modules
    """
    targets = _resolve_sequential_targets(model, sequential_targets)

    if targets == {model}:
        # FX traces the root's forward directly, without consulting is_leaf_module, so
        # the root is left untraced and `partition_subgraphs` keeps it as one subgraph
        whole_model = _create_whole_model_subgraph(set(sample_input))
        graph = GraphModule(model, whole_model.graph)
        graph.input_names = whole_model.input_names
        return graph, targets

    ancestors = get_sequential_ancestors(model, targets)

    # initialize arguments
    tracer = SequentialTracer(ancestors)
    concrete_args = populate_concrete_args(model, sample_input)

    with contextlib.ExitStack() as stack:
        # calibration context
        stack.enter_context(calibration_forward_context(model, eager_attention))
        stack.enter_context(HooksMixin.disable_hooks())

        # flags useful for tracing
        # Attention uses the model's configured implementation unless
        # `eager_attention` is enabled.
        stack.enter_context(patch_attr(torch.compiler, "_is_compiling_flag", True))
        stack.enter_context(patch_attr(torch.compiler, "_is_exporting_flag", True))

        # autowrap forwards
        stack.enter_context(autowrap_forwards(ancestors, ignore))

        # avoid bug where pytorch cannot handle wrapped root functions
        unwrapped = inspect.unwrap(model.forward).__get__(model)
        stack.enter_context(patch_attr(model, "forward", unwrapped))
        stack.enter_context(patch_attr(type(model), "forward", unwrapped.__func__))
        assert isinstance(model.forward, MethodType)
        assert isinstance(type(model).forward, FunctionType)

        # avoid device movement during tracing
        stack.enter_context(disable_onloading())

        with append_autowrap_source_on_fail():
            graph = GraphModule(
                model,
                tracer.trace(
                    model,
                    dummy_inputs=sample_input,
                    concrete_args=concrete_args,
                    complete_concrete_args_with_inputs_not_in_dummy_inputs=False,
                    # bug in trace throws an error for variadic
                    # args and kwargs in function signature
                ),
            )

    # copy metadata
    graph.config = model.config
    graph.class_for_deserialization = model.__class__
    graph.device = model.device

    # Modules with parameters which are neither ancestors nor owned by a subgraph were
    # not seen during tracing (e.g. a wrapped function failed to execute on meta).
    # Every partition of the graph owns the same modules, so this is checked here
    unowned = [
        name
        for name, module in find_modules_outside_graph(model, graph).items()
        if module not in ancestors and module._parameters
    ]
    if unowned:
        logger.warning(
            f"Modules {unowned} do not belong to any subgraph and will be kept "
            "onloaded for the whole calibration",
            log_once=True,
        )

    return graph, targets

trace_subgraphs

trace_subgraphs(
    model: PreTrainedModel,
    sample_input: dict[str, Any],
    sequential_targets: list[str],
    ignore: list[str],
    targets_per_subgraph: int = 1,
    eager_attention: bool = False,
) -> list[Subgraph]

Trace a model to produce subgraphs, where each sequential target belongs to exactly one subgraph and where executing each subgraph in order is equivalent to executing the original model

Parameters:

  • model (PreTrainedModel) –

    model being traced

  • sample_input (dict[str, Any]) –

    inputs whose values will change during execution but whose len, bool, and contains values are assumed constant across batches

  • sequential_targets (list[str]) –

    list of patterns matching sequential targets. Detected attention modules are also used as targets when not contained by a requested target.

  • ignore (list[str]) –

    function and method names to skip during tracing

  • targets_per_subgraph (int, default: 1 ) –

    number of targets to include per subgraph

  • eager_attention (bool, default: False ) –

    whether to force eager attention while tracing

Returns:

  • list[Subgraph] –

    a list of Subgraphs in order of execution

Source code in src/llmcompressor/pipelines/sequential/helpers.py
def trace_subgraphs(
    model: PreTrainedModel,
    sample_input: dict[str, Any],
    sequential_targets: list[str],
    ignore: list[str],
    targets_per_subgraph: int = 1,
    eager_attention: bool = False,
) -> list[Subgraph]:
    """
    Trace a model to produce subgraphs, where each sequential target belongs to exactly
    one subgraph and where executing each subgraph in order is equivalent to executing
    the original model

    :param model: model being traced
    :param sample_input: inputs whose values will change during execution but whose
        __len__, __bool__, and __contains__ values are assumed constant across batches
    :param sequential_targets: list of patterns matching sequential targets. Detected
        attention modules are also used as targets when not contained by a requested
        target.
    :param ignore: function and method names to skip during tracing
    :param targets_per_subgraph: number of targets to include per subgraph
    :param eager_attention: whether to force eager attention while tracing
    :return: a list of Subgraphs in order of execution
    """
    graph, targets = trace_graph(
        model, sample_input, sequential_targets, ignore, eager_attention
    )
    return partition_subgraphs(model, graph, targets, targets_per_subgraph)