Coverage for hierarchicalsoftmax/inference.py: 100.00%
106 statements
« prev ^ index » next coverage.py v7.17.5, created at 2026-11-26 12:41 +0000
« prev ^ index » next coverage.py v7.17.5, created at 2026-11-26 12:41 +0000
1from typing import List, Optional
2import torch
3from pathlib import Path
4from anytree import PreOrderIter
5from rich.progress import track
7from . import nodes
8from .dotexporter import ThresholdDotExporter
11class ShapeError(RuntimeError):
12 """
13 Raised when the shape of a tensor is different to what is expected.
14 """
16def node_probabilities(prediction_tensor:torch.Tensor, root:nodes.SoftmaxNode, progress_bar:bool=False) -> torch.Tensor:
17 """
18 Takes the prediction scores for a number of samples and converts it to a list of probabilities of nodes in the tree.
19 """
20 probabilities = torch.zeros(size=prediction_tensor.shape, device=prediction_tensor.device)
22 if root.softmax_start_index is None:
23 raise nodes.IndexNotSetError(f"The index of the root node {root} has not been set. Call `set_indexes` on this object.")
25 if prediction_tensor.shape[-1] != root.layer_size:
26 raise ShapeError(
27 f"The predictions tensor given to {__name__} has final dimensions of {prediction_tensor.shape[-1]}. "
28 f"That is not compatible with the root node which expects prediciton tensors to have a final dimension of {root.layer_size}."
29 )
31 for node in track(PreOrderIter(root)) if progress_bar else PreOrderIter(root):
32 if node.is_leaf:
33 continue
34 elif node == root:
35 my_probability = 1.0
36 elif node.index_in_softmax_layer != None:
37 my_probability = probabilities[:,node.index_in_softmax_layer]
38 my_probability = my_probability[:,None]
40 if len(node.children) == 1:
41 # If this has just one child, then skip it
42 continue
44 softmax_probabilities = torch.softmax(
45 prediction_tensor[:,node.softmax_start_index:node.softmax_end_index],
46 dim=1,
47 )
49 probabilities[:,node.softmax_start_index:node.softmax_end_index] = softmax_probabilities * my_probability
51 return probabilities
54def leaf_probabilities(prediction_tensor:torch.Tensor, root:nodes.SoftmaxNode) -> torch.Tensor:
55 """
56 Takes the prediction scores for a number of samples and converts it to a list of probabilities of nodes in the tree.
57 """
58 probabilities = node_probabilities(prediction_tensor, root=root)
59 return torch.index_select(probabilities, 1, root.leaf_indexes.to(probabilities.device))
62def greedy_predictions(
63 prediction_tensor:torch.Tensor,
64 root:nodes.SoftmaxNode,
65 max_depth:Optional[int]=None,
66 threshold:Optional[float]=None,
67 progress_bar:bool=False,
68 ) -> List[nodes.SoftmaxNode]:
69 """
70 Takes the prediction scores for a number of samples and converts it to a list of predictions of nodes in the tree.
72 Predictions use the `greedy` method which means that it chooses the greatest prediction score at each level of the tree.
74 Args:
75 prediction_tensor (torch.Tensor): The output from the softmax layer.
76 Shape (samples, root.layer_size)
77 Works with raw scores or probabilities.
78 root (SoftmaxNode): The root softmax node. Needs `set_indexes` to have been called.
79 prediction_tensor (torch.Tensor): The predictions coming from the softmax layer. Shape (samples, root.layer_size)
80 max_depth (int, optional): If set, then it only gives predictions at a maximum of this number of levels from the root.
81 threshold (int, optional): If set, then it only gives predictions where the value at the node is greater than this threshold.
82 Designed for use with probabilities.
84 Returns:
85 List[nodes.SoftmaxNode]: A list of nodes predicted for each sample.
86 """
87 prediction_nodes = []
89 if isinstance(prediction_tensor, tuple) and len(prediction_tensor) == 1:
90 prediction_tensor = prediction_tensor[0]
92 if root.softmax_start_index is None:
93 raise nodes.IndexNotSetError(f"The index of the root node {root} has not been set. Call `set_indexes` on this object.")
95 if prediction_tensor.shape[-1] != root.layer_size:
96 raise ShapeError(
97 f"The predictions tensor given to {__name__} has final dimensions of {prediction_tensor.shape[-1]}. "
98 f"That is not compatible with the root node which expects prediciton tensors to have a final dimension of {root.layer_size}."
99 )
101 for predictions in track(prediction_tensor) if progress_bar else prediction_tensor:
102 node = root
103 depth = 1
104 while (node.children):
105 if len(node.children) == 1:
106 # if this has just one child, then we don't check the prediction
107 prediction_child_index = 0
108 else:
109 # This would be better if we could use torch.argmax but it doesn't work with MPS in the production version of pytorch
110 # See https://github.com/pytorch/pytorch/issues/98191
111 # https://github.com/pytorch/pytorch/pull/104374
112 prediction_child_index = torch.max(predictions[node.softmax_start_index:node.softmax_end_index], dim=0).indices
114 # Stop if the prediction is below the threshold
115 # A single child has no slot in the softmax layer (it carries its parent's probability), so skip the check
116 if threshold and len(node.children) > 1 and predictions[node.softmax_start_index+prediction_child_index] < threshold:
117 break
119 node = node.children[prediction_child_index]
121 # Stop if we have reached the maximum depth
122 if max_depth and depth >= max_depth:
123 break
125 depth += 1
127 prediction_nodes.append(node)
129 return prediction_nodes
132def greedy_lineage_probabilities(
133 prediction_tensor:torch.Tensor,
134 root:nodes.SoftmaxNode,
135 max_depth:Optional[int]=None,
136 threshold:Optional[float]=None,
137 progress_bar:bool=False,
138 ) -> List[nodes.SoftmaxNode]:
139 """
140 Takes the prediction scores for a number of samples and converts it to a list of predictions of nodes in the tree.
142 Predictions use the `greedy` method which means that it chooses the greatest prediction score at each level of the tree.
144 Args:
145 prediction_tensor (torch.Tensor): The output from the softmax layer.
146 Shape (samples, root.layer_size)
147 Works with raw scores or probabilities.
148 root (SoftmaxNode): The root softmax node. Needs `set_indexes` to have been called.
149 prediction_tensor (torch.Tensor): The predictions coming from the softmax layer. Shape (samples, root.layer_size)
150 max_depth (int, optional): If set, then it only gives predictions at a maximum of this number of levels from the root.
151 threshold (int, optional): If set, then it only gives predictions where the value at the node is greater than this threshold.
152 Designed for use with probabilities.
154 Returns:
155 List[List[Tuple[nodes.SoftmaxNode, float]]]: A list of nodes predicted for each sample with their probabilities.
156 """
157 prediction_lineages = []
159 if isinstance(prediction_tensor, tuple) and len(prediction_tensor) == 1:
160 prediction_tensor = prediction_tensor[0]
162 if root.softmax_start_index is None:
163 raise nodes.IndexNotSetError(f"The index of the root node {root} has not been set. Call `set_indexes` on this object.")
165 if prediction_tensor.shape[-1] != root.layer_size:
166 raise ShapeError(
167 f"The predictions tensor given to {__name__} has final dimensions of {prediction_tensor.shape[-1]}. "
168 f"That is not compatible with the root node which expects prediciton tensors to have a final dimension of {root.layer_size}."
169 )
171 for predictions in track(prediction_tensor) if progress_bar else prediction_tensor:
172 node = root
173 depth = 1
174 probability = 1.0 # Start with the root node having a probability of 1.0
175 my_lineage = []
176 while (node.children):
177 if len(node.children) == 1:
178 # if this has just one child, then we don't check the prediction
179 prediction_child_index = 0
180 else:
181 # This would be better if we could use torch.argmax but it doesn't work with MPS in the production version of pytorch
182 # See https://github.com/pytorch/pytorch/issues/98191
183 # https://github.com/pytorch/pytorch/pull/104374
184 child_probabilities = torch.softmax(
185 predictions[node.softmax_start_index:node.softmax_end_index],
186 dim=0,
187 )
188 prediction_child_index = torch.max(child_probabilities, dim=0).indices
189 probability *= child_probabilities[prediction_child_index].item()
191 # Stop if the probability is below the threshold
192 if threshold and probability < threshold:
193 break
195 node = node.children[prediction_child_index]
197 my_lineage.append(
198 (node, probability)
199 )
201 # Stop if we have reached the maximum depth
202 if max_depth and depth >= max_depth:
203 break
205 depth += 1
207 prediction_lineages.append(my_lineage)
209 return prediction_lineages
212def greedy_prediction_node_ids(
213 prediction_tensor:torch.Tensor,
214 root:nodes.SoftmaxNode,
215 max_depth:Optional[int]=None,
216 threshold:Optional[float]=None,
217 progress_bar:bool=False,
218 ) -> List[int]:
219 """
220 Takes the prediction scores for a number of samples and converts it to a list of predictions of nodes in the tree.
222 Predictions use the `greedy` method which means that it chooses the greatest prediction score at each level of the tree.
224 Args:
225 root (SoftmaxNode): The root softmax node. Needs `set_indexes` to have been called.
226 prediction_tensor (torch.Tensor): The predictions coming from the softmax layer. Shape (samples, root.layer_size)
227 max_depth (int, optional): If set, then it only gives predictions at a maximum of this number of levels from the root.
229 Returns:
230 List[int]: A list of node IDs predicted for each sample.
231 """
232 prediction_nodes = greedy_predictions(
233 prediction_tensor=prediction_tensor,
234 root=root,
235 max_depth=max_depth,
236 threshold=threshold,
237 progress_bar=progress_bar,)
238 return root.get_node_ids(prediction_nodes)
241def greedy_prediction_node_ids_tensor(prediction_tensor:torch.Tensor, root:nodes.SoftmaxNode, max_depth:Optional[int]=None) -> torch.Tensor:
242 node_ids = greedy_prediction_node_ids(prediction_tensor=prediction_tensor, root=root, max_depth=max_depth)
243 return torch.as_tensor( node_ids, dtype=int)
246def render_probabilities(
247 root:nodes.SoftmaxNode,
248 filepaths:List[Path]=None,
249 prediction_color="red",
250 non_prediction_color="gray",
251 prediction_tensor:torch.Tensor=None,
252 probabilities:torch.Tensor=None,
253 predictions:List[nodes.SoftmaxNode]=None,
254 horizontal:bool=True,
255 threshold:float=0.005,
256 ) -> List[ThresholdDotExporter]:
257 """
258 Renders the probabilities of each node in the tree as a graphviz graph.
260 See https://anytree.readthedocs.io/en/latest/_modules/anytree/exporter/dotexporter.html for more information.
262 Args:
263 prediction_tensor (torch.Tensor): The output activations from the softmax layer. Shape (samples, root.layer_size)
264 root (SoftmaxNode): The root softmax node. Needs `set_indexes` to have been called.
265 filepaths (List[Path], optional): Paths to locations where the files can be saved.
266 Can have extension .dot or another format which can be interpreted by GraphViz such as .png or .svg.
267 Defaults to None so that files are not saved.
268 prediction_color (str, optional): The color for the greedy prediction nodes and edges. Defaults to "red".
269 non_prediction_color (str, optional): The color for the edges which weren't predicted. Defaults to "gray".
271 Returns:
272 List[DotExporter]: The list of rendered graphs.
273 """
274 if probabilities is None:
275 assert prediction_tensor is not None, "Either `prediction_tensor` or `probabilities` must be given."
276 probabilities = node_probabilities(prediction_tensor, root=root)
278 if predictions is None:
279 assert prediction_tensor is not None, "Either `prediction_tensor` or `node_probabilities` must be given."
280 predictions = greedy_predictions(prediction_tensor, root=root)
282 graphs = []
283 for my_probabilities, my_prediction in zip(probabilities, predictions):
284 greedy_nodes = my_prediction.ancestors + (my_prediction,)
285 graphs.append(ThresholdDotExporter(
286 root,
287 probabilities=my_probabilities,
288 greedy_nodes=greedy_nodes,
289 horizontal=horizontal,
290 prediction_color=prediction_color,
291 non_prediction_color=non_prediction_color,
292 threshold=threshold,
293 ))
295 if filepaths:
296 for graph, filepath in zip(graphs, filepaths):
297 filepath = Path(filepath)
298 filepath.parent.mkdir(exist_ok=True, parents=True)
299 if filepath.suffix == ".dot":
300 graph.to_dotfile(str(filepath))
301 else:
302 graph.to_picture(str(filepath))
304 return graphs