Resolve a SharedQuantizationSpec into a concrete QuantizationSpecBase. Resolution strategy: 1) If `spec` is not a SharedQuantizationSpec, return it directly. 2) If it *is* a SharedQuantizationSpec, use `spec.edge_or_node` to locate the source node where the concrete qs
(
spec: Optional[QuantizationSpecBase],
visited: Optional[Set[torch.fx.Node]] = None,
)
| 108 | |
| 109 | |
| 110 | def _resolve_shared_qspec( |
| 111 | spec: Optional[QuantizationSpecBase], |
| 112 | visited: Optional[Set[torch.fx.Node]] = None, |
| 113 | ) -> Optional[QuantizationSpecBase]: |
| 114 | """ |
| 115 | Resolve a SharedQuantizationSpec into a concrete QuantizationSpecBase. |
| 116 | |
| 117 | Resolution strategy: |
| 118 | 1) If `spec` is not a SharedQuantizationSpec, return it directly. |
| 119 | 2) If it *is* a SharedQuantizationSpec, use `spec.edge_or_node` to locate |
| 120 | the source node where the concrete qspec originates. |
| 121 | 3) If second_node exists, choose to the |
| 122 | `second_node`'s `input_qspec_map[source_node]`, then resolve recursively. |
| 123 | 4) Using the source node's `annotation.output_qspec`. If that is |
| 124 | also shared, resolve recursively. |
| 125 | 5) If nothing can be resolved, return None. |
| 126 | |
| 127 | A `visited` set is used to avoid infinite recursion when malformed |
| 128 | annotations or cyclic references exist. |
| 129 | |
| 130 | Args: |
| 131 | spec: The qspec to be resolved (SharedQuantizationSpec). |
| 132 | visited: Internal recursion guard to detect cycles (optional). |
| 133 | |
| 134 | Returns: |
| 135 | A concrete QuantizationSpec if successfully resolved; otherwise None. |
| 136 | """ |
| 137 | if spec is None: |
| 138 | return None |
| 139 | |
| 140 | if not isinstance(spec, SharedQuantizationSpec): |
| 141 | # Already concrete; nothing to resolve. |
| 142 | return spec |
| 143 | |
| 144 | visited = visited or set() |
| 145 | |
| 146 | # `edge_or_node` may be a (node, edge) tuple or a node directly. |
| 147 | edge_or_node = spec.edge_or_node |
| 148 | second_node = None |
| 149 | if isinstance(edge_or_node, tuple): |
| 150 | source_node, second_node = edge_or_node |
| 151 | else: |
| 152 | source_node = edge_or_node |
| 153 | |
| 154 | # Cycle guard to avoid infinite recursion. |
| 155 | if source_node in visited: |
| 156 | return None |
| 157 | visited.add(source_node) |
| 158 | |
| 159 | # First, try to look up the spec from the current node's input map. |
| 160 | # This is because in the case of mix precision, the second node |
| 161 | # might have a specific quantization spec for the input. |
| 162 | if second_node: |
| 163 | sec_ann = second_node.meta.get(Q_ANNOTATION_KEY, None) |
| 164 | if sec_ann and (in_spec := sec_ann.input_qspec_map.get(source_node, None)): |
| 165 | return _resolve_shared_qspec(in_spec, visited) |
| 166 | |
| 167 | # use the source node's own output qspec. |
no test coverage detected