1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
|
# mypy: allow-untyped-defs
"""This file defines an additional layer of abstraction on top of the SARIF OM."""
from __future__ import annotations
import dataclasses
import enum
import logging
from typing import Mapping, Sequence
from torch.onnx._internal.diagnostics.infra import formatter, sarif
class Level(enum.IntEnum):
"""The level of a diagnostic.
This class is used to represent the level of a diagnostic. The levels are defined
by the SARIF specification, and are not modifiable. For alternative categories,
please use infra.Tag instead. When selecting a level, please consider the following
guidelines:
- NONE: Informational result that does not indicate the presence of a problem.
- NOTE: An opportunity for improvement was found.
- WARNING: A potential problem was found.
- ERROR: A serious problem was found.
This level is a subclass of enum.IntEnum, and can be used as an integer. Its integer
value maps to the logging levels in Python's logging module. The mapping is as
follows:
Level.NONE = logging.DEBUG = 10
Level.NOTE = logging.INFO = 20
Level.WARNING = logging.WARNING = 30
Level.ERROR = logging.ERROR = 40
"""
NONE = 10
NOTE = 20
WARNING = 30
ERROR = 40
levels = Level
class Tag(enum.Enum):
"""The tag of a diagnostic. This class can be inherited to define custom tags."""
class PatchedPropertyBag(sarif.PropertyBag):
"""Key/value pairs that provide additional information about the object.
The definition of PropertyBag via SARIF spec is "A property bag is an object (section 3.6)
containing an unordered set of properties with arbitrary names." However it is not
reflected in the json file, and therefore not captured by the python representation.
This patch adds additional **kwargs to the `__init__` method to allow recording
arbitrary key/value pairs.
"""
def __init__(self, tags: list[str] | None = None, **kwargs):
super().__init__(tags=tags)
self.__dict__.update(kwargs)
@dataclasses.dataclass(frozen=True)
class Rule:
id: str
name: str
message_default_template: str
short_description: str | None = None
full_description: str | None = None
full_description_markdown: str | None = None
help_uri: str | None = None
@classmethod
def from_sarif(cls, **kwargs):
"""Returns a rule from the SARIF reporting descriptor."""
short_description = kwargs.get("short_description", {}).get("text")
full_description = kwargs.get("full_description", {}).get("text")
full_description_markdown = kwargs.get("full_description", {}).get("markdown")
help_uri = kwargs.get("help_uri")
rule = cls(
id=kwargs["id"],
name=kwargs["name"],
message_default_template=kwargs["message_strings"]["default"]["text"],
short_description=short_description,
full_description=full_description,
full_description_markdown=full_description_markdown,
help_uri=help_uri,
)
return rule
def sarif(self) -> sarif.ReportingDescriptor:
"""Returns a SARIF reporting descriptor of this Rule."""
short_description = (
sarif.MultiformatMessageString(text=self.short_description)
if self.short_description is not None
else None
)
full_description = (
sarif.MultiformatMessageString(
text=self.full_description, markdown=self.full_description_markdown
)
if self.full_description is not None
else None
)
return sarif.ReportingDescriptor(
id=self.id,
name=self.name,
short_description=short_description,
full_description=full_description,
help_uri=self.help_uri,
)
def format(self, level: Level, *args, **kwargs) -> tuple[Rule, Level, str]:
"""Returns a tuple of (rule, level, message) for a diagnostic.
This method is used to format the message of a diagnostic. The message is
formatted using the default template of this rule, and the arguments passed in
as `*args` and `**kwargs`. The level is used to override the default level of
this rule.
"""
return (self, level, self.format_message(*args, **kwargs))
def format_message(self, *args, **kwargs) -> str:
"""Returns the formatted default message of this Rule.
This method should be overridden (with code generation) by subclasses to reflect
the exact arguments needed by the message template. This is a helper method to
create the default message for a diagnostic.
"""
return self.message_default_template.format(*args, **kwargs)
@dataclasses.dataclass
class Location:
uri: str | None = None
line: int | None = None
message: str | None = None
start_column: int | None = None
end_column: int | None = None
snippet: str | None = None
function: str | None = None
def sarif(self) -> sarif.Location:
"""Returns the SARIF representation of this location."""
return sarif.Location(
physical_location=sarif.PhysicalLocation(
artifact_location=sarif.ArtifactLocation(uri=self.uri),
region=sarif.Region(
start_line=self.line,
start_column=self.start_column,
end_column=self.end_column,
snippet=sarif.ArtifactContent(text=self.snippet),
),
),
message=sarif.Message(text=self.message)
if self.message is not None
else None,
)
@dataclasses.dataclass
class StackFrame:
location: Location
def sarif(self) -> sarif.StackFrame:
"""Returns the SARIF representation of this stack frame."""
return sarif.StackFrame(location=self.location.sarif())
@dataclasses.dataclass
class Stack:
"""Records a stack trace. The frames are in order from newest to oldest stack frame."""
frames: list[StackFrame] = dataclasses.field(default_factory=list)
message: str | None = None
def sarif(self) -> sarif.Stack:
"""Returns the SARIF representation of this stack."""
return sarif.Stack(
frames=[frame.sarif() for frame in self.frames],
message=sarif.Message(text=self.message)
if self.message is not None
else None,
)
@dataclasses.dataclass
class ThreadFlowLocation:
"""Records code location and the initial state."""
location: Location
state: Mapping[str, str]
index: int
stack: Stack | None = None
def sarif(self) -> sarif.ThreadFlowLocation:
"""Returns the SARIF representation of this thread flow location."""
return sarif.ThreadFlowLocation(
location=self.location.sarif(),
state=self.state,
stack=self.stack.sarif() if self.stack is not None else None,
)
@dataclasses.dataclass
class Graph:
"""A graph of diagnostics.
This class stores the string representation of a model graph.
The `nodes` and `edges` fields are unused in the current implementation.
"""
graph: str
name: str
description: str | None = None
def sarif(self) -> sarif.Graph:
"""Returns the SARIF representation of this graph."""
return sarif.Graph(
description=sarif.Message(text=self.graph),
properties=PatchedPropertyBag(name=self.name, description=self.description),
)
@dataclasses.dataclass
class RuleCollection:
_rule_id_name_set: frozenset[tuple[str, str]] = dataclasses.field(init=False)
def __post_init__(self) -> None:
self._rule_id_name_set = frozenset(
{
(field.default.id, field.default.name)
for field in dataclasses.fields(self)
if isinstance(field.default, Rule)
}
)
def __contains__(self, rule: Rule) -> bool:
"""Checks if the rule is in the collection."""
return (rule.id, rule.name) in self._rule_id_name_set
@classmethod
def custom_collection_from_list(
cls, new_collection_class_name: str, rules: Sequence[Rule]
) -> RuleCollection:
"""Creates a custom class inherited from RuleCollection with the list of rules."""
return dataclasses.make_dataclass(
new_collection_class_name,
[
(
formatter.kebab_case_to_snake_case(rule.name),
type(rule),
dataclasses.field(default=rule),
)
for rule in rules
],
bases=(cls,),
)()
class Invocation:
# TODO: Implement this.
# Tracks top level call arguments and diagnostic options.
def __init__(self) -> None:
raise NotImplementedError
@dataclasses.dataclass
class DiagnosticOptions:
"""Options for diagnostic context.
Attributes:
verbosity_level: Set the amount of information logged for each diagnostics,
equivalent to the 'level' in Python logging module.
warnings_as_errors: When True, warning diagnostics are treated as error diagnostics.
"""
verbosity_level: int = dataclasses.field(default=logging.INFO)
"""Set the amount of information logged for each diagnostics, equivalent to the 'level' in Python logging module."""
warnings_as_errors: bool = dataclasses.field(default=False)
"""If True, warning diagnostics are treated as error diagnostics."""
|