language stringclasses 1
value | repo stringclasses 346
values | path stringlengths 6 201 | class_span dict | source stringlengths 21 2.38M | target stringlengths 1 96 |
|---|---|---|---|---|---|
python | huggingface__transformers | tests/models/florence2/test_processing_florence2.py | {
"start": 923,
"end": 11654
} | class ____(ProcessorTesterMixin, unittest.TestCase):
processor_class = Florence2Processor
@classmethod
def _setup_image_processor(cls):
image_processor_class = cls._get_component_class_from_processor("image_processor")
image_processor = image_processor_class.from_pretrained("florence-community/Florence-2-base")
image_processor.image_seq_length = 0
return image_processor
@classmethod
def _setup_tokenizer(cls):
tokenizer_class = cls._get_component_class_from_processor("tokenizer")
tokenizer = tokenizer_class.from_pretrained("florence-community/Florence-2-base")
tokenizer.image_token = "<image>"
tokenizer.image_token_id = tokenizer.encode(tokenizer.image_token, add_special_tokens=False)[0]
tokenizer.extra_special_tokens = {"image_token": "<image>"}
return tokenizer
@unittest.skip("Florence2Processor adds prefix and suffix tokens to the text")
def test_tokenizer_defaults(self):
pass
@staticmethod
def prepare_processor_dict():
return {
"post_processor_config": {
"ocr": {
"pattern": r"(.+?)<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>",
"area_threshold": 0.0,
},
"phrase_grounding": {"banned_grounding_tokens": ["the image"]},
"pure_text": {},
"description_with_bboxes": {},
"description_with_polygons": {},
"polygons": {},
"bboxes": {},
"description_with_bboxes_or_polygons": {},
}
}
def test_construct_prompts(self):
processor = self.processor_class.from_pretrained(self.tmpdirname)
# Test single text without task token
text = "This is a simple text."
prompts = processor._construct_prompts(text)
self.assertEqual(prompts, [text])
# Test list of texts with task without input
texts = ["<OCR>", "<CAPTION>"]
prompts = processor._construct_prompts(texts)
EXPECTED_PROMPTS_WITHOUT_INPUT = ["What is the text in the image?", "What does the image describe?"]
self.assertEqual(prompts, EXPECTED_PROMPTS_WITHOUT_INPUT)
# Test task with input
texts = ["<CAPTION_TO_PHRASE_GROUNDING> a red car"]
prompts = processor._construct_prompts(texts)
EXPECTED_PROMPTS_WITH_INPUT = ["Locate the phrases in the caption: a red car"]
self.assertEqual(prompts, EXPECTED_PROMPTS_WITH_INPUT)
# Test invalid prompt with task token not alone
with self.assertRaises(ValueError):
processor._construct_prompts("<OCR> extra text")
def test_quantizer_quantize_dequantize(self):
processor = self.processor_class.from_pretrained(self.tmpdirname)
# Test bounding box quantization and dequantization
boxes = torch.tensor([[0, 0, 30, 40], [500, 550, 600, 690], [750, 1121, 851, 1239]], dtype=torch.int32)
size = (800, 1200)
quantized_boxes = processor.post_processor.quantize(boxes, size)
dequantized_boxes = processor.post_processor.dequantize(quantized_boxes, size)
EXPECTED_DEQUANTIZED_BBOX = torch.tensor(
[[0, 0, 30, 40], [500, 550, 600, 690], [750, 1121, 799, 1199]], dtype=torch.int32
)
self.assertTrue(torch.allclose(dequantized_boxes, EXPECTED_DEQUANTIZED_BBOX))
# Test points quantization and dequantization
points = torch.tensor([[0, 0], [300, 400], [850, 1250]], dtype=torch.int32)
quantized_points = processor.post_processor.quantize(points, size)
dequantized_points = processor.post_processor.dequantize(quantized_points, size)
EXPECTED_DEQUANTIZED_POINTS = torch.tensor([[0, 0], [300, 400], [799, 1199]], dtype=torch.int32)
self.assertTrue(torch.allclose(dequantized_points, EXPECTED_DEQUANTIZED_POINTS))
# Test invalid shape
with self.assertRaises(ValueError):
processor.post_processor.quantize(torch.tensor([[1, 2, 3]]), size)
def test_post_process_parse_description_with_bboxes_from_text_and_spans(self):
processor = self.processor_class.from_pretrained(self.tmpdirname)
text_without_phrase = "</s><s><loc_53><loc_334><loc_933><loc_775><loc_711><loc_203><loc_906><loc_546><loc_585><loc_309><loc_774><loc_709><loc_577></s><pad>"
image_size = (1000, 1000)
parsed_text_without_phrase = processor.post_processor.parse_description_with_bboxes_from_text_and_spans(
text_without_phrase, image_size=image_size, allow_empty_phrase=True
)
EXPECTED_PARSED_TEXT_WITHOUT_PHRASE = [
{"bbox": [53, 334, 933, 775], "cat_name": ""},
{"bbox": [711, 203, 906, 546], "cat_name": ""},
{"bbox": [585, 309, 774, 709], "cat_name": ""},
]
self.assertEqual(parsed_text_without_phrase, EXPECTED_PARSED_TEXT_WITHOUT_PHRASE)
text_with_phrase = (
"</s><s>car<loc_53><loc_334><loc_933><loc_775>door handle<loc_425><loc_504><loc_474><loc_516></s><pad>"
)
image_size = (1000, 1000)
parsed_text_with_phrase = processor.post_processor.parse_description_with_bboxes_from_text_and_spans(
text_with_phrase, image_size=image_size, allow_empty_phrase=False
)
EXPECTED_PARSED_TEXT_WITH_PHRASE = [
{"bbox": [53, 334, 933, 775], "cat_name": "car"},
{"bbox": [425, 504, 474, 516], "cat_name": "door handle"},
]
self.assertEqual(parsed_text_with_phrase, EXPECTED_PARSED_TEXT_WITH_PHRASE)
def test_post_process_parse_description_with_polygons_from_text_and_spans(self):
processor = self.processor_class.from_pretrained(self.tmpdirname)
text_without_phrase = "<loc_279><loc_379><loc_282><loc_379><loc_290><loc_373><loc_293><loc_373><loc_298><loc_369><loc_301><loc_369>"
image_size = (1000, 1000)
parsed_text_without_phrase = processor.post_processor.parse_description_with_polygons_from_text_and_spans(
text_without_phrase, image_size=image_size, allow_empty_phrase=True
)
EXPECTED_PARSED_TEXT_WITHOUT_PHRASE = [
{
"cat_name": "",
"polygons": [[279, 379, 282, 379, 290, 373, 293, 373, 298, 369, 301, 369]],
}
]
self.assertEqual(parsed_text_without_phrase, EXPECTED_PARSED_TEXT_WITHOUT_PHRASE)
text_with_phrase = (
"Hello<loc_769><loc_248><loc_771><loc_234><loc_773><loc_206><loc_773><loc_198><loc_771><loc_193>"
)
image_size = (1000, 1000)
parsed_text_with_phrase = processor.post_processor.parse_description_with_polygons_from_text_and_spans(
text_with_phrase, image_size=image_size, allow_empty_phrase=False
)
EXPECTED_PARSED_TEXT_WITH_PHRASE = [
{
"cat_name": "Hello",
"polygons": [[769, 248, 771, 234, 773, 206, 773, 198, 771, 193]],
}
]
self.assertEqual(parsed_text_with_phrase, EXPECTED_PARSED_TEXT_WITH_PHRASE)
def test_post_process_parse_ocr_from_text_and_spans(self):
processor = self.processor_class.from_pretrained(self.tmpdirname)
text = "</s><s>Hello<loc_100><loc_100><loc_200><loc_100><loc_200><loc_200><loc_100><loc_200>World<loc_300><loc_300><loc_400><loc_300><loc_400><loc_400><loc_300><loc_400></s>"
image_size = (1000, 1000)
parsed = processor.post_processor.parse_ocr_from_text_and_spans(
text, pattern=None, image_size=image_size, area_threshold=0.0
)
EXPECTED_PARSED_OCR = [
{"quad_box": [100, 100, 200, 100, 200, 200, 100, 200], "text": "Hello"},
{"quad_box": [300, 300, 400, 300, 400, 400, 300, 400], "text": "World"},
]
self.assertEqual(parsed, EXPECTED_PARSED_OCR)
# Test with area threshold filtering
small_text = "Small<loc_1><loc_1><loc_2><loc_2><loc_2><loc_2><loc_1><loc_1>"
parsed_small = processor.post_processor.parse_ocr_from_text_and_spans(
small_text, pattern=None, image_size=image_size, area_threshold=0.01
)
EXPECTED_PARSED_OCR_SMALL = []
self.assertEqual(parsed_small, EXPECTED_PARSED_OCR_SMALL)
def test_post_process_parse_phrase_grounding_from_text_and_spans(self):
processor = self.processor_class.from_pretrained(self.tmpdirname)
text = "</s><s>red car<loc_53><loc_334><loc_933><loc_775><loc_711><loc_203><loc_906><loc_546>sky<loc_0><loc_0><loc_1000><loc_300></s>"
image_size = (1000, 1000)
parsed = processor.post_processor.parse_phrase_grounding_from_text_and_spans(text, image_size=image_size)
EXPECTED_PARSED_PHRASE_GROUNDING = [
{"bbox": [[53, 334, 933, 775], [711, 203, 906, 546]], "cat_name": "red car"},
{"bbox": [[0, 0, 1000, 300]], "cat_name": "sky"},
]
self.assertEqual(parsed, EXPECTED_PARSED_PHRASE_GROUNDING)
# Test with blacklisted phrase
blacklisted_text = "the image<loc_100><loc_100><loc_200><loc_200>"
parsed_blacklisted = processor.post_processor.parse_phrase_grounding_from_text_and_spans(
blacklisted_text, image_size=image_size
)
EXPECTED_PARSED_BLACKLISTED = []
self.assertEqual(parsed_blacklisted, EXPECTED_PARSED_BLACKLISTED)
def test_post_process_generation(self):
processor = self.processor_class.from_pretrained(self.tmpdirname)
# Test pure_text task
text = "<s>Hello world</s>"
cap_result = processor.post_process_generation(text=text, task="<CAPTION>", image_size=None)
EXPECTED_PURE_TEXT_RESULT = {"<CAPTION>": "Hello world"}
self.assertEqual(cap_result, EXPECTED_PURE_TEXT_RESULT)
# Test description_with_bboxes task
text = "car<loc_53><loc_334><loc_933><loc_775>"
od_result = processor.post_process_generation(text=text, task="<OD>", image_size=(1000, 1000))
EXPECTED_BBOXES_RESULT = {"<OD>": {"bboxes": [[53, 334, 933, 775]], "labels": ["car"]}}
self.assertEqual(od_result, EXPECTED_BBOXES_RESULT)
# Test OCR task
text = "Hello<loc_100><loc_100><loc_200><loc_100><loc_200><loc_200><loc_100><loc_200>"
ocr_result = processor.post_process_generation(text=text, task="<OCR_WITH_REGION>", image_size=(1000, 1000))
EXPECTED_OCR_RESULT = {
"<OCR_WITH_REGION>": {"quad_boxes": [[100, 100, 200, 100, 200, 200, 100, 200]], "labels": ["Hello"]}
}
self.assertEqual(ocr_result, EXPECTED_OCR_RESULT)
| Florence2ProcessorTest |
python | plotly__plotly.py | plotly/graph_objs/scatter3d/line/_colorbar.py | {
"start": 233,
"end": 61634
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scatter3d.line"
_path_str = "scatter3d.line.colorbar"
_valid_props = {
"bgcolor",
"bordercolor",
"borderwidth",
"dtick",
"exponentformat",
"labelalias",
"len",
"lenmode",
"minexponent",
"nticks",
"orientation",
"outlinecolor",
"outlinewidth",
"separatethousands",
"showexponent",
"showticklabels",
"showtickprefix",
"showticksuffix",
"thickness",
"thicknessmode",
"tick0",
"tickangle",
"tickcolor",
"tickfont",
"tickformat",
"tickformatstopdefaults",
"tickformatstops",
"ticklabeloverflow",
"ticklabelposition",
"ticklabelstep",
"ticklen",
"tickmode",
"tickprefix",
"ticks",
"ticksuffix",
"ticktext",
"ticktextsrc",
"tickvals",
"tickvalssrc",
"tickwidth",
"title",
"x",
"xanchor",
"xpad",
"xref",
"y",
"yanchor",
"ypad",
"yref",
}
@property
def bgcolor(self):
"""
Sets the color of padded area.
The 'bgcolor' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
Returns
-------
str
"""
return self["bgcolor"]
@bgcolor.setter
def bgcolor(self, val):
self["bgcolor"] = val
@property
def bordercolor(self):
"""
Sets the axis line color.
The 'bordercolor' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
Returns
-------
str
"""
return self["bordercolor"]
@bordercolor.setter
def bordercolor(self, val):
self["bordercolor"] = val
@property
def borderwidth(self):
"""
Sets the width (in px) or the border enclosing this color bar.
The 'borderwidth' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["borderwidth"]
@borderwidth.setter
def borderwidth(self, val):
self["borderwidth"] = val
@property
def dtick(self):
"""
Sets the step in-between ticks on this axis. Use with `tick0`.
Must be a positive number, or special strings available to
"log" and "date" axes. If the axis `type` is "log", then ticks
are set every 10^(n*dtick) where n is the tick number. For
example, to set a tick mark at 1, 10, 100, 1000, ... set dtick
to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2.
To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to
log_10(5), or 0.69897000433. "log" has several special values;
"L<f>", where `f` is a positive number, gives ticks linearly
spaced in value (but not position). For example `tick0` = 0.1,
`dtick` = "L0.5" will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To
show powers of 10 plus small digits between, use "D1" (all
digits) or "D2" (only 2 and 5). `tick0` is ignored for "D1" and
"D2". If the axis `type` is "date", then you must convert the
time to milliseconds. For example, to set the interval between
ticks to one day, set `dtick` to 86400000.0. "date" also has
special values "M<n>" gives ticks spaced by a number of months.
`n` must be a positive integer. To set ticks on the 15th of
every third month, set `tick0` to "2000-01-15" and `dtick` to
"M3". To set ticks every 4 years, set `dtick` to "M48"
The 'dtick' property accepts values of any type
Returns
-------
Any
"""
return self["dtick"]
@dtick.setter
def dtick(self, val):
self["dtick"] = val
@property
def exponentformat(self):
"""
Determines a formatting rule for the tick exponents. For
example, consider the number 1,000,000,000. If "none", it
appears as 1,000,000,000. If "e", 1e+9. If "E", 1E+9. If
"power", 1x10^9 (with 9 in a super script). If "SI", 1G. If
"B", 1B. "SI" uses prefixes from "femto" f (10^-15) to "tera" T
(10^12). *SI extended* covers instead the full SI range from
"quecto" q (10^-30) to "quetta" Q (10^30). If "SI" or *SI
extended* is used and the exponent is beyond the above ranges,
the formatting rule will automatically be switched to the power
notation.
The 'exponentformat' property is an enumeration that may be specified as:
- One of the following enumeration values:
['none', 'e', 'E', 'power', 'SI', 'B', 'SI extended']
Returns
-------
Any
"""
return self["exponentformat"]
@exponentformat.setter
def exponentformat(self, val):
self["exponentformat"] = val
@property
def labelalias(self):
"""
Replacement text for specific tick or hover labels. For example
using {US: 'USA', CA: 'Canada'} changes US to USA and CA to
Canada. The labels we would have shown must match the keys
exactly, after adding any tickprefix or ticksuffix. For
negative numbers the minus sign symbol used (U+2212) is wider
than the regular ascii dash. That means you need to use −1
instead of -1. labelalias can be used with any axis type, and
both keys (if needed) and values (if desired) can include html-
like tags or MathJax.
The 'labelalias' property accepts values of any type
Returns
-------
Any
"""
return self["labelalias"]
@labelalias.setter
def labelalias(self, val):
self["labelalias"] = val
@property
def len(self):
"""
Sets the length of the color bar This measure excludes the
padding of both ends. That is, the color bar length is this
length minus the padding on both ends.
The 'len' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["len"]
@len.setter
def len(self, val):
self["len"] = val
@property
def lenmode(self):
"""
Determines whether this color bar's length (i.e. the measure in
the color variation direction) is set in units of plot
"fraction" or in *pixels. Use `len` to set the value.
The 'lenmode' property is an enumeration that may be specified as:
- One of the following enumeration values:
['fraction', 'pixels']
Returns
-------
Any
"""
return self["lenmode"]
@lenmode.setter
def lenmode(self, val):
self["lenmode"] = val
@property
def minexponent(self):
"""
Hide SI prefix for 10^n if |n| is below this number. This only
has an effect when `tickformat` is "SI" or "B".
The 'minexponent' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["minexponent"]
@minexponent.setter
def minexponent(self, val):
self["minexponent"] = val
@property
def nticks(self):
"""
Specifies the maximum number of ticks for the particular axis.
The actual number of ticks will be chosen automatically to be
less than or equal to `nticks`. Has an effect only if
`tickmode` is set to "auto".
The 'nticks' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
in the interval [0, 9223372036854775807]
Returns
-------
int
"""
return self["nticks"]
@nticks.setter
def nticks(self, val):
self["nticks"] = val
@property
def orientation(self):
"""
Sets the orientation of the colorbar.
The 'orientation' property is an enumeration that may be specified as:
- One of the following enumeration values:
['h', 'v']
Returns
-------
Any
"""
return self["orientation"]
@orientation.setter
def orientation(self, val):
self["orientation"] = val
@property
def outlinecolor(self):
"""
Sets the axis line color.
The 'outlinecolor' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
Returns
-------
str
"""
return self["outlinecolor"]
@outlinecolor.setter
def outlinecolor(self, val):
self["outlinecolor"] = val
@property
def outlinewidth(self):
"""
Sets the width (in px) of the axis line.
The 'outlinewidth' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["outlinewidth"]
@outlinewidth.setter
def outlinewidth(self, val):
self["outlinewidth"] = val
@property
def separatethousands(self):
"""
If "true", even 4-digit integers are separated
The 'separatethousands' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["separatethousands"]
@separatethousands.setter
def separatethousands(self, val):
self["separatethousands"] = val
@property
def showexponent(self):
"""
If "all", all exponents are shown besides their significands.
If "first", only the exponent of the first tick is shown. If
"last", only the exponent of the last tick is shown. If "none",
no exponents appear.
The 'showexponent' property is an enumeration that may be specified as:
- One of the following enumeration values:
['all', 'first', 'last', 'none']
Returns
-------
Any
"""
return self["showexponent"]
@showexponent.setter
def showexponent(self, val):
self["showexponent"] = val
@property
def showticklabels(self):
"""
Determines whether or not the tick labels are drawn.
The 'showticklabels' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["showticklabels"]
@showticklabels.setter
def showticklabels(self, val):
self["showticklabels"] = val
@property
def showtickprefix(self):
"""
If "all", all tick labels are displayed with a prefix. If
"first", only the first tick is displayed with a prefix. If
"last", only the last tick is displayed with a suffix. If
"none", tick prefixes are hidden.
The 'showtickprefix' property is an enumeration that may be specified as:
- One of the following enumeration values:
['all', 'first', 'last', 'none']
Returns
-------
Any
"""
return self["showtickprefix"]
@showtickprefix.setter
def showtickprefix(self, val):
self["showtickprefix"] = val
@property
def showticksuffix(self):
"""
Same as `showtickprefix` but for tick suffixes.
The 'showticksuffix' property is an enumeration that may be specified as:
- One of the following enumeration values:
['all', 'first', 'last', 'none']
Returns
-------
Any
"""
return self["showticksuffix"]
@showticksuffix.setter
def showticksuffix(self, val):
self["showticksuffix"] = val
@property
def thickness(self):
"""
Sets the thickness of the color bar This measure excludes the
size of the padding, ticks and labels.
The 'thickness' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["thickness"]
@thickness.setter
def thickness(self, val):
self["thickness"] = val
@property
def thicknessmode(self):
"""
Determines whether this color bar's thickness (i.e. the measure
in the constant color direction) is set in units of plot
"fraction" or in "pixels". Use `thickness` to set the value.
The 'thicknessmode' property is an enumeration that may be specified as:
- One of the following enumeration values:
['fraction', 'pixels']
Returns
-------
Any
"""
return self["thicknessmode"]
@thicknessmode.setter
def thicknessmode(self, val):
self["thicknessmode"] = val
@property
def tick0(self):
"""
Sets the placement of the first tick on this axis. Use with
`dtick`. If the axis `type` is "log", then you must take the
log of your starting tick (e.g. to set the starting tick to
100, set the `tick0` to 2) except when `dtick`=*L<f>* (see
`dtick` for more info). If the axis `type` is "date", it should
be a date string, like date data. If the axis `type` is
"category", it should be a number, using the scale where each
category is assigned a serial number from zero in the order it
appears.
The 'tick0' property accepts values of any type
Returns
-------
Any
"""
return self["tick0"]
@tick0.setter
def tick0(self, val):
self["tick0"] = val
@property
def tickangle(self):
"""
Sets the angle of the tick labels with respect to the
horizontal. For example, a `tickangle` of -90 draws the tick
labels vertically.
The 'tickangle' property is a angle (in degrees) that may be
specified as a number between -180 and 180.
Numeric values outside this range are converted to the equivalent value
(e.g. 270 is converted to -90).
Returns
-------
int|float
"""
return self["tickangle"]
@tickangle.setter
def tickangle(self, val):
self["tickangle"] = val
@property
def tickcolor(self):
"""
Sets the tick color.
The 'tickcolor' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
Returns
-------
str
"""
return self["tickcolor"]
@tickcolor.setter
def tickcolor(self, val):
self["tickcolor"] = val
@property
def tickfont(self):
"""
Sets the color bar's tick label font
The 'tickfont' property is an instance of Tickfont
that may be specified as:
- An instance of :class:`plotly.graph_objs.scatter3d.line.colorbar.Tickfont`
- A dict of string/value properties that will be passed
to the Tickfont constructor
Returns
-------
plotly.graph_objs.scatter3d.line.colorbar.Tickfont
"""
return self["tickfont"]
@tickfont.setter
def tickfont(self, val):
self["tickfont"] = val
@property
def tickformat(self):
"""
Sets the tick label formatting rule using d3 formatting mini-
languages which are very similar to those in Python. For
numbers, see:
https://github.com/d3/d3-format/tree/v1.4.5#d3-format. And for
dates see: https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two items to d3's date
formatter: "%h" for half of the year as a decimal number as
well as "%{n}f" for fractional seconds with n digits. For
example, *2016-10-13 09:15:23.456* with tickformat
"%H~%M~%S.%2f" would display "09~15~23.46"
The 'tickformat' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["tickformat"]
@tickformat.setter
def tickformat(self, val):
self["tickformat"] = val
@property
def tickformatstops(self):
"""
The 'tickformatstops' property is a tuple of instances of
Tickformatstop that may be specified as:
- A list or tuple of instances of plotly.graph_objs.scatter3d.line.colorbar.Tickformatstop
- A list or tuple of dicts of string/value properties that
will be passed to the Tickformatstop constructor
Returns
-------
tuple[plotly.graph_objs.scatter3d.line.colorbar.Tickformatstop]
"""
return self["tickformatstops"]
@tickformatstops.setter
def tickformatstops(self, val):
self["tickformatstops"] = val
@property
def tickformatstopdefaults(self):
"""
When used in a template (as layout.template.data.scatter3d.line
.colorbar.tickformatstopdefaults), sets the default property
values to use for elements of
scatter3d.line.colorbar.tickformatstops
The 'tickformatstopdefaults' property is an instance of Tickformatstop
that may be specified as:
- An instance of :class:`plotly.graph_objs.scatter3d.line.colorbar.Tickformatstop`
- A dict of string/value properties that will be passed
to the Tickformatstop constructor
Returns
-------
plotly.graph_objs.scatter3d.line.colorbar.Tickformatstop
"""
return self["tickformatstopdefaults"]
@tickformatstopdefaults.setter
def tickformatstopdefaults(self, val):
self["tickformatstopdefaults"] = val
@property
def ticklabeloverflow(self):
"""
Determines how we handle tick labels that would overflow either
the graph div or the domain of the axis. The default value for
inside tick labels is *hide past domain*. In other cases the
default is *hide past div*.
The 'ticklabeloverflow' property is an enumeration that may be specified as:
- One of the following enumeration values:
['allow', 'hide past div', 'hide past domain']
Returns
-------
Any
"""
return self["ticklabeloverflow"]
@ticklabeloverflow.setter
def ticklabeloverflow(self, val):
self["ticklabeloverflow"] = val
@property
def ticklabelposition(self):
"""
Determines where tick labels are drawn relative to the ticks.
Left and right options are used when `orientation` is "h", top
and bottom when `orientation` is "v".
The 'ticklabelposition' property is an enumeration that may be specified as:
- One of the following enumeration values:
['outside', 'inside', 'outside top', 'inside top',
'outside left', 'inside left', 'outside right', 'inside
right', 'outside bottom', 'inside bottom']
Returns
-------
Any
"""
return self["ticklabelposition"]
@ticklabelposition.setter
def ticklabelposition(self, val):
self["ticklabelposition"] = val
@property
def ticklabelstep(self):
"""
Sets the spacing between tick labels as compared to the spacing
between ticks. A value of 1 (default) means each tick gets a
label. A value of 2 means shows every 2nd label. A larger value
n means only every nth tick is labeled. `tick0` determines
which labels are shown. Not implemented for axes with `type`
"log" or "multicategory", or when `tickmode` is "array".
The 'ticklabelstep' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
in the interval [1, 9223372036854775807]
Returns
-------
int
"""
return self["ticklabelstep"]
@ticklabelstep.setter
def ticklabelstep(self, val):
self["ticklabelstep"] = val
@property
def ticklen(self):
"""
Sets the tick length (in px).
The 'ticklen' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["ticklen"]
@ticklen.setter
def ticklen(self, val):
self["ticklen"] = val
@property
def tickmode(self):
"""
Sets the tick mode for this axis. If "auto", the number of
ticks is set via `nticks`. If "linear", the placement of the
ticks is determined by a starting position `tick0` and a tick
step `dtick` ("linear" is the default value if `tick0` and
`dtick` are provided). If "array", the placement of the ticks
is set via `tickvals` and the tick text is `ticktext`. ("array"
is the default value if `tickvals` is provided).
The 'tickmode' property is an enumeration that may be specified as:
- One of the following enumeration values:
['auto', 'linear', 'array']
Returns
-------
Any
"""
return self["tickmode"]
@tickmode.setter
def tickmode(self, val):
self["tickmode"] = val
@property
def tickprefix(self):
"""
Sets a tick label prefix.
The 'tickprefix' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["tickprefix"]
@tickprefix.setter
def tickprefix(self, val):
self["tickprefix"] = val
@property
def ticks(self):
"""
Determines whether ticks are drawn or not. If "", this axis'
ticks are not drawn. If "outside" ("inside"), this axis' are
drawn outside (inside) the axis lines.
The 'ticks' property is an enumeration that may be specified as:
- One of the following enumeration values:
['outside', 'inside', '']
Returns
-------
Any
"""
return self["ticks"]
@ticks.setter
def ticks(self, val):
self["ticks"] = val
@property
def ticksuffix(self):
"""
Sets a tick label suffix.
The 'ticksuffix' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["ticksuffix"]
@ticksuffix.setter
def ticksuffix(self, val):
self["ticksuffix"] = val
@property
def ticktext(self):
"""
Sets the text displayed at the ticks position via `tickvals`.
Only has an effect if `tickmode` is set to "array". Used with
`tickvals`.
The 'ticktext' property is an array that may be specified as a tuple,
list, numpy array, or pandas Series
Returns
-------
numpy.ndarray
"""
return self["ticktext"]
@ticktext.setter
def ticktext(self, val):
self["ticktext"] = val
@property
def ticktextsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `ticktext`.
The 'ticktextsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["ticktextsrc"]
@ticktextsrc.setter
def ticktextsrc(self, val):
self["ticktextsrc"] = val
@property
def tickvals(self):
"""
Sets the values at which ticks on this axis appear. Only has an
effect if `tickmode` is set to "array". Used with `ticktext`.
The 'tickvals' property is an array that may be specified as a tuple,
list, numpy array, or pandas Series
Returns
-------
numpy.ndarray
"""
return self["tickvals"]
@tickvals.setter
def tickvals(self, val):
self["tickvals"] = val
@property
def tickvalssrc(self):
"""
Sets the source reference on Chart Studio Cloud for `tickvals`.
The 'tickvalssrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["tickvalssrc"]
@tickvalssrc.setter
def tickvalssrc(self, val):
self["tickvalssrc"] = val
@property
def tickwidth(self):
"""
Sets the tick width (in px).
The 'tickwidth' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["tickwidth"]
@tickwidth.setter
def tickwidth(self, val):
self["tickwidth"] = val
@property
def title(self):
"""
The 'title' property is an instance of Title
that may be specified as:
- An instance of :class:`plotly.graph_objs.scatter3d.line.colorbar.Title`
- A dict of string/value properties that will be passed
to the Title constructor
Returns
-------
plotly.graph_objs.scatter3d.line.colorbar.Title
"""
return self["title"]
@title.setter
def title(self, val):
self["title"] = val
@property
def x(self):
"""
Sets the x position with respect to `xref` of the color bar (in
plot fraction). When `xref` is "paper", defaults to 1.02 when
`orientation` is "v" and 0.5 when `orientation` is "h". When
`xref` is "container", defaults to 1 when `orientation` is "v"
and 0.5 when `orientation` is "h". Must be between 0 and 1 if
`xref` is "container" and between "-2" and 3 if `xref` is
"paper".
The 'x' property is a number and may be specified as:
- An int or float
Returns
-------
int|float
"""
return self["x"]
@x.setter
def x(self, val):
self["x"] = val
@property
def xanchor(self):
"""
Sets this color bar's horizontal position anchor. This anchor
binds the `x` position to the "left", "center" or "right" of
the color bar. Defaults to "left" when `orientation` is "v" and
"center" when `orientation` is "h".
The 'xanchor' property is an enumeration that may be specified as:
- One of the following enumeration values:
['left', 'center', 'right']
Returns
-------
Any
"""
return self["xanchor"]
@xanchor.setter
def xanchor(self, val):
self["xanchor"] = val
@property
def xpad(self):
"""
Sets the amount of padding (in px) along the x direction.
The 'xpad' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["xpad"]
@xpad.setter
def xpad(self, val):
self["xpad"] = val
@property
def xref(self):
"""
Sets the container `x` refers to. "container" spans the entire
`width` of the plot. "paper" refers to the width of the
plotting area only.
The 'xref' property is an enumeration that may be specified as:
- One of the following enumeration values:
['container', 'paper']
Returns
-------
Any
"""
return self["xref"]
@xref.setter
def xref(self, val):
self["xref"] = val
@property
def y(self):
"""
Sets the y position with respect to `yref` of the color bar (in
plot fraction). When `yref` is "paper", defaults to 0.5 when
`orientation` is "v" and 1.02 when `orientation` is "h". When
`yref` is "container", defaults to 0.5 when `orientation` is
"v" and 1 when `orientation` is "h". Must be between 0 and 1 if
`yref` is "container" and between "-2" and 3 if `yref` is
"paper".
The 'y' property is a number and may be specified as:
- An int or float
Returns
-------
int|float
"""
return self["y"]
@y.setter
def y(self, val):
self["y"] = val
@property
def yanchor(self):
"""
Sets this color bar's vertical position anchor This anchor
binds the `y` position to the "top", "middle" or "bottom" of
the color bar. Defaults to "middle" when `orientation` is "v"
and "bottom" when `orientation` is "h".
The 'yanchor' property is an enumeration that may be specified as:
- One of the following enumeration values:
['top', 'middle', 'bottom']
Returns
-------
Any
"""
return self["yanchor"]
@yanchor.setter
def yanchor(self, val):
self["yanchor"] = val
@property
def ypad(self):
"""
Sets the amount of padding (in px) along the y direction.
The 'ypad' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["ypad"]
@ypad.setter
def ypad(self, val):
self["ypad"] = val
@property
def yref(self):
"""
Sets the container `y` refers to. "container" spans the entire
`height` of the plot. "paper" refers to the height of the
plotting area only.
The 'yref' property is an enumeration that may be specified as:
- One of the following enumeration values:
['container', 'paper']
Returns
-------
Any
"""
return self["yref"]
@yref.setter
def yref(self, val):
self["yref"] = val
@property
def _prop_descriptions(self):
return """\
bgcolor
Sets the color of padded area.
bordercolor
Sets the axis line color.
borderwidth
Sets the width (in px) or the border enclosing this
color bar.
dtick
Sets the step in-between ticks on this axis. Use with
`tick0`. Must be a positive number, or special strings
available to "log" and "date" axes. If the axis `type`
is "log", then ticks are set every 10^(n*dtick) where n
is the tick number. For example, to set a tick mark at
1, 10, 100, 1000, ... set dtick to 1. To set tick marks
at 1, 100, 10000, ... set dtick to 2. To set tick marks
at 1, 5, 25, 125, 625, 3125, ... set dtick to
log_10(5), or 0.69897000433. "log" has several special
values; "L<f>", where `f` is a positive number, gives
ticks linearly spaced in value (but not position). For
example `tick0` = 0.1, `dtick` = "L0.5" will put ticks
at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus
small digits between, use "D1" (all digits) or "D2"
(only 2 and 5). `tick0` is ignored for "D1" and "D2".
If the axis `type` is "date", then you must convert the
time to milliseconds. For example, to set the interval
between ticks to one day, set `dtick` to 86400000.0.
"date" also has special values "M<n>" gives ticks
spaced by a number of months. `n` must be a positive
integer. To set ticks on the 15th of every third month,
set `tick0` to "2000-01-15" and `dtick` to "M3". To set
ticks every 4 years, set `dtick` to "M48"
exponentformat
Determines a formatting rule for the tick exponents.
For example, consider the number 1,000,000,000. If
"none", it appears as 1,000,000,000. If "e", 1e+9. If
"E", 1E+9. If "power", 1x10^9 (with 9 in a super
script). If "SI", 1G. If "B", 1B. "SI" uses prefixes
from "femto" f (10^-15) to "tera" T (10^12). *SI
extended* covers instead the full SI range from
"quecto" q (10^-30) to "quetta" Q (10^30). If "SI" or
*SI extended* is used and the exponent is beyond the
above ranges, the formatting rule will automatically be
switched to the power notation.
labelalias
Replacement text for specific tick or hover labels. For
example using {US: 'USA', CA: 'Canada'} changes US to
USA and CA to Canada. The labels we would have shown
must match the keys exactly, after adding any
tickprefix or ticksuffix. For negative numbers the
minus sign symbol used (U+2212) is wider than the
regular ascii dash. That means you need to use −1
instead of -1. labelalias can be used with any axis
type, and both keys (if needed) and values (if desired)
can include html-like tags or MathJax.
len
Sets the length of the color bar This measure excludes
the padding of both ends. That is, the color bar length
is this length minus the padding on both ends.
lenmode
Determines whether this color bar's length (i.e. the
measure in the color variation direction) is set in
units of plot "fraction" or in *pixels. Use `len` to
set the value.
minexponent
Hide SI prefix for 10^n if |n| is below this number.
This only has an effect when `tickformat` is "SI" or
"B".
nticks
Specifies the maximum number of ticks for the
particular axis. The actual number of ticks will be
chosen automatically to be less than or equal to
`nticks`. Has an effect only if `tickmode` is set to
"auto".
orientation
Sets the orientation of the colorbar.
outlinecolor
Sets the axis line color.
outlinewidth
Sets the width (in px) of the axis line.
separatethousands
If "true", even 4-digit integers are separated
showexponent
If "all", all exponents are shown besides their
significands. If "first", only the exponent of the
first tick is shown. If "last", only the exponent of
the last tick is shown. If "none", no exponents appear.
showticklabels
Determines whether or not the tick labels are drawn.
showtickprefix
If "all", all tick labels are displayed with a prefix.
If "first", only the first tick is displayed with a
prefix. If "last", only the last tick is displayed with
a suffix. If "none", tick prefixes are hidden.
showticksuffix
Same as `showtickprefix` but for tick suffixes.
thickness
Sets the thickness of the color bar This measure
excludes the size of the padding, ticks and labels.
thicknessmode
Determines whether this color bar's thickness (i.e. the
measure in the constant color direction) is set in
units of plot "fraction" or in "pixels". Use
`thickness` to set the value.
tick0
Sets the placement of the first tick on this axis. Use
with `dtick`. If the axis `type` is "log", then you
must take the log of your starting tick (e.g. to set
the starting tick to 100, set the `tick0` to 2) except
when `dtick`=*L<f>* (see `dtick` for more info). If the
axis `type` is "date", it should be a date string, like
date data. If the axis `type` is "category", it should
be a number, using the scale where each category is
assigned a serial number from zero in the order it
appears.
tickangle
Sets the angle of the tick labels with respect to the
horizontal. For example, a `tickangle` of -90 draws the
tick labels vertically.
tickcolor
Sets the tick color.
tickfont
Sets the color bar's tick label font
tickformat
Sets the tick label formatting rule using d3 formatting
mini-languages which are very similar to those in
Python. For numbers, see:
https://github.com/d3/d3-format/tree/v1.4.5#d3-format.
And for dates see: https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two items to
d3's date formatter: "%h" for half of the year as a
decimal number as well as "%{n}f" for fractional
seconds with n digits. For example, *2016-10-13
09:15:23.456* with tickformat "%H~%M~%S.%2f" would
display "09~15~23.46"
tickformatstops
A tuple of :class:`plotly.graph_objects.scatter3d.line.
colorbar.Tickformatstop` instances or dicts with
compatible properties
tickformatstopdefaults
When used in a template (as layout.template.data.scatte
r3d.line.colorbar.tickformatstopdefaults), sets the
default property values to use for elements of
scatter3d.line.colorbar.tickformatstops
ticklabeloverflow
Determines how we handle tick labels that would
overflow either the graph div or the domain of the
axis. The default value for inside tick labels is *hide
past domain*. In other cases the default is *hide past
div*.
ticklabelposition
Determines where tick labels are drawn relative to the
ticks. Left and right options are used when
`orientation` is "h", top and bottom when `orientation`
is "v".
ticklabelstep
Sets the spacing between tick labels as compared to the
spacing between ticks. A value of 1 (default) means
each tick gets a label. A value of 2 means shows every
2nd label. A larger value n means only every nth tick
is labeled. `tick0` determines which labels are shown.
Not implemented for axes with `type` "log" or
"multicategory", or when `tickmode` is "array".
ticklen
Sets the tick length (in px).
tickmode
Sets the tick mode for this axis. If "auto", the number
of ticks is set via `nticks`. If "linear", the
placement of the ticks is determined by a starting
position `tick0` and a tick step `dtick` ("linear" is
the default value if `tick0` and `dtick` are provided).
If "array", the placement of the ticks is set via
`tickvals` and the tick text is `ticktext`. ("array" is
the default value if `tickvals` is provided).
tickprefix
Sets a tick label prefix.
ticks
Determines whether ticks are drawn or not. If "", this
axis' ticks are not drawn. If "outside" ("inside"),
this axis' are drawn outside (inside) the axis lines.
ticksuffix
Sets a tick label suffix.
ticktext
Sets the text displayed at the ticks position via
`tickvals`. Only has an effect if `tickmode` is set to
"array". Used with `tickvals`.
ticktextsrc
Sets the source reference on Chart Studio Cloud for
`ticktext`.
tickvals
Sets the values at which ticks on this axis appear.
Only has an effect if `tickmode` is set to "array".
Used with `ticktext`.
tickvalssrc
Sets the source reference on Chart Studio Cloud for
`tickvals`.
tickwidth
Sets the tick width (in px).
title
:class:`plotly.graph_objects.scatter3d.line.colorbar.Ti
tle` instance or dict with compatible properties
x
Sets the x position with respect to `xref` of the color
bar (in plot fraction). When `xref` is "paper",
defaults to 1.02 when `orientation` is "v" and 0.5 when
`orientation` is "h". When `xref` is "container",
defaults to 1 when `orientation` is "v" and 0.5 when
`orientation` is "h". Must be between 0 and 1 if `xref`
is "container" and between "-2" and 3 if `xref` is
"paper".
xanchor
Sets this color bar's horizontal position anchor. This
anchor binds the `x` position to the "left", "center"
or "right" of the color bar. Defaults to "left" when
`orientation` is "v" and "center" when `orientation` is
"h".
xpad
Sets the amount of padding (in px) along the x
direction.
xref
Sets the container `x` refers to. "container" spans the
entire `width` of the plot. "paper" refers to the width
of the plotting area only.
y
Sets the y position with respect to `yref` of the color
bar (in plot fraction). When `yref` is "paper",
defaults to 0.5 when `orientation` is "v" and 1.02 when
`orientation` is "h". When `yref` is "container",
defaults to 0.5 when `orientation` is "v" and 1 when
`orientation` is "h". Must be between 0 and 1 if `yref`
is "container" and between "-2" and 3 if `yref` is
"paper".
yanchor
Sets this color bar's vertical position anchor This
anchor binds the `y` position to the "top", "middle" or
"bottom" of the color bar. Defaults to "middle" when
`orientation` is "v" and "bottom" when `orientation` is
"h".
ypad
Sets the amount of padding (in px) along the y
direction.
yref
Sets the container `y` refers to. "container" spans the
entire `height` of the plot. "paper" refers to the
height of the plotting area only.
"""
def __init__(
self,
arg=None,
bgcolor=None,
bordercolor=None,
borderwidth=None,
dtick=None,
exponentformat=None,
labelalias=None,
len=None,
lenmode=None,
minexponent=None,
nticks=None,
orientation=None,
outlinecolor=None,
outlinewidth=None,
separatethousands=None,
showexponent=None,
showticklabels=None,
showtickprefix=None,
showticksuffix=None,
thickness=None,
thicknessmode=None,
tick0=None,
tickangle=None,
tickcolor=None,
tickfont=None,
tickformat=None,
tickformatstops=None,
tickformatstopdefaults=None,
ticklabeloverflow=None,
ticklabelposition=None,
ticklabelstep=None,
ticklen=None,
tickmode=None,
tickprefix=None,
ticks=None,
ticksuffix=None,
ticktext=None,
ticktextsrc=None,
tickvals=None,
tickvalssrc=None,
tickwidth=None,
title=None,
x=None,
xanchor=None,
xpad=None,
xref=None,
y=None,
yanchor=None,
ypad=None,
yref=None,
**kwargs,
):
"""
Construct a new ColorBar object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.scatter3d.line.ColorBar`
bgcolor
Sets the color of padded area.
bordercolor
Sets the axis line color.
borderwidth
Sets the width (in px) or the border enclosing this
color bar.
dtick
Sets the step in-between ticks on this axis. Use with
`tick0`. Must be a positive number, or special strings
available to "log" and "date" axes. If the axis `type`
is "log", then ticks are set every 10^(n*dtick) where n
is the tick number. For example, to set a tick mark at
1, 10, 100, 1000, ... set dtick to 1. To set tick marks
at 1, 100, 10000, ... set dtick to 2. To set tick marks
at 1, 5, 25, 125, 625, 3125, ... set dtick to
log_10(5), or 0.69897000433. "log" has several special
values; "L<f>", where `f` is a positive number, gives
ticks linearly spaced in value (but not position). For
example `tick0` = 0.1, `dtick` = "L0.5" will put ticks
at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus
small digits between, use "D1" (all digits) or "D2"
(only 2 and 5). `tick0` is ignored for "D1" and "D2".
If the axis `type` is "date", then you must convert the
time to milliseconds. For example, to set the interval
between ticks to one day, set `dtick` to 86400000.0.
"date" also has special values "M<n>" gives ticks
spaced by a number of months. `n` must be a positive
integer. To set ticks on the 15th of every third month,
set `tick0` to "2000-01-15" and `dtick` to "M3". To set
ticks every 4 years, set `dtick` to "M48"
exponentformat
Determines a formatting rule for the tick exponents.
For example, consider the number 1,000,000,000. If
"none", it appears as 1,000,000,000. If "e", 1e+9. If
"E", 1E+9. If "power", 1x10^9 (with 9 in a super
script). If "SI", 1G. If "B", 1B. "SI" uses prefixes
from "femto" f (10^-15) to "tera" T (10^12). *SI
extended* covers instead the full SI range from
"quecto" q (10^-30) to "quetta" Q (10^30). If "SI" or
*SI extended* is used and the exponent is beyond the
above ranges, the formatting rule will automatically be
switched to the power notation.
labelalias
Replacement text for specific tick or hover labels. For
example using {US: 'USA', CA: 'Canada'} changes US to
USA and CA to Canada. The labels we would have shown
must match the keys exactly, after adding any
tickprefix or ticksuffix. For negative numbers the
minus sign symbol used (U+2212) is wider than the
regular ascii dash. That means you need to use −1
instead of -1. labelalias can be used with any axis
type, and both keys (if needed) and values (if desired)
can include html-like tags or MathJax.
len
Sets the length of the color bar This measure excludes
the padding of both ends. That is, the color bar length
is this length minus the padding on both ends.
lenmode
Determines whether this color bar's length (i.e. the
measure in the color variation direction) is set in
units of plot "fraction" or in *pixels. Use `len` to
set the value.
minexponent
Hide SI prefix for 10^n if |n| is below this number.
This only has an effect when `tickformat` is "SI" or
"B".
nticks
Specifies the maximum number of ticks for the
particular axis. The actual number of ticks will be
chosen automatically to be less than or equal to
`nticks`. Has an effect only if `tickmode` is set to
"auto".
orientation
Sets the orientation of the colorbar.
outlinecolor
Sets the axis line color.
outlinewidth
Sets the width (in px) of the axis line.
separatethousands
If "true", even 4-digit integers are separated
showexponent
If "all", all exponents are shown besides their
significands. If "first", only the exponent of the
first tick is shown. If "last", only the exponent of
the last tick is shown. If "none", no exponents appear.
showticklabels
Determines whether or not the tick labels are drawn.
showtickprefix
If "all", all tick labels are displayed with a prefix.
If "first", only the first tick is displayed with a
prefix. If "last", only the last tick is displayed with
a suffix. If "none", tick prefixes are hidden.
showticksuffix
Same as `showtickprefix` but for tick suffixes.
thickness
Sets the thickness of the color bar This measure
excludes the size of the padding, ticks and labels.
thicknessmode
Determines whether this color bar's thickness (i.e. the
measure in the constant color direction) is set in
units of plot "fraction" or in "pixels". Use
`thickness` to set the value.
tick0
Sets the placement of the first tick on this axis. Use
with `dtick`. If the axis `type` is "log", then you
must take the log of your starting tick (e.g. to set
the starting tick to 100, set the `tick0` to 2) except
when `dtick`=*L<f>* (see `dtick` for more info). If the
axis `type` is "date", it should be a date string, like
date data. If the axis `type` is "category", it should
be a number, using the scale where each category is
assigned a serial number from zero in the order it
appears.
tickangle
Sets the angle of the tick labels with respect to the
horizontal. For example, a `tickangle` of -90 draws the
tick labels vertically.
tickcolor
Sets the tick color.
tickfont
Sets the color bar's tick label font
tickformat
Sets the tick label formatting rule using d3 formatting
mini-languages which are very similar to those in
Python. For numbers, see:
https://github.com/d3/d3-format/tree/v1.4.5#d3-format.
And for dates see: https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two items to
d3's date formatter: "%h" for half of the year as a
decimal number as well as "%{n}f" for fractional
seconds with n digits. For example, *2016-10-13
09:15:23.456* with tickformat "%H~%M~%S.%2f" would
display "09~15~23.46"
tickformatstops
A tuple of :class:`plotly.graph_objects.scatter3d.line.
colorbar.Tickformatstop` instances or dicts with
compatible properties
tickformatstopdefaults
When used in a template (as layout.template.data.scatte
r3d.line.colorbar.tickformatstopdefaults), sets the
default property values to use for elements of
scatter3d.line.colorbar.tickformatstops
ticklabeloverflow
Determines how we handle tick labels that would
overflow either the graph div or the domain of the
axis. The default value for inside tick labels is *hide
past domain*. In other cases the default is *hide past
div*.
ticklabelposition
Determines where tick labels are drawn relative to the
ticks. Left and right options are used when
`orientation` is "h", top and bottom when `orientation`
is "v".
ticklabelstep
Sets the spacing between tick labels as compared to the
spacing between ticks. A value of 1 (default) means
each tick gets a label. A value of 2 means shows every
2nd label. A larger value n means only every nth tick
is labeled. `tick0` determines which labels are shown.
Not implemented for axes with `type` "log" or
"multicategory", or when `tickmode` is "array".
ticklen
Sets the tick length (in px).
tickmode
Sets the tick mode for this axis. If "auto", the number
of ticks is set via `nticks`. If "linear", the
placement of the ticks is determined by a starting
position `tick0` and a tick step `dtick` ("linear" is
the default value if `tick0` and `dtick` are provided).
If "array", the placement of the ticks is set via
`tickvals` and the tick text is `ticktext`. ("array" is
the default value if `tickvals` is provided).
tickprefix
Sets a tick label prefix.
ticks
Determines whether ticks are drawn or not. If "", this
axis' ticks are not drawn. If "outside" ("inside"),
this axis' are drawn outside (inside) the axis lines.
ticksuffix
Sets a tick label suffix.
ticktext
Sets the text displayed at the ticks position via
`tickvals`. Only has an effect if `tickmode` is set to
"array". Used with `tickvals`.
ticktextsrc
Sets the source reference on Chart Studio Cloud for
`ticktext`.
tickvals
Sets the values at which ticks on this axis appear.
Only has an effect if `tickmode` is set to "array".
Used with `ticktext`.
tickvalssrc
Sets the source reference on Chart Studio Cloud for
`tickvals`.
tickwidth
Sets the tick width (in px).
title
:class:`plotly.graph_objects.scatter3d.line.colorbar.Ti
tle` instance or dict with compatible properties
x
Sets the x position with respect to `xref` of the color
bar (in plot fraction). When `xref` is "paper",
defaults to 1.02 when `orientation` is "v" and 0.5 when
`orientation` is "h". When `xref` is "container",
defaults to 1 when `orientation` is "v" and 0.5 when
`orientation` is "h". Must be between 0 and 1 if `xref`
is "container" and between "-2" and 3 if `xref` is
"paper".
xanchor
Sets this color bar's horizontal position anchor. This
anchor binds the `x` position to the "left", "center"
or "right" of the color bar. Defaults to "left" when
`orientation` is "v" and "center" when `orientation` is
"h".
xpad
Sets the amount of padding (in px) along the x
direction.
xref
Sets the container `x` refers to. "container" spans the
entire `width` of the plot. "paper" refers to the width
of the plotting area only.
y
Sets the y position with respect to `yref` of the color
bar (in plot fraction). When `yref` is "paper",
defaults to 0.5 when `orientation` is "v" and 1.02 when
`orientation` is "h". When `yref` is "container",
defaults to 0.5 when `orientation` is "v" and 1 when
`orientation` is "h". Must be between 0 and 1 if `yref`
is "container" and between "-2" and 3 if `yref` is
"paper".
yanchor
Sets this color bar's vertical position anchor This
anchor binds the `y` position to the "top", "middle" or
"bottom" of the color bar. Defaults to "middle" when
`orientation` is "v" and "bottom" when `orientation` is
"h".
ypad
Sets the amount of padding (in px) along the y
direction.
yref
Sets the container `y` refers to. "container" spans the
entire `height` of the plot. "paper" refers to the
height of the plotting area only.
Returns
-------
ColorBar
"""
super().__init__("colorbar")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError("""\
The first argument to the plotly.graph_objs.scatter3d.line.ColorBar
constructor must be a dict or
an instance of :class:`plotly.graph_objs.scatter3d.line.ColorBar`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("bgcolor", arg, bgcolor)
self._set_property("bordercolor", arg, bordercolor)
self._set_property("borderwidth", arg, borderwidth)
self._set_property("dtick", arg, dtick)
self._set_property("exponentformat", arg, exponentformat)
self._set_property("labelalias", arg, labelalias)
self._set_property("len", arg, len)
self._set_property("lenmode", arg, lenmode)
self._set_property("minexponent", arg, minexponent)
self._set_property("nticks", arg, nticks)
self._set_property("orientation", arg, orientation)
self._set_property("outlinecolor", arg, outlinecolor)
self._set_property("outlinewidth", arg, outlinewidth)
self._set_property("separatethousands", arg, separatethousands)
self._set_property("showexponent", arg, showexponent)
self._set_property("showticklabels", arg, showticklabels)
self._set_property("showtickprefix", arg, showtickprefix)
self._set_property("showticksuffix", arg, showticksuffix)
self._set_property("thickness", arg, thickness)
self._set_property("thicknessmode", arg, thicknessmode)
self._set_property("tick0", arg, tick0)
self._set_property("tickangle", arg, tickangle)
self._set_property("tickcolor", arg, tickcolor)
self._set_property("tickfont", arg, tickfont)
self._set_property("tickformat", arg, tickformat)
self._set_property("tickformatstops", arg, tickformatstops)
self._set_property("tickformatstopdefaults", arg, tickformatstopdefaults)
self._set_property("ticklabeloverflow", arg, ticklabeloverflow)
self._set_property("ticklabelposition", arg, ticklabelposition)
self._set_property("ticklabelstep", arg, ticklabelstep)
self._set_property("ticklen", arg, ticklen)
self._set_property("tickmode", arg, tickmode)
self._set_property("tickprefix", arg, tickprefix)
self._set_property("ticks", arg, ticks)
self._set_property("ticksuffix", arg, ticksuffix)
self._set_property("ticktext", arg, ticktext)
self._set_property("ticktextsrc", arg, ticktextsrc)
self._set_property("tickvals", arg, tickvals)
self._set_property("tickvalssrc", arg, tickvalssrc)
self._set_property("tickwidth", arg, tickwidth)
self._set_property("title", arg, title)
self._set_property("x", arg, x)
self._set_property("xanchor", arg, xanchor)
self._set_property("xpad", arg, xpad)
self._set_property("xref", arg, xref)
self._set_property("y", arg, y)
self._set_property("yanchor", arg, yanchor)
self._set_property("ypad", arg, ypad)
self._set_property("yref", arg, yref)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| ColorBar |
python | ray-project__ray | python/ray/serve/llm/__init__.py | {
"start": 809,
"end": 940
} | class ____(_LLMConfig):
"""The configuration for starting an LLM deployment."""
pass
@PublicAPI(stability="alpha")
| LLMConfig |
python | neetcode-gh__leetcode | python/0054-spiral-matrix.py | {
"start": 0,
"end": 949
} | class ____:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
res = []
left, right = 0, len(matrix[0])
top, bottom = 0, len(matrix)
while left < right and top < bottom:
# get every i in the top row
for i in range(left, right):
res.append(matrix[top][i])
top += 1
# get every i in the right col
for i in range(top, bottom):
res.append(matrix[i][right - 1])
right -= 1
if not (left < right and top < bottom):
break
# get every i in the bottom row
for i in range(right - 1, left - 1, -1):
res.append(matrix[bottom - 1][i])
bottom -= 1
# get every i in the left col
for i in range(bottom - 1, top - 1, -1):
res.append(matrix[i][left])
left += 1
return res
| Solution |
python | apache__airflow | providers/mysql/tests/unit/mysql/transfers/test_s3_to_mysql.py | {
"start": 1084,
"end": 4765
} | class ____:
@pytest.fixture(autouse=True)
def setup_connections(self, create_connection_without_db):
create_connection_without_db(
models.Connection(
conn_id="s3_test",
conn_type="s3",
schema="test",
extra='{"aws_access_key_id": "aws_access_key_id", "aws_secret_access_key":'
' "aws_secret_access_key"}',
)
)
create_connection_without_db(
models.Connection(
conn_id="mysql_test",
conn_type="mysql",
host="some.host.com",
schema="test_db",
login="user",
password="password",
)
)
self.s3_to_mysql_transfer_kwargs = {
"aws_conn_id": "s3_test",
"mysql_conn_id": "mysql_test",
"s3_source_key": "test/s3_to_mysql_test.csv",
"mysql_table": "mysql_table",
"mysql_duplicate_key_handling": "IGNORE",
"mysql_extra_options": """
FIELDS TERMINATED BY ','
IGNORE 1 LINES
""",
"mysql_local_infile": False,
"task_id": "task_id",
"dag": None,
}
@patch("airflow.providers.mysql.transfers.s3_to_mysql.S3Hook.download_file")
@patch("airflow.providers.mysql.transfers.s3_to_mysql.MySqlHook.bulk_load_custom")
@patch("airflow.providers.mysql.transfers.s3_to_mysql.os.remove")
def test_execute(self, mock_remove, mock_bulk_load_custom, mock_download_file):
S3ToMySqlOperator(**self.s3_to_mysql_transfer_kwargs).execute({})
mock_download_file.assert_called_once_with(key=self.s3_to_mysql_transfer_kwargs["s3_source_key"])
mock_bulk_load_custom.assert_called_once_with(
table=self.s3_to_mysql_transfer_kwargs["mysql_table"],
tmp_file=mock_download_file.return_value,
duplicate_key_handling=self.s3_to_mysql_transfer_kwargs["mysql_duplicate_key_handling"],
extra_options=self.s3_to_mysql_transfer_kwargs["mysql_extra_options"],
)
mock_remove.assert_called_once_with(mock_download_file.return_value)
@patch("airflow.providers.mysql.transfers.s3_to_mysql.S3Hook.download_file")
@patch("airflow.providers.mysql.transfers.s3_to_mysql.MySqlHook.bulk_load_custom")
@patch("airflow.providers.mysql.transfers.s3_to_mysql.os.remove")
def test_execute_exception(self, mock_remove, mock_bulk_load_custom, mock_download_file):
mock_bulk_load_custom.side_effect = RuntimeError("Some exception occurred")
with pytest.raises(RuntimeError, match="Some exception occurred"):
S3ToMySqlOperator(**self.s3_to_mysql_transfer_kwargs).execute({})
mock_download_file.assert_called_once_with(key=self.s3_to_mysql_transfer_kwargs["s3_source_key"])
mock_bulk_load_custom.assert_called_once_with(
table=self.s3_to_mysql_transfer_kwargs["mysql_table"],
tmp_file=mock_download_file.return_value,
duplicate_key_handling=self.s3_to_mysql_transfer_kwargs["mysql_duplicate_key_handling"],
extra_options=self.s3_to_mysql_transfer_kwargs["mysql_extra_options"],
)
mock_remove.assert_called_once_with(mock_download_file.return_value)
def teardown_method(self):
with create_session() as session:
(
session.query(models.Connection)
.filter(
or_(models.Connection.conn_id == "s3_test", models.Connection.conn_id == "mysql_test")
)
.delete()
)
| TestS3ToMySqlTransfer |
python | kamyu104__LeetCode-Solutions | Python/shortest-path-in-a-weighted-tree.py | {
"start": 535,
"end": 2274
} | class ____(object):
def treeQueries(self, n, edges, queries):
"""
:type n: int
:type edges: List[List[int]]
:type queries: List[List[int]]
:rtype: List[int]
"""
def iter_dfs():
L, R, dist, lookup = [0]*n, [0]*n, [0]*n, [0]*n
cnt = 0
stk = [(1, (0, -1, 0))]
while stk:
step, args = stk.pop()
if step == 1:
u, p, d = args
L[u] = cnt
cnt += 1
dist[u] = d
stk.append((2, (u,)))
for v, w in adj[u]:
if v == p:
continue
lookup[v] = w
stk.append((1, (v, u, d+w)))
elif step == 2:
u = args[0]
R[u] = cnt
return L, R, dist, lookup
adj = [[] for _ in xrange(n)]
for u, v, w in edges:
u -= 1
v -= 1
adj[u].append((v, w))
adj[v].append((u, w))
L, R, dist, lookup = iter_dfs()
bit = BIT(n)
result = []
for q in queries:
if q[0] == 1:
_, u, v, w = q
u -= 1
v -= 1
if L[u] > L[v]:
u, v = v, u
diff = w-lookup[v]
bit.add(L[v], diff)
bit.add(R[v], -diff)
lookup[v] = w
else:
_, x = q
x -= 1
result.append(dist[x]+bit.query(L[x]))
return result
# Time: O(nlogn)
# Space: O(n)
# dfs, fenwick tree
| Solution |
python | doocs__leetcode | solution/2100-2199/2154.Keep Multiplying Found Values by Two/Solution.py | {
"start": 0,
"end": 187
} | class ____:
def findFinalValue(self, nums: List[int], original: int) -> int:
s = set(nums)
while original in s:
original <<= 1
return original
| Solution |
python | jd__tenacity | tests/test_tenacity.py | {
"start": 29885,
"end": 30514
} | class ____:
"""Holds counter state for invoking a method several times in a row."""
def __init__(self, count):
self.counter = 0
self.count = count
def go2(self):
raise OSError("Hi there, I'm an IOError")
def go(self):
"""Raise a NameError with an IOError as cause until after count threshold has been crossed.
Then return True.
"""
if self.counter < self.count:
self.counter += 1
try:
self.go2()
except OSError as e:
raise NameError() from e
return True
| NoIOErrorCauseAfterCount |
python | numpy__numpy | numpy/typing/tests/data/pass/ufunc_config.py | {
"start": 318,
"end": 403
} | class ____:
def write(self, a: str, b: int = 1) -> None:
return None
| Write2 |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/triggers/test_eks.py | {
"start": 7301,
"end": 12792
} | class ____(TestEksTrigger):
def setup_method(self):
super().setup_method()
self.get_waiter_patcher = patch(
"airflow.providers.amazon.aws.hooks.eks.EksHook.get_waiter", return_value="waiter"
)
self.mock_waiter = self.get_waiter_patcher.start()
self.trigger = EksDeleteClusterTrigger(
cluster_name=CLUSTER_NAME,
waiter_delay=WAITER_DELAY,
waiter_max_attempts=WAITER_MAX_ATTEMPTS,
aws_conn_id=AWS_CONN_ID,
region_name=REGION_NAME,
force_delete_compute=False,
)
self.trigger.log.info = Mock()
def teardown_method(self):
super().teardown_method()
self.get_waiter_patcher.stop()
@pytest.mark.asyncio
async def test_delete_nodegroups(self):
mock_list_node_groups = AsyncMock(return_value={"nodegroups": ["g1", "g2"]})
mock_delete_nodegroup = AsyncMock()
mock_client = AsyncMock(list_nodegroups=mock_list_node_groups, delete_nodegroup=mock_delete_nodegroup)
await self.trigger.delete_any_nodegroups(mock_client)
mock_list_node_groups.assert_called_once_with(clusterName=CLUSTER_NAME)
self.trigger.log.info.assert_has_calls([call("Deleting nodegroups"), call("All nodegroups deleted")])
self.mock_waiter.assert_called_once_with(
"all_nodegroups_deleted", deferrable=True, client=mock_client
)
mock_delete_nodegroup.assert_has_calls(
[
call(clusterName=CLUSTER_NAME, nodegroupName="g1"),
call(clusterName=CLUSTER_NAME, nodegroupName="g2"),
]
)
self.mock_async_wait.assert_called_once_with(
waiter="waiter",
waiter_delay=WAITER_DELAY,
waiter_max_attempts=WAITER_MAX_ATTEMPTS,
args={"clusterName": CLUSTER_NAME},
failure_message="Error deleting nodegroup for cluster test_cluster",
status_message="Deleting nodegroups associated with the cluster",
status_args=["nodegroups"],
)
@pytest.mark.asyncio
async def test_when_there_are_no_nodegroups_it_should_only_log_message(self):
mock_list_node_groups = AsyncMock(return_value={"nodegroups": []})
mock_delete_nodegroup = AsyncMock()
mock_client = AsyncMock(list_nodegroups=mock_list_node_groups, delete_nodegroup=mock_delete_nodegroup)
await self.trigger.delete_any_nodegroups(mock_client)
mock_list_node_groups.assert_called_once_with(clusterName=CLUSTER_NAME)
self.mock_async_wait.assert_not_called()
mock_delete_nodegroup.assert_not_called()
self.trigger.log.info.assert_called_once_with(
"No nodegroups associated with cluster %s", CLUSTER_NAME
)
@pytest.mark.asyncio
async def test_delete_any_fargate_profiles(self):
mock_list_fargate_profiles = AsyncMock(return_value={"fargateProfileNames": FARGATE_PROFILES})
mock_delete_fargate_profile = AsyncMock()
mock_client = AsyncMock(
list_fargate_profiles=mock_list_fargate_profiles,
delete_fargate_profile=mock_delete_fargate_profile,
get_waiter=self.mock_waiter,
)
await self.trigger.delete_any_fargate_profiles(mock_client)
mock_list_fargate_profiles.assert_called_once_with(clusterName=CLUSTER_NAME)
self.trigger.log.info.assert_has_calls(
[
call("Waiting for Fargate profiles to delete. This will take some time."),
call("All Fargate profiles deleted"),
]
)
self.mock_waiter.assert_has_calls([call("fargate_profile_deleted"), call("fargate_profile_deleted")])
mock_delete_fargate_profile.assert_has_calls(
[
call(clusterName=CLUSTER_NAME, fargateProfileName="p1"),
call(clusterName=CLUSTER_NAME, fargateProfileName="p2"),
]
)
self.mock_async_wait.assert_has_calls(
[
call(
waiter="waiter",
waiter_delay=WAITER_DELAY,
waiter_max_attempts=WAITER_MAX_ATTEMPTS,
args={"clusterName": CLUSTER_NAME, "fargateProfileName": profile},
failure_message="Error deleting fargate profile for cluster test_cluster",
status_message="Status of fargate profile is",
status_args=["fargateProfile.status"],
)
for profile in FARGATE_PROFILES
]
)
@pytest.mark.asyncio
async def test_when_there_are_no_fargate_profiles_it_should_only_log_message(self):
mock_list_fargate_profiles = AsyncMock(return_value={"fargateProfileNames": []})
mock_delete_fargate_profile = AsyncMock()
mock_client = AsyncMock(
list_fargate_profiles=mock_list_fargate_profiles,
delete_fargate_profile=mock_delete_fargate_profile,
)
await self.trigger.delete_any_fargate_profiles(mock_client)
mock_list_fargate_profiles.assert_called_once_with(clusterName=CLUSTER_NAME)
self.mock_async_wait.assert_not_called()
mock_delete_fargate_profile.assert_not_called()
self.trigger.log.info.assert_called_once_with(
"No Fargate profiles associated with cluster %s", CLUSTER_NAME
)
| TestEksDeleteClusterTriggerDeleteNodegroupsAndFargateProfiles |
python | numpy__numpy | numpy/_build_utils/tempita/_tempita.py | {
"start": 17165,
"end": 36992
} | class ____:
def __call__(self, *args, **kw):
return self
def __str__(self):
return ""
def __repr__(self):
return "Empty"
def __unicode__(self):
return ""
def __iter__(self):
return iter(())
def __bool__(self):
return False
Empty = _Empty()
del _Empty
############################################################
## Lexing and Parsing
############################################################
def lex(s, name=None, trim_whitespace=True, line_offset=0, delimiters=None):
"""
Lex a string into chunks:
>>> lex('hey')
['hey']
>>> lex('hey {{you}}')
['hey ', ('you', (1, 7))]
>>> lex('hey {{')
Traceback (most recent call last):
...
TemplateError: No }} to finish last expression at line 1 column 7
>>> lex('hey }}')
Traceback (most recent call last):
...
TemplateError: }} outside expression at line 1 column 7
>>> lex('hey {{ {{')
Traceback (most recent call last):
...
TemplateError: {{ inside expression at line 1 column 10
"""
if delimiters is None:
delimiters = (
Template.default_namespace["start_braces"],
Template.default_namespace["end_braces"],
)
in_expr = False
chunks = []
last = 0
last_pos = (line_offset + 1, 1)
token_re = re.compile(
r"%s|%s" % (re.escape(delimiters[0]), re.escape(delimiters[1]))
)
for match in token_re.finditer(s):
expr = match.group(0)
pos = find_position(s, match.end(), last, last_pos)
if expr == delimiters[0] and in_expr:
raise TemplateError(
"%s inside expression" % delimiters[0], position=pos, name=name
)
elif expr == delimiters[1] and not in_expr:
raise TemplateError(
"%s outside expression" % delimiters[1], position=pos, name=name
)
if expr == delimiters[0]:
part = s[last:match.start()]
if part:
chunks.append(part)
in_expr = True
else:
chunks.append((s[last: match.start()], last_pos))
in_expr = False
last = match.end()
last_pos = pos
if in_expr:
raise TemplateError(
"No %s to finish last expression" % delimiters[1],
name=name,
position=last_pos,
)
part = s[last:]
if part:
chunks.append(part)
if trim_whitespace:
chunks = trim_lex(chunks)
return chunks
statement_re = re.compile(r"^(?:if |elif |for |def |inherit |default |py:)")
single_statements = ["else", "endif", "endfor", "enddef", "continue", "break"]
trail_whitespace_re = re.compile(r"\n\r?[\t ]*$")
lead_whitespace_re = re.compile(r"^[\t ]*\n")
def trim_lex(tokens):
r"""
Takes a lexed set of tokens, and removes whitespace when there is
a directive on a line by itself:
>>> tokens = lex('{{if x}}\nx\n{{endif}}\ny', trim_whitespace=False)
>>> tokens
[('if x', (1, 3)), '\nx\n', ('endif', (3, 3)), '\ny']
>>> trim_lex(tokens)
[('if x', (1, 3)), 'x\n', ('endif', (3, 3)), 'y']
"""
last_trim = None
for i, current in enumerate(tokens):
if isinstance(current, basestring_):
# we don't trim this
continue
item = current[0]
if not statement_re.search(item) and item not in single_statements:
continue
if not i:
prev = ""
else:
prev = tokens[i - 1]
if i + 1 >= len(tokens):
next_chunk = ""
else:
next_chunk = tokens[i + 1]
if not isinstance(next_chunk, basestring_) or not isinstance(prev, basestring_):
continue
prev_ok = not prev or trail_whitespace_re.search(prev)
if i == 1 and not prev.strip():
prev_ok = True
if last_trim is not None and last_trim + 2 == i and not prev.strip():
prev_ok = "last"
if prev_ok and (
not next_chunk
or lead_whitespace_re.search(next_chunk)
or (i == len(tokens) - 2 and not next_chunk.strip())
):
if prev:
if (i == 1 and not prev.strip()) or prev_ok == "last":
tokens[i - 1] = ""
else:
m = trail_whitespace_re.search(prev)
# +1 to leave the leading \n on:
prev = prev[: m.start() + 1]
tokens[i - 1] = prev
if next_chunk:
last_trim = i
if i == len(tokens) - 2 and not next_chunk.strip():
tokens[i + 1] = ""
else:
m = lead_whitespace_re.search(next_chunk)
next_chunk = next_chunk[m.end():]
tokens[i + 1] = next_chunk
return tokens
def find_position(string, index, last_index, last_pos):
"""Given a string and index, return (line, column)"""
lines = string.count("\n", last_index, index)
if lines > 0:
column = index - string.rfind("\n", last_index, index)
else:
column = last_pos[1] + (index - last_index)
return (last_pos[0] + lines, column)
def parse(s, name=None, line_offset=0, delimiters=None):
r"""
Parses a string into a kind of AST
>>> parse('{{x}}')
[('expr', (1, 3), 'x')]
>>> parse('foo')
['foo']
>>> parse('{{if x}}test{{endif}}')
[('cond', (1, 3), ('if', (1, 3), 'x', ['test']))]
>>> parse('series->{{for x in y}}x={{x}}{{endfor}}')
['series->', ('for', (1, 11), ('x',), 'y', ['x=', ('expr', (1, 27), 'x')])]
>>> parse('{{for x, y in z:}}{{continue}}{{endfor}}')
[('for', (1, 3), ('x', 'y'), 'z', [('continue', (1, 21))])]
>>> parse('{{py:x=1}}')
[('py', (1, 3), 'x=1')]
>>> parse('{{if x}}a{{elif y}}b{{else}}c{{endif}}')
[('cond', (1, 3), ('if', (1, 3), 'x', ['a']), ('elif', (1, 12), 'y', ['b']), ('else', (1, 23), None, ['c']))]
Some exceptions::
>>> parse('{{continue}}')
Traceback (most recent call last):
...
TemplateError: continue outside of for loop at line 1 column 3
>>> parse('{{if x}}foo')
Traceback (most recent call last):
...
TemplateError: No {{endif}} at line 1 column 3
>>> parse('{{else}}')
Traceback (most recent call last):
...
TemplateError: else outside of an if block at line 1 column 3
>>> parse('{{if x}}{{for x in y}}{{endif}}{{endfor}}')
Traceback (most recent call last):
...
TemplateError: Unexpected endif at line 1 column 25
>>> parse('{{if}}{{endif}}')
Traceback (most recent call last):
...
TemplateError: if with no expression at line 1 column 3
>>> parse('{{for x y}}{{endfor}}')
Traceback (most recent call last):
...
TemplateError: Bad for (no "in") in 'x y' at line 1 column 3
>>> parse('{{py:x=1\ny=2}}')
Traceback (most recent call last):
...
TemplateError: Multi-line py blocks must start with a newline at line 1 column 3
""" # noqa: E501
if delimiters is None:
delimiters = (
Template.default_namespace["start_braces"],
Template.default_namespace["end_braces"],
)
tokens = lex(s, name=name, line_offset=line_offset, delimiters=delimiters)
result = []
while tokens:
next_chunk, tokens = parse_expr(tokens, name)
result.append(next_chunk)
return result
def parse_expr(tokens, name, context=()):
if isinstance(tokens[0], basestring_):
return tokens[0], tokens[1:]
expr, pos = tokens[0]
expr = expr.strip()
if expr.startswith("py:"):
expr = expr[3:].lstrip(" \t")
if expr.startswith(("\n", "\r")):
expr = expr.lstrip("\r\n")
if "\r" in expr:
expr = expr.replace("\r\n", "\n")
expr = expr.replace("\r", "")
expr += "\n"
elif "\n" in expr:
raise TemplateError(
"Multi-line py blocks must start with a newline",
position=pos,
name=name,
)
return ("py", pos, expr), tokens[1:]
elif expr in ("continue", "break"):
if "for" not in context:
raise TemplateError("continue outside of for loop", position=pos, name=name)
return (expr, pos), tokens[1:]
elif expr.startswith("if "):
return parse_cond(tokens, name, context)
elif expr.startswith("elif ") or expr == "else":
raise TemplateError(
"%s outside of an if block" % expr.split()[0], position=pos, name=name
)
elif expr in ("if", "elif", "for"):
raise TemplateError("%s with no expression" % expr, position=pos, name=name)
elif expr in ("endif", "endfor", "enddef"):
raise TemplateError("Unexpected %s" % expr, position=pos, name=name)
elif expr.startswith("for "):
return parse_for(tokens, name, context)
elif expr.startswith("default "):
return parse_default(tokens, name, context)
elif expr.startswith("inherit "):
return parse_inherit(tokens, name, context)
elif expr.startswith("def "):
return parse_def(tokens, name, context)
elif expr.startswith("#"):
return ("comment", pos, tokens[0][0]), tokens[1:]
return ("expr", pos, tokens[0][0]), tokens[1:]
def parse_cond(tokens, name, context):
start = tokens[0][1]
pieces = []
context = context + ("if",)
while 1:
if not tokens:
raise TemplateError("Missing {{endif}}", position=start, name=name)
if isinstance(tokens[0], tuple) and tokens[0][0] == "endif":
return ("cond", start) + tuple(pieces), tokens[1:]
next_chunk, tokens = parse_one_cond(tokens, name, context)
pieces.append(next_chunk)
def parse_one_cond(tokens, name, context):
(first, pos), tokens = tokens[0], tokens[1:]
content = []
first = first.removesuffix(":")
if first.startswith("if "):
part = ("if", pos, first[3:].lstrip(), content)
elif first.startswith("elif "):
part = ("elif", pos, first[5:].lstrip(), content)
elif first == "else":
part = ("else", pos, None, content)
else:
assert 0, "Unexpected token %r at %s" % (first, pos)
while 1:
if not tokens:
raise TemplateError("No {{endif}}", position=pos, name=name)
if isinstance(tokens[0], tuple) and (
tokens[0][0] == "endif"
or tokens[0][0].startswith("elif ")
or tokens[0][0] == "else"
):
return part, tokens
next_chunk, tokens = parse_expr(tokens, name, context)
content.append(next_chunk)
def parse_for(tokens, name, context):
first, pos = tokens[0]
tokens = tokens[1:]
context = ("for",) + context
content = []
assert first.startswith("for "), first
first = first.removesuffix(":")
first = first[3:].strip()
match = in_re.search(first)
if not match:
raise TemplateError('Bad for (no "in") in %r' % first, position=pos, name=name)
vars = first[: match.start()]
if "(" in vars:
raise TemplateError(
"You cannot have () in the variable section of a for loop (%r)" % vars,
position=pos,
name=name,
)
vars = tuple(v.strip() for v in first[: match.start()].split(",") if v.strip())
expr = first[match.end():]
while 1:
if not tokens:
raise TemplateError("No {{endfor}}", position=pos, name=name)
if isinstance(tokens[0], tuple) and tokens[0][0] == "endfor":
return ("for", pos, vars, expr, content), tokens[1:]
next_chunk, tokens = parse_expr(tokens, name, context)
content.append(next_chunk)
def parse_default(tokens, name, context):
first, pos = tokens[0]
assert first.startswith("default ")
first = first.split(None, 1)[1]
parts = first.split("=", 1)
if len(parts) == 1:
raise TemplateError(
"Expression must be {{default var=value}}; no = found in %r" % first,
position=pos,
name=name,
)
var = parts[0].strip()
if "," in var:
raise TemplateError(
"{{default x, y = ...}} is not supported", position=pos, name=name
)
if not var_re.search(var):
raise TemplateError(
"Not a valid variable name for {{default}}: %r" % var,
position=pos,
name=name,
)
expr = parts[1].strip()
return ("default", pos, var, expr), tokens[1:]
def parse_inherit(tokens, name, context):
first, pos = tokens[0]
assert first.startswith("inherit ")
expr = first.split(None, 1)[1]
return ("inherit", pos, expr), tokens[1:]
def parse_def(tokens, name, context):
first, start = tokens[0]
tokens = tokens[1:]
assert first.startswith("def ")
first = first.split(None, 1)[1]
first = first.removesuffix(":")
if "(" not in first:
func_name = first
sig = ((), None, None, {})
elif not first.endswith(")"):
raise TemplateError(
"Function definition doesn't end with ): %s" % first,
position=start,
name=name,
)
else:
first = first[:-1]
func_name, sig_text = first.split("(", 1)
sig = parse_signature(sig_text, name, start)
context = context + ("def",)
content = []
while 1:
if not tokens:
raise TemplateError("Missing {{enddef}}", position=start, name=name)
if isinstance(tokens[0], tuple) and tokens[0][0] == "enddef":
return ("def", start, func_name, sig, content), tokens[1:]
next_chunk, tokens = parse_expr(tokens, name, context)
content.append(next_chunk)
def parse_signature(sig_text, name, pos):
tokens = tokenize.generate_tokens(StringIO(sig_text).readline)
sig_args = []
var_arg = None
var_kw = None
defaults = {}
def get_token(pos=False):
try:
tok_type, tok_string, (srow, scol), (erow, ecol), line = next(tokens)
except StopIteration:
return tokenize.ENDMARKER, ""
if pos:
return tok_type, tok_string, (srow, scol), (erow, ecol)
else:
return tok_type, tok_string
while 1:
var_arg_type = None
tok_type, tok_string = get_token()
if tok_type == tokenize.ENDMARKER:
break
if tok_type == tokenize.OP and tok_string in {"*", "**"}:
var_arg_type = tok_string
tok_type, tok_string = get_token()
if tok_type != tokenize.NAME:
raise TemplateError(
"Invalid signature: (%s)" % sig_text, position=pos, name=name
)
var_name = tok_string
tok_type, tok_string = get_token()
if tok_type == tokenize.ENDMARKER or (
tok_type == tokenize.OP and tok_string == ","
):
if var_arg_type == "*":
var_arg = var_name
elif var_arg_type == "**":
var_kw = var_name
else:
sig_args.append(var_name)
if tok_type == tokenize.ENDMARKER:
break
continue
if var_arg_type is not None:
raise TemplateError(
"Invalid signature: (%s)" % sig_text, position=pos, name=name
)
if tok_type == tokenize.OP and tok_string == "=":
nest_type = None
unnest_type = None
nest_count = 0
start_pos = end_pos = None
parts = []
while 1:
tok_type, tok_string, s, e = get_token(True)
if start_pos is None:
start_pos = s
end_pos = e
if tok_type == tokenize.ENDMARKER and nest_count:
raise TemplateError(
"Invalid signature: (%s)" % sig_text, position=pos, name=name
)
if not nest_count and (
tok_type == tokenize.ENDMARKER
or (tok_type == tokenize.OP and tok_string == ",")
):
default_expr = isolate_expression(sig_text, start_pos, end_pos)
defaults[var_name] = default_expr
sig_args.append(var_name)
break
parts.append((tok_type, tok_string))
if nest_count and tok_type == tokenize.OP and tok_string == nest_type:
nest_count += 1
elif (
nest_count and tok_type == tokenize.OP and tok_string == unnest_type
):
nest_count -= 1
if not nest_count:
nest_type = unnest_type = None
elif (
not nest_count
and tok_type == tokenize.OP
and tok_string in ("(", "[", "{")
):
nest_type = tok_string
nest_count = 1
unnest_type = {"(": ")", "[": "]", "{": "}"}[nest_type]
return sig_args, var_arg, var_kw, defaults
def isolate_expression(string, start_pos, end_pos):
srow, scol = start_pos
srow -= 1
erow, ecol = end_pos
erow -= 1
lines = string.splitlines(True)
if srow == erow:
return lines[srow][scol:ecol]
parts = [lines[srow][scol:]]
parts.extend(lines[srow + 1:erow])
if erow < len(lines):
# It'll sometimes give (end_row_past_finish, 0)
parts.append(lines[erow][:ecol])
return "".join(parts)
_fill_command_usage = """\
%prog [OPTIONS] TEMPLATE arg=value
Use py:arg=value to set a Python value; otherwise all values are
strings.
"""
def fill_command(args=None):
import optparse
import os
import sys
import pkg_resources
if args is None:
args = sys.argv[1:]
dist = pkg_resources.get_distribution("Paste")
parser = optparse.OptionParser(version=coerce_text(dist), usage=_fill_command_usage)
parser.add_option(
"-o",
"--output",
dest="output",
metavar="FILENAME",
help="File to write output to (default stdout)",
)
parser.add_option(
"--env",
dest="use_env",
action="store_true",
help="Put the environment in as top-level variables",
)
options, args = parser.parse_args(args)
if len(args) < 1:
print("You must give a template filename")
sys.exit(2)
template_name = args[0]
args = args[1:]
vars = {}
if options.use_env:
vars.update(os.environ)
for value in args:
if "=" not in value:
print("Bad argument: %r" % value)
sys.exit(2)
name, value = value.split("=", 1)
if name.startswith("py:"):
name = name[:3]
value = eval(value)
vars[name] = value
if template_name == "-":
template_content = sys.stdin.read()
template_name = "<stdin>"
else:
with open(template_name, "rb") as f:
template_content = f.read()
template = Template(template_content, name=template_name)
result = template.substitute(vars)
if options.output:
with open(options.output, "wb") as f:
f.write(result)
else:
sys.stdout.write(result)
if __name__ == "__main__":
fill_command()
| _Empty |
python | sympy__sympy | sympy/physics/quantum/cg.py | {
"start": 4480,
"end": 7162
} | class ____(Wigner3j):
r"""Class for Clebsch-Gordan coefficient.
Explanation
===========
Clebsch-Gordan coefficients describe the angular momentum coupling between
two systems. The coefficients give the expansion of a coupled total angular
momentum state and an uncoupled tensor product state. The Clebsch-Gordan
coefficients are defined as [1]_:
.. math ::
C^{j_3,m_3}_{j_1,m_1,j_2,m_2} = \left\langle j_1,m_1;j_2,m_2 | j_3,m_3\right\rangle
Parameters
==========
j1, m1, j2, m2 : Number, Symbol
Angular momenta of states 1 and 2.
j3, m3: Number, Symbol
Total angular momentum of the coupled system.
Examples
========
Define a Clebsch-Gordan coefficient and evaluate its value
>>> from sympy.physics.quantum.cg import CG
>>> from sympy import S
>>> cg = CG(S(3)/2, S(3)/2, S(1)/2, -S(1)/2, 1, 1)
>>> cg
CG(3/2, 3/2, 1/2, -1/2, 1, 1)
>>> cg.doit()
sqrt(3)/2
>>> CG(j1=S(1)/2, m1=-S(1)/2, j2=S(1)/2, m2=+S(1)/2, j3=1, m3=0).doit()
sqrt(2)/2
Compare [2]_.
See Also
========
Wigner3j: Wigner-3j symbols
References
==========
.. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988.
.. [2] `Clebsch-Gordan Coefficients, Spherical Harmonics, and d Functions
<https://pdg.lbl.gov/2020/reviews/rpp2020-rev-clebsch-gordan-coefs.pdf>`_
in P.A. Zyla *et al.* (Particle Data Group), Prog. Theor. Exp. Phys.
2020, 083C01 (2020).
"""
precedence = PRECEDENCE["Pow"] - 1
def doit(self, **hints):
if self.is_symbolic:
raise ValueError("Coefficients must be numerical")
return clebsch_gordan(self.j1, self.j2, self.j3, self.m1, self.m2, self.m3)
def _pretty(self, printer, *args):
bot = printer._print_seq(
(self.j1, self.m1, self.j2, self.m2), delimiter=',')
top = printer._print_seq((self.j3, self.m3), delimiter=',')
pad = max(top.width(), bot.width())
bot = prettyForm(*bot.left(' '))
top = prettyForm(*top.left(' '))
if not pad == bot.width():
bot = prettyForm(*bot.right(' '*(pad - bot.width())))
if not pad == top.width():
top = prettyForm(*top.right(' '*(pad - top.width())))
s = stringPict('C' + ' '*pad)
s = prettyForm(*s.below(bot))
s = prettyForm(*s.above(top))
return s
def _latex(self, printer, *args):
label = map(printer._print, (self.j3, self.m3, self.j1,
self.m1, self.j2, self.m2))
return r'C^{%s,%s}_{%s,%s,%s,%s}' % tuple(label)
| CG |
python | doocs__leetcode | solution/2200-2299/2273.Find Resultant Array After Removing Anagrams/Solution.py | {
"start": 0,
"end": 426
} | class ____:
def removeAnagrams(self, words: List[str]) -> List[str]:
def check(s: str, t: str) -> bool:
if len(s) != len(t):
return True
cnt = Counter(s)
for c in t:
cnt[c] -= 1
if cnt[c] < 0:
return True
return False
return [words[0]] + [t for s, t in pairwise(words) if check(s, t)]
| Solution |
python | pytorch__pytorch | tools/test/test_utils.py | {
"start": 62,
"end": 870
} | class ____(unittest.TestCase):
def test_create_from_namespaced_tuple(self) -> None:
helper = NamespaceHelper.from_namespaced_entity("aten::add")
self.assertEqual(helper.entity_name, "add")
self.assertEqual(helper.get_cpp_namespace(), "aten")
def test_default_namespace(self) -> None:
helper = NamespaceHelper.from_namespaced_entity("add")
self.assertEqual(helper.entity_name, "add")
self.assertEqual(helper.get_cpp_namespace(), "")
self.assertEqual(helper.get_cpp_namespace("default"), "default")
def test_namespace_levels_more_than_max(self) -> None:
with self.assertRaises(AssertionError):
NamespaceHelper(
namespace_str="custom_1::custom_2", entity_name="", max_level=1
)
| TestNamespaceHelper |
python | dagster-io__dagster | python_modules/automation/automation_tests/dagster_docs_tests/test_method_docstrings.py | {
"start": 189,
"end": 12634
} | class ____:
"""Test that method docstrings are validated correctly and self/cls parameters are handled properly."""
# Using function-based validation approach
def test_instance_method_docstring_validation(self):
"""Test that instance method docstrings are validated correctly."""
@public
class TestClass:
@public
def process_data(self, data, options=None):
"""Process the provided data with optional configuration.
Args:
data: The data to process
options: Optional processing configuration
Returns:
Processed data result
"""
pass
@public
def bad_method_with_self(self, data):
"""Process data (incorrect style documenting self).
Args:
self: The instance (should not be documented)
data: Data to process
Returns:
Processed data result
"""
pass
# Test valid instance method docstring (doesn't document 'self')
result = validate_docstring_text(
TestClass.process_data.__doc__ or "", "TestClass.process_data"
)
assert result.is_valid(), f"Instance method should have valid docstring: {result.errors}"
assert result.parsing_successful
# Test that documenting 'self' is handled gracefully (not flagged as RST error)
result_with_self = validate_docstring_text(
TestClass.bad_method_with_self.__doc__ or "", "TestClass.bad_method_with_self"
)
# Should parse successfully even though it's bad style
assert result_with_self.parsing_successful
def test_static_method_docstring_validation(self):
"""Test that static method docstrings are validated correctly."""
@public
class TestClass:
@public
@staticmethod
def validate_email(email, strict=False):
"""Validate email address format using regex.
Args:
email: Email address to validate
strict: Whether to use strict validation
Returns:
True if valid, False otherwise
"""
pass
result = validate_docstring_text(
TestClass.validate_email.__doc__ or "", "TestClass.validate_email"
)
assert result.is_valid(), f"Static method should have valid docstring: {result.errors}"
assert result.parsing_successful
def test_class_method_docstring_validation(self):
"""Test that class method docstrings are validated correctly."""
@public
class TestClass:
@public
@classmethod
def from_config(cls, config_file, validate=True):
"""Create instance from configuration file.
Args:
config_file: Path to configuration file
validate: Whether to validate configuration
Returns:
New instance of the class
"""
pass
@public
@classmethod
def bad_method_with_cls(cls, config):
"""Create instance with cls documented (incorrect style).
Args:
cls: The class (should not be documented)
config: Configuration data
Returns:
New instance
"""
pass
# Valid class method docstring (doesn't document 'cls')
result = validate_docstring_text(
TestClass.from_config.__doc__ or "", "TestClass.from_config"
)
assert result.is_valid(), f"Class method should have valid docstring: {result.errors}"
assert result.parsing_successful
# Test that documenting 'cls' is handled gracefully
result_with_cls = validate_docstring_text(
TestClass.bad_method_with_cls.__doc__ or "", "TestClass.bad_method_with_cls"
)
# Should parse successfully even though it's bad style
assert result_with_cls.parsing_successful
def test_property_docstring_validation(self):
"""Test that property docstrings are validated correctly."""
@public
class TestClass:
@public
@property
def status(self):
"""Current status of the instance.
Returns:
Status string indicating current state
"""
return "active"
result = validate_docstring_text(TestClass.status.__doc__ or "", "TestClass.status")
assert result.is_valid(), f"Property should have valid docstring: {result.errors}"
assert result.parsing_successful
def test_docstring_formatting_errors(self):
"""Test that common docstring formatting errors are detected."""
@public
class TestClass:
@public
def method_with_invalid_section(self, data):
"""Process data with invalid section header.
Arguments!: # Invalid punctuation in section header
data: Data to process
Returns:
Result
"""
pass
@public
def method_with_bad_indentation(self, data, options):
"""Process data with missing parameter indentation.
Args:
data: Not indented properly
options: Also not indented
Returns:
Result
"""
pass
# Test an error that we know the validator catches - invalid section header
result = validate_docstring_text(
TestClass.method_with_invalid_section.__doc__ or "",
"TestClass.method_with_invalid_section",
)
# This should either have warnings/errors or be parsing successfully
assert result.parsing_successful # At minimum should parse
# Missing indentation in parameters
result = validate_docstring_text(
TestClass.method_with_bad_indentation.__doc__ or "",
"TestClass.method_with_bad_indentation",
)
# This may or may not be flagged depending on RST parser behavior
assert result.parsing_successful # At minimum should parse
def test_edge_case_docstrings(self):
"""Test edge cases with docstrings."""
@public
class TestClass:
@public
def empty_method(self):
"""""" # noqa: D419
pass
@public
def helper(self):
"""Helper method."""
pass
@public
def whitespace_method(self):
""" """ # noqa: D419
pass
# Empty docstring should produce warning but not error
result_empty = validate_docstring_text(
TestClass.empty_method.__doc__ or "", "TestClass.empty_method"
)
assert result_empty.has_warnings()
assert "No docstring found" in str(result_empty.warnings)
assert result_empty.is_valid() # Empty is valid, just warned
# Minimal but valid docstring
result_minimal = validate_docstring_text(TestClass.helper.__doc__ or "", "TestClass.helper")
assert result_minimal.is_valid()
assert not result_minimal.has_errors()
# Whitespace-only docstring
result_whitespace = validate_docstring_text(
TestClass.whitespace_method.__doc__ or "", "TestClass.whitespace_method"
)
assert result_whitespace.has_warnings()
assert "No docstring found" in str(result_whitespace.warnings)
def test_complex_valid_docstring(self):
"""Test that complex but valid docstrings are handled correctly."""
@public
class TestClass:
@public
def execute_pipeline(self, pipeline_config, execution_mode, retry_policy=None):
"""Execute multi-stage data processing pipeline.
This method performs comprehensive data processing through multiple
stages with configurable options and error handling.
Args:
pipeline_config: Configuration dictionary containing:
- stage_1: Initial data ingestion settings
- stage_2: Data transformation parameters
- stage_3: Export configuration options
execution_mode: Mode selection ('sequential', 'parallel', 'adaptive')
retry_policy: Error retry configuration
Returns:
PipelineResult containing:
- execution_summary: High-level statistics
- stage_results: Detailed per-stage results
- performance_metrics: Timing and resource data
Raises:
PipelineConfigError: If configuration is invalid
DataProcessingError: If processing fails at any stage
ResourceError: If insufficient system resources
Examples:
Basic usage:
>>> config = {'stage_1': {...}, 'stage_2': {...}}
>>> result = processor.execute_pipeline(config, 'sequential')
>>> print(result.execution_summary)
Note:
This method requires substantial computational resources for large
datasets. Consider using batch processing for datasets larger
than 100,000 records.
"""
pass
result = validate_docstring_text(
TestClass.execute_pipeline.__doc__ or "", "TestClass.execute_pipeline"
)
# Should be valid despite complexity
assert result.is_valid() or not result.has_errors(), (
f"Complex docstring should be valid: {result.errors}"
)
assert result.parsing_successful
def test_mixed_method_types_in_single_class(self):
"""Test a class with all different types of methods."""
@public
class MixedMethodClass:
@public
def instance_method(self, data):
"""Process data using instance state.
Args:
data: Data to process
Returns:
Processed result
"""
pass
@public
@staticmethod
def utility_function(value):
"""Utility function that doesn't need instance or class.
Args:
value: Value to process
Returns:
Processed value
"""
pass
@public
@classmethod
def factory_method(cls, config):
"""Create instance using factory pattern.
Args:
config: Configuration for new instance
Returns:
New instance of this class
"""
pass
@public
@property
def computed_value(self):
"""Computed value based on instance state.
Returns:
Computed value
"""
return 42
# Test that all method types validate correctly
methods_to_test = [
(MixedMethodClass.instance_method.__doc__ or "", "MixedMethodClass.instance_method"),
(MixedMethodClass.utility_function.__doc__ or "", "MixedMethodClass.utility_function"),
(MixedMethodClass.factory_method.__doc__ or "", "MixedMethodClass.factory_method"),
(MixedMethodClass.computed_value.__doc__ or "", "MixedMethodClass.computed_value"),
]
for docstring, method_name in methods_to_test:
result = validate_docstring_text(docstring, method_name)
assert result.is_valid(), f"{method_name} should have valid docstring: {result.errors}"
| TestMethodDocstringValidation |
python | networkx__networkx | networkx/algorithms/isomorphism/temporalisomorphvf2.py | {
"start": 5084,
"end": 10946
} | class ____(DiGraphMatcher):
def __init__(self, G1, G2, temporal_attribute_name, delta):
"""Initialize TimeRespectingDiGraphMatcher.
G1 and G2 should be nx.DiGraph or nx.MultiDiGraph instances.
Examples
--------
To create a TimeRespectingDiGraphMatcher which checks for
syntactic and semantic feasibility:
>>> from networkx.algorithms import isomorphism
>>> from datetime import timedelta
>>> G1 = nx.DiGraph(nx.path_graph(4, create_using=nx.DiGraph()))
>>> G2 = nx.DiGraph(nx.path_graph(4, create_using=nx.DiGraph()))
>>> GM = isomorphism.TimeRespectingDiGraphMatcher(
... G1, G2, "date", timedelta(days=1)
... )
"""
self.temporal_attribute_name = temporal_attribute_name
self.delta = delta
super().__init__(G1, G2)
def get_pred_dates(self, Gx, Gx_node, core_x, pred):
"""
Get the dates of edges from predecessors.
"""
pred_dates = []
if isinstance(Gx, nx.DiGraph): # Graph G[u][v] returns the data dictionary.
for n in pred:
pred_dates.append(Gx[n][Gx_node][self.temporal_attribute_name])
else: # MultiGraph G[u][v] returns a dictionary of key -> data dictionary.
for n in pred:
for edge in Gx[n][
Gx_node
].values(): # Iterates all edge data between node pair.
pred_dates.append(edge[self.temporal_attribute_name])
return pred_dates
def get_succ_dates(self, Gx, Gx_node, core_x, succ):
"""
Get the dates of edges to successors.
"""
succ_dates = []
if isinstance(Gx, nx.DiGraph): # Graph G[u][v] returns the data dictionary.
for n in succ:
succ_dates.append(Gx[Gx_node][n][self.temporal_attribute_name])
else: # MultiGraph G[u][v] returns a dictionary of key -> data dictionary.
for n in succ:
for edge in Gx[Gx_node][
n
].values(): # Iterates all edge data between node pair.
succ_dates.append(edge[self.temporal_attribute_name])
return succ_dates
def one_hop(self, Gx, Gx_node, core_x, pred, succ):
"""
The ego node.
"""
pred_dates = self.get_pred_dates(Gx, Gx_node, core_x, pred)
succ_dates = self.get_succ_dates(Gx, Gx_node, core_x, succ)
return self.test_one(pred_dates, succ_dates) and self.test_two(
pred_dates, succ_dates
)
def two_hop_pred(self, Gx, Gx_node, core_x, pred):
"""
The predecessors of the ego node.
"""
return all(
self.one_hop(
Gx,
p,
core_x,
self.preds(Gx, core_x, p),
self.succs(Gx, core_x, p, Gx_node),
)
for p in pred
)
def two_hop_succ(self, Gx, Gx_node, core_x, succ):
"""
The successors of the ego node.
"""
return all(
self.one_hop(
Gx,
s,
core_x,
self.preds(Gx, core_x, s, Gx_node),
self.succs(Gx, core_x, s),
)
for s in succ
)
def preds(self, Gx, core_x, v, Gx_node=None):
pred = [n for n in Gx.predecessors(v) if n in core_x]
if Gx_node:
pred.append(Gx_node)
return pred
def succs(self, Gx, core_x, v, Gx_node=None):
succ = [n for n in Gx.successors(v) if n in core_x]
if Gx_node:
succ.append(Gx_node)
return succ
def test_one(self, pred_dates, succ_dates):
"""
Edges one hop out from Gx_node in the mapping should be
time-respecting with respect to each other, regardless of
direction.
"""
time_respecting = True
dates = pred_dates + succ_dates
if any(x is None for x in dates):
raise ValueError("Date or datetime not supplied for at least one edge.")
dates.sort() # Small to large.
if 0 < len(dates) and not (dates[-1] - dates[0] <= self.delta):
time_respecting = False
return time_respecting
def test_two(self, pred_dates, succ_dates):
"""
Edges from a dual Gx_node in the mapping should be ordered in
a time-respecting manner.
"""
time_respecting = True
pred_dates.sort()
succ_dates.sort()
# First out before last in; negative of the necessary condition for time-respect.
if (
0 < len(succ_dates)
and 0 < len(pred_dates)
and succ_dates[0] < pred_dates[-1]
):
time_respecting = False
return time_respecting
def semantic_feasibility(self, G1_node, G2_node):
"""Returns True if adding (G1_node, G2_node) is semantically
feasible.
Any subclass which redefines semantic_feasibility() must
maintain the self.tests if needed, to keep the match() method
functional. Implementations should consider multigraphs.
"""
pred, succ = (
[n for n in self.G1.predecessors(G1_node) if n in self.core_1],
[n for n in self.G1.successors(G1_node) if n in self.core_1],
)
if not self.one_hop(
self.G1, G1_node, self.core_1, pred, succ
): # Fail fast on first node.
return False
if not self.two_hop_pred(self.G1, G1_node, self.core_1, pred):
return False
if not self.two_hop_succ(self.G1, G1_node, self.core_1, succ):
return False
# Otherwise, this node is semantically feasible!
return True
| TimeRespectingDiGraphMatcher |
python | kubernetes-client__python | kubernetes/client/models/v1_runtime_class.py | {
"start": 383,
"end": 9352
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'api_version': 'str',
'handler': 'str',
'kind': 'str',
'metadata': 'V1ObjectMeta',
'overhead': 'V1Overhead',
'scheduling': 'V1Scheduling'
}
attribute_map = {
'api_version': 'apiVersion',
'handler': 'handler',
'kind': 'kind',
'metadata': 'metadata',
'overhead': 'overhead',
'scheduling': 'scheduling'
}
def __init__(self, api_version=None, handler=None, kind=None, metadata=None, overhead=None, scheduling=None, local_vars_configuration=None): # noqa: E501
"""V1RuntimeClass - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._api_version = None
self._handler = None
self._kind = None
self._metadata = None
self._overhead = None
self._scheduling = None
self.discriminator = None
if api_version is not None:
self.api_version = api_version
self.handler = handler
if kind is not None:
self.kind = kind
if metadata is not None:
self.metadata = metadata
if overhead is not None:
self.overhead = overhead
if scheduling is not None:
self.scheduling = scheduling
@property
def api_version(self):
"""Gets the api_version of this V1RuntimeClass. # noqa: E501
APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501
:return: The api_version of this V1RuntimeClass. # noqa: E501
:rtype: str
"""
return self._api_version
@api_version.setter
def api_version(self, api_version):
"""Sets the api_version of this V1RuntimeClass.
APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501
:param api_version: The api_version of this V1RuntimeClass. # noqa: E501
:type: str
"""
self._api_version = api_version
@property
def handler(self):
"""Gets the handler of this V1RuntimeClass. # noqa: E501
handler specifies the underlying runtime and configuration that the CRI implementation will use to handle pods of this class. The possible values are specific to the node & CRI configuration. It is assumed that all handlers are available on every node, and handlers of the same name are equivalent on every node. For example, a handler called \"runc\" might specify that the runc OCI runtime (using native Linux containers) will be used to run the containers in a pod. The Handler must be lowercase, conform to the DNS Label (RFC 1123) requirements, and is immutable. # noqa: E501
:return: The handler of this V1RuntimeClass. # noqa: E501
:rtype: str
"""
return self._handler
@handler.setter
def handler(self, handler):
"""Sets the handler of this V1RuntimeClass.
handler specifies the underlying runtime and configuration that the CRI implementation will use to handle pods of this class. The possible values are specific to the node & CRI configuration. It is assumed that all handlers are available on every node, and handlers of the same name are equivalent on every node. For example, a handler called \"runc\" might specify that the runc OCI runtime (using native Linux containers) will be used to run the containers in a pod. The Handler must be lowercase, conform to the DNS Label (RFC 1123) requirements, and is immutable. # noqa: E501
:param handler: The handler of this V1RuntimeClass. # noqa: E501
:type: str
"""
if self.local_vars_configuration.client_side_validation and handler is None: # noqa: E501
raise ValueError("Invalid value for `handler`, must not be `None`") # noqa: E501
self._handler = handler
@property
def kind(self):
"""Gets the kind of this V1RuntimeClass. # noqa: E501
Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501
:return: The kind of this V1RuntimeClass. # noqa: E501
:rtype: str
"""
return self._kind
@kind.setter
def kind(self, kind):
"""Sets the kind of this V1RuntimeClass.
Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501
:param kind: The kind of this V1RuntimeClass. # noqa: E501
:type: str
"""
self._kind = kind
@property
def metadata(self):
"""Gets the metadata of this V1RuntimeClass. # noqa: E501
:return: The metadata of this V1RuntimeClass. # noqa: E501
:rtype: V1ObjectMeta
"""
return self._metadata
@metadata.setter
def metadata(self, metadata):
"""Sets the metadata of this V1RuntimeClass.
:param metadata: The metadata of this V1RuntimeClass. # noqa: E501
:type: V1ObjectMeta
"""
self._metadata = metadata
@property
def overhead(self):
"""Gets the overhead of this V1RuntimeClass. # noqa: E501
:return: The overhead of this V1RuntimeClass. # noqa: E501
:rtype: V1Overhead
"""
return self._overhead
@overhead.setter
def overhead(self, overhead):
"""Sets the overhead of this V1RuntimeClass.
:param overhead: The overhead of this V1RuntimeClass. # noqa: E501
:type: V1Overhead
"""
self._overhead = overhead
@property
def scheduling(self):
"""Gets the scheduling of this V1RuntimeClass. # noqa: E501
:return: The scheduling of this V1RuntimeClass. # noqa: E501
:rtype: V1Scheduling
"""
return self._scheduling
@scheduling.setter
def scheduling(self, scheduling):
"""Sets the scheduling of this V1RuntimeClass.
:param scheduling: The scheduling of this V1RuntimeClass. # noqa: E501
:type: V1Scheduling
"""
self._scheduling = scheduling
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, V1RuntimeClass):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, V1RuntimeClass):
return True
return self.to_dict() != other.to_dict()
| V1RuntimeClass |
python | ray-project__ray | rllib/examples/envs/classes/random_env.py | {
"start": 4272,
"end": 4630
} | class ____(RandomEnv):
def __init__(self, config=None):
config = config or {}
config.update(
{
"observation_space": gym.spaces.Box(-1.0, 1.0, (5000,)),
"action_space": gym.spaces.Box(-1.0, 1.0, (5,)),
}
)
super().__init__(config=config)
| RandomLargeObsSpaceEnvContActions |
python | Textualize__textual | docs/examples/guide/widgets/hello04.py | {
"start": 363,
"end": 909
} | class ____(Static):
"""Display a greeting."""
DEFAULT_CSS = """
Hello {
width: 40;
height: 9;
padding: 1 2;
background: $panel;
border: $secondary tall;
content-align: center middle;
}
"""
def on_mount(self) -> None:
self.next_word()
def on_click(self) -> None:
self.next_word()
def next_word(self) -> None:
"""Get a new hello and update the content area."""
hello = next(hellos)
self.update(f"{hello}, [b]World[/b]!")
| Hello |
python | fastapi__sqlmodel | docs_src/tutorial/where/tutorial003_py310.py | {
"start": 71,
"end": 1548
} | class ____(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str
secret_name: str
age: int | None = None
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
engine = create_engine(sqlite_url, echo=True)
def create_db_and_tables():
SQLModel.metadata.create_all(engine)
def create_heroes():
hero_1 = Hero(name="Deadpond", secret_name="Dive Wilson")
hero_2 = Hero(name="Spider-Boy", secret_name="Pedro Parqueador")
hero_3 = Hero(name="Rusty-Man", secret_name="Tommy Sharp", age=48)
hero_4 = Hero(name="Tarantula", secret_name="Natalia Roman-on", age=32)
hero_5 = Hero(name="Black Lion", secret_name="Trevor Challa", age=35)
hero_6 = Hero(name="Dr. Weird", secret_name="Steve Weird", age=36)
hero_7 = Hero(name="Captain North America", secret_name="Esteban Rogelios", age=93)
with Session(engine) as session:
session.add(hero_1)
session.add(hero_2)
session.add(hero_3)
session.add(hero_4)
session.add(hero_5)
session.add(hero_6)
session.add(hero_7)
session.commit()
def select_heroes():
with Session(engine) as session:
statement = select(Hero).where(Hero.age > 35)
results = session.exec(statement)
for hero in results:
print(hero)
def main():
create_db_and_tables()
create_heroes()
select_heroes()
if __name__ == "__main__":
main()
| Hero |
python | pandas-dev__pandas | asv_bench/benchmarks/indexing.py | {
"start": 11050,
"end": 11584
} | class ____:
def setup(self):
dti = date_range("2016-01-01", periods=10000, tz="US/Pacific")
index = np.array(dti)
unsorted_index = index.copy()
unsorted_index[10] = unsorted_index[20]
self.df_unsorted = DataFrame(index=unsorted_index, data={"a": 1})
self.df_sort = DataFrame(index=index, data={"a": 1})
def time_loc_unsorted(self):
self.df_unsorted.loc["2016-6-11"]
def time_loc_sorted(self):
self.df_sort.loc["2016-6-11"]
| SortedAndUnsortedDatetimeIndexLoc |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/text_area_unfocus.py | {
"start": 153,
"end": 433
} | class ____(App):
AUTO_FOCUS = None
def compose(self) -> ComposeResult:
text_area = TextArea.code_editor()
text_area.cursor_blink = False
yield text_area
app = TextAreaUnfocusSnapshot()
if __name__ == "__main__":
app.run()
| TextAreaUnfocusSnapshot |
python | huggingface__transformers | src/transformers/models/gpt_neox_japanese/modeling_gpt_neox_japanese.py | {
"start": 1600,
"end": 2258
} | class ____(PreTrainedModel):
config: GPTNeoXJapaneseConfig
base_model_prefix = "gpt_neox_japanese"
_no_split_modules = ["GPTNeoXJapaneseLayer"]
_skip_keys_device_placement = "past_key_values"
_can_compile_fullgraph = True
@torch.no_grad()
def _init_weights(self, module):
"""Initialize the weights"""
super()._init_weights(module)
if isinstance(module, GPTNeoXJapaneseAttention):
if module.dense_bias is not None:
init.zeros_(module.dense_bias)
# Copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->GPTNeoXJapanese
| GPTNeoXJapanesePreTrainedModel |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/core_tests/runtime_types_tests/test_types.py | {
"start": 7443,
"end": 20490
} | class ____(Exception):
# Made to make exception explicit so that we aren't accidentally masking other Exceptions
pass
def _always_fails(_, _value):
raise AlwaysFailsException("kdjfkjd")
ThrowsExceptionType = dg.DagsterType(
name="ThrowsExceptionType",
type_check_fn=_always_fails,
)
def _return_bad_value(_, _value):
return "foo"
BadType = dg.DagsterType(name="BadType", type_check_fn=_return_bad_value) # pyright: ignore[reportArgumentType]
def test_input_type_returns_wrong_thing():
@dg.op
def return_one():
return 1
@dg.op(ins={"value": dg.In(BadType)})
def take_bad_thing(value):
return value
@dg.job
def pipe():
take_bad_thing(return_one())
with pytest.raises(
dg.DagsterInvariantViolationError,
match=re.escape("You have returned 'foo' of type <")
+ "(class|type)"
+ re.escape(
" 'str'> from the type check function of type \"BadType\". Return value must be"
" instance of TypeCheck or a bool."
),
):
pipe.execute_in_process()
result = execute_no_throw(pipe)
assert not result.success
failure_event = [
event
for event in result.events_for_node("take_bad_thing")
if event.event_type == DagsterEventType.STEP_FAILURE
].pop()
assert failure_event.step_failure_data.error.cls_name == "DagsterInvariantViolationError" # pyright: ignore[reportOptionalMemberAccess]
def test_output_type_returns_wrong_thing():
@dg.op(out=dg.Out(BadType))
def return_one_bad_thing():
return 1
@dg.job
def pipe():
return_one_bad_thing()
with pytest.raises(dg.DagsterInvariantViolationError):
pipe.execute_in_process()
result = execute_no_throw(pipe)
assert not result.success
failure_event = [
event
for event in result.events_for_node("return_one_bad_thing")
if event.event_type == DagsterEventType.STEP_FAILURE
].pop()
assert failure_event.step_failure_data.error.cls_name == "DagsterInvariantViolationError" # pyright: ignore[reportOptionalMemberAccess]
def test_input_type_throw_arbitrary_exception():
@dg.op
def return_one():
return 1
@dg.op(ins={"value": dg.In(ThrowsExceptionType)})
def take_throws(value):
return value
@dg.job
def pipe():
take_throws(return_one())
with pytest.raises(AlwaysFailsException):
pipe.execute_in_process()
result = execute_no_throw(pipe)
assert not result.success
failure_event = [
event
for event in result.events_for_node("take_throws")
if event.event_type == DagsterEventType.STEP_FAILURE
].pop()
assert failure_event.step_failure_data.error.cause.cls_name == "AlwaysFailsException" # pyright: ignore[reportOptionalMemberAccess]
def test_output_type_throw_arbitrary_exception():
@dg.op(out=dg.Out(ThrowsExceptionType))
def return_one_throws():
return 1
@dg.job
def pipe():
return_one_throws()
with pytest.raises(AlwaysFailsException):
pipe.execute_in_process()
result = execute_no_throw(pipe)
assert not result.success
failure_event = [
event
for event in result.events_for_node("return_one_throws")
if event.event_type == DagsterEventType.STEP_FAILURE
].pop()
assert failure_event.step_failure_data.error.cause.cls_name == "AlwaysFailsException" # pyright: ignore[reportOptionalMemberAccess]
assert "kdjfkjd" in failure_event.step_failure_data.error.cause.message # pyright: ignore[reportOptionalMemberAccess]
def define_custom_dict(name, permitted_key_names):
def type_check_method(_, value):
if not isinstance(value, dict):
return dg.TypeCheck(
False,
description=f"Value {value} should be of type {name}.",
)
for key in value:
if key not in permitted_key_names:
return dg.TypeCheck(
False,
description=(
f"Key {value.name} is not a permitted value, values can only be of: {permitted_key_names}" # pyright: ignore[reportAttributeAccessIssue]
),
)
return dg.TypeCheck(
True,
metadata={
"row_count": MetadataValue.text(str(len(value))),
"series_names": MetadataValue.text(", ".join(value.keys())),
},
)
return dg.DagsterType(key=name, name=name, type_check_fn=type_check_method)
def test_fan_in_custom_types_with_storage():
CustomDict = define_custom_dict("CustomDict", ["foo", "bar"])
@dg.op(out=dg.Out(CustomDict))
def return_dict_1(_context):
return {"foo": 3}
@dg.op(out=dg.Out(CustomDict))
def return_dict_2(_context):
return {"bar": "zip"}
@dg.op(ins={"dicts": dg.In(dg.List[CustomDict])})
def get_foo(_context, dicts):
return dicts[0]["foo"]
@dg.job(resource_defs={"io_manager": dg.fs_io_manager})
def dict_job():
# Fan-in
get_foo([return_dict_1(), return_dict_2()])
result = dict_job.execute_in_process()
assert result.success
ReturnBoolType = dg.DagsterType(name="ReturnBoolType", type_check_fn=lambda _, _val: True)
def test_return_bool_type():
@dg.op(out=dg.Out(ReturnBoolType))
def return_always_pass_bool_type(_):
return 1
@dg.job
def bool_type_job():
return_always_pass_bool_type()
assert bool_type_job.execute_in_process().success
def test_raise_on_error_type_check_returns_false():
FalsyType = dg.DagsterType(name="FalsyType", type_check_fn=lambda _, _val: False)
@dg.op(out=dg.Out(FalsyType))
def foo_op(_):
return 1
@dg.job
def foo_job():
foo_op()
with pytest.raises(dg.DagsterTypeCheckDidNotPass):
foo_job.execute_in_process()
result = foo_job.execute_in_process(raise_on_error=False)
assert not result.success
assert [event.event_type_value for event in result.all_node_events] == [
DagsterEventType.STEP_START.value,
DagsterEventType.STEP_OUTPUT.value,
DagsterEventType.STEP_FAILURE.value,
]
for event in result.all_node_events:
if event.event_type_value == DagsterEventType.STEP_FAILURE.value:
assert event.event_specific_data.error.cls_name == "DagsterTypeCheckDidNotPass" # pyright: ignore[reportOptionalMemberAccess,reportAttributeAccessIssue]
def test_raise_on_error_true_type_check_returns_unsuccessful_type_check():
FalsyType = dg.DagsterType(
name="FalsyType",
type_check_fn=lambda _, _val: dg.TypeCheck(success=False, metadata={"bar": "foo"}),
)
@dg.op(out=dg.Out(FalsyType))
def foo_op(_):
return 1
@dg.job
def foo_job():
foo_op()
with pytest.raises(dg.DagsterTypeCheckDidNotPass) as e:
foo_job.execute_in_process()
assert "bar" in e.value.metadata
assert e.value.metadata["bar"].text == "foo"
assert isinstance(e.value.dagster_type, dg.DagsterType)
result = foo_job.execute_in_process(raise_on_error=False)
assert not result.success
assert [event.event_type_value for event in result.all_node_events] == [
DagsterEventType.STEP_START.value,
DagsterEventType.STEP_OUTPUT.value,
DagsterEventType.STEP_FAILURE.value,
]
for event in result.all_node_events:
if event.event_type_value == DagsterEventType.STEP_FAILURE.value:
assert event.event_specific_data.error.cls_name == "DagsterTypeCheckDidNotPass" # pyright: ignore[reportOptionalMemberAccess,reportAttributeAccessIssue]
def test_raise_on_error_true_type_check_raises_exception():
def raise_exception_inner(_context, _):
raise dg.Failure("I am dissapoint")
ThrowExceptionType = dg.DagsterType(
name="ThrowExceptionType", type_check_fn=raise_exception_inner
)
@dg.op(out=dg.Out(ThrowExceptionType))
def foo_op(_):
return 1
@dg.job
def foo_job():
foo_op()
with pytest.raises(dg.Failure, match=re.escape("I am dissapoint")):
foo_job.execute_in_process()
result = foo_job.execute_in_process(raise_on_error=False)
assert not result.success
assert [event.event_type_value for event in result.all_node_events] == [
DagsterEventType.STEP_START.value,
DagsterEventType.STEP_FAILURE.value,
]
for event in result.all_node_events:
if event.event_type_value == DagsterEventType.STEP_FAILURE.value:
assert event.event_specific_data.error.cause.cls_name == "Failure" # pyright: ignore[reportOptionalMemberAccess,reportAttributeAccessIssue]
def test_raise_on_error_true_type_check_returns_true():
TruthyExceptionType = dg.DagsterType(
name="TruthyExceptionType", type_check_fn=lambda _, _val: True
)
@dg.op(out=dg.Out(TruthyExceptionType))
def foo_op(_):
return 1
@dg.job
def foo_job():
foo_op()
assert foo_job.execute_in_process().success
result = foo_job.execute_in_process(raise_on_error=False)
assert result.success
assert set(
[
DagsterEventType.STEP_START.value,
DagsterEventType.STEP_OUTPUT.value,
DagsterEventType.STEP_SUCCESS.value,
]
).issubset([event.event_type_value for event in result.all_node_events])
def test_raise_on_error_true_type_check_returns_successful_type_check():
TruthyExceptionType = dg.DagsterType(
name="TruthyExceptionType",
type_check_fn=lambda _, _val: dg.TypeCheck(success=True, metadata={"bar": "foo"}),
)
@dg.op(out=dg.Out(TruthyExceptionType))
def foo_op(_):
return 1
@dg.job
def foo_job():
foo_op()
result = foo_job.execute_in_process()
assert result.success
for event in result.all_node_events:
if event.event_type_value == DagsterEventType.STEP_OUTPUT.value:
assert event.event_specific_data.type_check_data # pyright: ignore[reportOptionalMemberAccess,reportAttributeAccessIssue]
assert event.event_specific_data.type_check_data.metadata["bar"].text == "foo" # pyright: ignore[reportOptionalMemberAccess,reportAttributeAccessIssue]
result = foo_job.execute_in_process(raise_on_error=False)
assert result.success
assert set(
[
DagsterEventType.STEP_START.value,
DagsterEventType.STEP_OUTPUT.value,
DagsterEventType.STEP_SUCCESS.value,
]
).issubset([event.event_type_value for event in result.all_node_events])
def test_contextual_type_check():
def fancy_type_check(context, value):
return dg.TypeCheck(success=context.resources.foo.check(value))
custom = dg.DagsterType(
key="custom",
name="custom",
type_check_fn=fancy_type_check,
required_resource_keys={"foo"},
)
@dg.resource
def foo(_context):
class _Foo:
def check(self, _value):
return True
return _Foo()
@dg.op
def return_one():
return 1
@dg.op(ins={"inp": dg.In(custom)})
def bar(_context, inp):
return inp
@dg.job(resource_defs={"foo": foo})
def fancy_job():
bar(return_one())
assert fancy_job.execute_in_process().success
def test_type_equality():
assert resolve_dagster_type(int) == resolve_dagster_type(int)
assert not (resolve_dagster_type(int) != resolve_dagster_type(int))
assert resolve_dagster_type(dg.List[int]) == resolve_dagster_type(dg.List[int])
assert not (resolve_dagster_type(dg.List[int]) != resolve_dagster_type(dg.List[int]))
assert resolve_dagster_type(dg.Optional[dg.List[int]]) == resolve_dagster_type(
dg.Optional[dg.List[int]]
)
assert not (
resolve_dagster_type(dg.Optional[dg.List[int]])
!= resolve_dagster_type(dg.Optional[dg.List[int]])
)
def test_make_usable_as_dagster_type_called_twice():
class AType:
pass
ADagsterType = dg.PythonObjectDagsterType(
AType,
name="ADagsterType",
)
BDagsterType = dg.PythonObjectDagsterType(
AType,
name="BDagsterType",
)
dg.make_python_type_usable_as_dagster_type(AType, ADagsterType)
dg.make_python_type_usable_as_dagster_type(AType, ADagsterType) # should not raise an error
with pytest.raises(dg.DagsterInvalidDefinitionError):
dg.make_python_type_usable_as_dagster_type(AType, BDagsterType)
def test_tuple_inner_types_not_mutable():
tuple_type = dg.Tuple[dg.List[dg.String]]
inner_types_1st_call = list(tuple_type.inner_types)
inner_types = list(tuple_type.inner_types)
assert inner_types_1st_call == inner_types, "inner types mutated on subsequent calls"
assert isinstance(inner_types[0], ListType)
assert inner_types[0].inner_type == inner_types[1]
assert len(inner_types) == 2
| AlwaysFailsException |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/sparse_ops/sparse_xent_op_test_base.py | {
"start": 1434,
"end": 13207
} | class ____(test.TestCase):
def _opFwdBwd(self, labels, logits):
"""Runs the op-under-test both forwards and backwards"""
logits = ops_lib.convert_to_tensor(logits) # needed for the gradient tape
with backprop_lib.GradientTape() as tape:
tape.watch(logits)
loss = nn_ops.sparse_softmax_cross_entropy_with_logits_v2(
labels=labels, logits=logits)
return loss, tape.gradient(loss, logits)
def _npXent(self, labels, logits):
logits = np.reshape(logits, [-1, logits.shape[-1]])
labels = np.reshape(labels, [-1])
batch_dim = 0
class_dim = 1
batch_size = logits.shape[batch_dim]
e = np.exp(logits -
np.reshape(np.amax(logits, axis=class_dim), [batch_size, 1]))
probs = e / np.reshape(np.sum(e, axis=class_dim), [batch_size, 1])
labels_mat = np.zeros_like(probs).astype(probs.dtype)
labels_mat[np.arange(batch_size), labels] = 1.0
gradient = (probs - labels_mat)
loss = -np.sum(labels_mat * np.log(probs + 1.0e-20), axis=1)
return loss, gradient
def _testXent(self, np_labels, np_logits):
np_loss, np_gradient = self._npXent(labels=np_labels, logits=np_logits)
tf_loss, tf_gradient = self._opFwdBwd(labels=np_labels, logits=np_logits)
self.assertAllCloseAccordingToType(np_loss, tf_loss)
self.assertAllCloseAccordingToType(np_gradient, tf_gradient)
def testSingleClass(self):
for label_dtype in np.int32, np.int64:
tf_loss, tf_gradient = self._opFwdBwd(
labels=np.array([0, 0, 0]).astype(label_dtype),
logits=np.array([[1.], [-1.], [0.]]).astype(np.float32))
self.assertAllClose([0.0, 0.0, 0.0], tf_loss)
self.assertAllClose([[0.0], [0.0], [0.0]], tf_gradient)
@test_util.run_gpu_only
def _testInvalidLabelGPU(self, invalid_label_gradient=np.nan):
labels = [4, 3, 0, -1]
logits = [[1., 1., 1., 1.], [1., 1., 1., 1.], [1., 2., 3., 4.],
[1., 2., 3., 4.]]
loss, gradient = self._opFwdBwd(labels=labels, logits=logits)
self.assertAllClose([np.nan, 1.3862, 3.4420, np.nan],
loss,
rtol=1e-3,
atol=1e-3)
self.assertAllClose(
[[invalid_label_gradient] * 4, [0.25, 0.25, 0.25, -0.75],
[-0.968, 0.087, 0.237, 0.6439], [invalid_label_gradient] * 4],
gradient,
rtol=1e-3,
atol=1e-3)
def testInvalidLabelGPU(self):
"""This method is structured to be easily overridden by a child class."""
self._testInvalidLabelGPU()
@test_util.run_in_graph_and_eager_modes(use_gpu=False)
@test_util.disable_xla("XLA cannot assert inside of a kernel.")
def _testInvalidLabelCPU(self, expected_regex="Received a label value of"):
labels = [4, 3, 0, -1]
logits = [[1., 1., 1., 1.], [1., 1., 1., 1.], [1., 2., 3., 4.],
[1., 2., 3., 4.]]
with self.assertRaisesRegex(
(errors_impl.InvalidArgumentError, errors_impl.UnknownError),
expected_regex):
self.evaluate(
nn_ops.sparse_softmax_cross_entropy_with_logits_v2(
labels=labels, logits=logits))
def testInvalidLabelCPU(self):
"""This method is structured to be easily overridden by a child class."""
self._testInvalidLabelCPU()
def testNpXent(self):
# We create 2 batches of logits for testing.
# batch 0 is the boring uniform distribution: 1, 1, 1, 1, with target 3.
# batch 1 has a bit of difference: 1, 2, 3, 4, with target 0.
labels = [3, 0]
logits = [[1., 1., 1., 1.], [1., 2., 3., 4.]]
# For batch 0, we expect the uniform distribution: 0.25, 0.25, 0.25, 0.25
# With a hard target 3, the gradient is [0.25, 0.25, 0.25, -0.75]
# The loss for this batch is -log(0.25) = 1.386
#
# For batch 1, we have:
# exp(0) = 1
# exp(1) = 2.718
# exp(2) = 7.389
# exp(3) = 20.085
# SUM = 31.192
# So we have as probabilities:
# exp(0) / SUM = 0.032
# exp(1) / SUM = 0.087
# exp(2) / SUM = 0.237
# exp(3) / SUM = 0.644
# With a hard 1, the gradient is [0.032 - 1.0 = -0.968, 0.087, 0.237, 0.644]
# The loss for this batch is [1.0 * -log(0.25), 1.0 * -log(0.032)]
# = [1.3862, 3.4420]
np_loss, np_gradient = self._npXent(
labels=np.array(labels), logits=np.array(logits))
self.assertAllClose(
np.array([[0.25, 0.25, 0.25, -0.75], [-0.968, 0.087, 0.237, 0.6439]]),
np_gradient,
rtol=1.e-3,
atol=1.e-3)
self.assertAllClose(
np.array([1.3862, 3.4420]), np_loss, rtol=1.e-3, atol=1.e-3)
def testShapeMismatch(self):
with self.assertRaisesRegex(
ValueError, "`labels.shape.rank` must equal `logits.shape.rank - 1`"):
nn_ops.sparse_softmax_cross_entropy_with_logits_v2(
labels=[[0, 2]], logits=[[0., 1.], [2., 3.], [2., 3.]])
def testScalar(self):
with self.assertRaisesRegex(ValueError, "`logits` cannot be a scalar"):
nn_ops.sparse_softmax_cross_entropy_with_logits_v2(
labels=constant_op.constant(0), logits=constant_op.constant(1.0))
def _testLabelsPlaceholderScalar(self, expected_error_message):
with ops_lib.Graph().as_default(), self.session():
labels = array_ops.placeholder(np.int32)
y = nn_ops.sparse_softmax_cross_entropy_with_logits_v2(
labels=labels, logits=[[7.]])
with self.assertRaisesOpError(expected_error_message):
y.eval(feed_dict={labels: 0})
def testLabelsPlaceholderScalar(self):
"""This method is structured to be easily overridden by a child class."""
self._testLabelsPlaceholderScalar(
expected_error_message="labels must be 1-D")
def testVector(self):
loss = nn_ops.sparse_softmax_cross_entropy_with_logits_v2(
labels=constant_op.constant(0), logits=constant_op.constant([1.0]))
self.assertAllClose(0.0, loss)
def testFloat(self):
for label_dtype in np.int32, np.int64:
self._testXent(
np_labels=np.array([3, 0]).astype(label_dtype),
np_logits=np.array([[1., 1., 1., 1.], [1., 2., 3.,
4.]]).astype(np.float32))
def testDouble(self):
for label_dtype in np.int32, np.int64:
self._testXent(
np_labels=np.array([0, 3]).astype(label_dtype),
np_logits=np.array([[1., 1., 1., 1.], [1., 2., 3.,
4.]]).astype(np.float64))
def testHalf(self):
for label_dtype in np.int32, np.int64:
self._testXent(
np_labels=np.array([3, 0]).astype(label_dtype),
np_logits=np.array([[1., 1., 1., 1.], [1., 2., 3.,
4.]]).astype(np.float16))
def testBfloat16(self):
for label_dtype in np.int32, np.int64:
self._testXent(
np_labels=np.array([3, 0]).astype(label_dtype),
np_logits=np.array([[1., 1., 1., 1.],
[1., 2., 3.,
4.]]).astype(dtypes.bfloat16.as_numpy_dtype))
def testEmpty(self):
self._testXent(
np_labels=np.zeros((0,), dtype=np.int32), np_logits=np.zeros((0, 3)))
@test_util.run_in_graph_and_eager_modes()
def testGradient(self):
with self.session() as sess:
labels = constant_op.constant([3, 0, 1], name="labels")
logits = constant_op.constant(
[0.1, 0.2, 0.3, 0.4, 0.1, 0.4, 0.9, 1.6, 0.1, 0.8, 2.7, 6.4],
shape=[3, 4],
dtype=dtypes.float64,
name="logits")
def xent(logits):
# gradient_checker_v2.computee_gradient doesn't take int32/int64.
# labels must be of type int32/int64, so passing them separately here.
return nn_ops.sparse_softmax_cross_entropy_with_logits_v2(
labels=labels, logits=logits, name="xent")
analytical, numerical = gradient_checker_v2.compute_gradient(
xent, [logits])
if not context.executing_eagerly():
# Check that no extra computation performed. When only first derivative
# is requested, second derivative must not be computed. So when there is
# no second derivative, there is no `BatchMatMul` op in the graph.
op_names = [
op.op_def.name for op in sess.graph.get_operations() if op.op_def
]
self.assertNotIn("BatchMatMul", op_names)
self.assertNotIn("BatchMatMulV2", op_names)
tol = 5e-8
self.assertAllClose(analytical, numerical, atol=tol, rtol=tol)
@test_util.run_in_graph_and_eager_modes()
def testSecondGradient(self):
with self.session() as sess:
labels = constant_op.constant([3, 0, 1], name="labels")
logits = constant_op.constant(
[0.3, 0.4, 0.1, 1.2, 0.1, 1.9, 0.1, 0.7, 0.8, 0.2, 1.3, 1.3],
shape=[3, 4],
dtype=dtypes.float64,
name="logits")
def xent_grad(logits):
with backprop_lib.GradientTape() as tape:
tape.watch(logits)
return tape.gradient(
nn_ops.sparse_softmax_cross_entropy_with_logits_v2(
labels=labels, logits=logits, name="xent"), [logits])[0]
analytical, numerical = gradient_checker_v2.compute_gradient(
xent_grad, [logits])
if (not context.executing_eagerly() and
not config.is_op_determinism_enabled()):
# Check that second derivative is calculated.
# (it is equivalent to being `BatchMatMul` op in the graph because of
# implementation of xentropy grad)
op_names = [
op.op_def.name for op in sess.graph.get_operations() if op.op_def
]
self.assertIn("BatchMatMulV2", op_names)
tol = 5e-8
self.assertAllClose(analytical, numerical, atol=tol, rtol=tol)
@test_util.run_in_graph_and_eager_modes()
def _testHighDim(self, labels, logits):
np_loss, np_gradient = self._npXent(
labels=np.array(labels), logits=np.array(logits))
# manually reshape loss
np_loss = np.reshape(np_loss, np.array(labels).shape)
tf_loss = nn_ops.sparse_softmax_cross_entropy_with_logits_v2(
labels=labels, logits=logits)
with backprop_lib.GradientTape() as tape:
logits = constant_op.constant(logits)
tape.watch(logits)
tf_gradient = tape.gradient(
nn_ops.sparse_softmax_cross_entropy_with_logits_v2(
labels=labels, logits=logits), [logits])[0]
tf_gradient = array_ops.reshape(tf_gradient, np_gradient.shape)
self.assertAllCloseAccordingToType(np_loss, tf_loss)
self.assertAllCloseAccordingToType(np_gradient, tf_gradient)
def testHighDim(self):
labels = [[3], [0]]
logits = [[[1., 1., 1., 1.]], [[1., 2., 3., 4.]]]
self._testHighDim(labels, logits)
def testHighDim2(self):
labels = [[3, 2], [0, 3]]
logits = [[[1., 1., 1., 1.], [2., 2., 2., 2.]],
[[1., 2., 3., 4.], [5., 6., 7., 8.]]]
self._testHighDim(labels, logits)
def _testScalarHandling(self, expected_regex):
with ops_lib.Graph().as_default(), self.session(use_gpu=False) as sess:
with self.assertRaisesRegex(errors_impl.InvalidArgumentError,
expected_regex):
labels = array_ops.placeholder(dtypes.int32, shape=[None, 1])
logits = array_ops.placeholder(dtypes.float32, shape=[None, 3])
ce = nn_ops.sparse_softmax_cross_entropy_with_logits_v2(
labels=array_ops.squeeze(labels), logits=logits)
labels_v2 = np.zeros((1, 1), dtype=np.int32)
logits_v2 = np.random.randn(1, 3)
sess.run([ce], feed_dict={labels: labels_v2, logits: logits_v2})
def testScalarHandling(self):
"""This method is structured to be easily overridden by a child class."""
self._testScalarHandling(expected_regex=".*labels must be 1-D.*")
| SparseXentOpTestBase |
python | walkccc__LeetCode | solutions/3193. Count the Number of Inversions/3193.py | {
"start": 0,
"end": 893
} | class ____:
def numberOfPermutations(self, n: int, requirements: list[list[int]]) -> int:
MOD = 1_000_000_007
MAX_INVERSIONS = 400
# dp[i][j] := the number of ways to arrange the first i numbers of the
# permutation s.t. there are j inversions
dp = [[0] * (MAX_INVERSIONS + 1) for _ in range(n + 1)]
endToCnt = {end + 1: cnt for end, cnt in requirements}
# There's only one way to arrange a single number with zero inversions.
dp[1][0] = 1
for i in range(2, n + 1):
for newInversions in range(i):
for j in range(MAX_INVERSIONS - newInversions + 1):
inversionsAfterInsertion = j + newInversions
if i in endToCnt and inversionsAfterInsertion != endToCnt[i]:
continue
dp[i][inversionsAfterInsertion] += dp[i - 1][j]
dp[i][inversionsAfterInsertion] %= MOD
return dp[n][endToCnt[n]]
| Solution |
python | celery__celery | t/unit/utils/test_platforms.py | {
"start": 3473,
"end": 5224
} | class ____:
@patch('signal.getsignal')
def test_getitem(self, getsignal):
signals['SIGINT']
getsignal.assert_called_with(signal.SIGINT)
def test_supported(self):
assert signals.supported('INT')
assert not signals.supported('SIGIMAGINARY')
@t.skip.if_win32
def test_reset_alarm(self):
with patch('signal.alarm') as _alarm:
signals.reset_alarm()
_alarm.assert_called_with(0)
def test_arm_alarm(self):
if hasattr(signal, 'setitimer'):
with patch('signal.setitimer', create=True) as seti:
signals.arm_alarm(30)
seti.assert_called()
def test_signum(self):
assert signals.signum(13) == 13
assert signals.signum('INT') == signal.SIGINT
assert signals.signum('SIGINT') == signal.SIGINT
with pytest.raises(TypeError):
signals.signum('int')
signals.signum(object())
@patch('signal.signal')
def test_ignore(self, set):
signals.ignore('SIGINT')
set.assert_called_with(signals.signum('INT'), signals.ignored)
signals.ignore('SIGTERM')
set.assert_called_with(signals.signum('TERM'), signals.ignored)
@patch('signal.signal')
def test_reset(self, set):
signals.reset('SIGINT')
set.assert_called_with(signals.signum('INT'), signals.default)
@patch('signal.signal')
def test_setitem(self, set):
def handle(*args):
return args
signals['INT'] = handle
set.assert_called_with(signal.SIGINT, handle)
@patch('signal.signal')
def test_setitem_raises(self, set):
set.side_effect = ValueError()
signals['INT'] = lambda *a: a
| test_Signals |
python | huggingface__transformers | tests/models/ibert/test_modeling_ibert.py | {
"start": 15016,
"end": 31207
} | class ____(unittest.TestCase):
def test_quant_embedding(self):
weight_bit = 8
embedding = QuantEmbedding(2, 4, quant_mode=True, weight_bit=weight_bit)
embedding_weight = torch.tensor([[-1.0, -2.0, -3.0, -4.0], [5.0, 6.0, 7.0, 8.0]])
embedding.weight = nn.Parameter(embedding_weight)
expected_scaling_factor = embedding_weight.abs().max() / (2 ** (weight_bit - 1) - 1)
x, x_scaling_factor = embedding(torch.tensor(0))
y, y_scaling_factor = embedding(torch.tensor(1))
# scaling factor should follow the symmetric quantization rule
self.assertTrue(torch.allclose(x_scaling_factor, expected_scaling_factor, atol=1e-4))
self.assertTrue(torch.allclose(x_scaling_factor, expected_scaling_factor, atol=1e-4))
self.assertTrue(torch.allclose(y_scaling_factor, expected_scaling_factor, atol=1e-4))
# quantization error should not exceed the scaling factor
self.assertTrue(torch.allclose(x, embedding_weight[0], atol=expected_scaling_factor))
self.assertTrue(torch.allclose(y, embedding_weight[1], atol=expected_scaling_factor))
def test_quant_act(self):
def _test_range():
act = QuantAct(activation_bit, act_range_momentum, quant_mode=True)
# First pass
x = torch.tensor([[-1.0, -2.0, -3.0, -4.0], [5.0, 6.0, 7.0, 8.0]])
x_scaling_factor = torch.tensor(1.0)
y, y_scaling_factor = act(x, x_scaling_factor)
y_int = y / y_scaling_factor
# After the first pass, x_min and x_max should be initialized with x.min() and x.max()
expected_x_min, expected_x_max = x.min(), x.max()
self.assertTrue(torch.allclose(act.x_min, expected_x_min, atol=1e-4))
self.assertTrue(torch.allclose(act.x_max, expected_x_max, atol=1e-4))
# scaling factor should follow the symmetric quantization rule
expected_range = torch.max(expected_x_min.abs(), expected_x_max.abs())
expected_scaling_factor = expected_range / (2 ** (activation_bit - 1) - 1)
self.assertTrue(torch.allclose(y_scaling_factor, expected_scaling_factor, atol=1e-4))
# quantization error should not exceed the scaling factor
self.assertTrue(torch.allclose(x, y, atol=expected_scaling_factor))
# output should be integer
self.assertTrue(torch.allclose(y_int, y_int.round(), atol=1e-4))
# Second Pass
x = torch.tensor([[-1.0, -2.0, -3.0, -4.0], [5.0, 6.0, 7.0, 8.0]]) * 2
x_scaling_factor = torch.tensor(1.0)
y, y_scaling_factor = act(x, x_scaling_factor)
y_int = y / y_scaling_factor
# From the second pass, x_min and x_max should be updated with moving average
expected_x_min = expected_x_min * act_range_momentum + x.min() * (1 - act_range_momentum)
expected_x_max = expected_x_max * act_range_momentum + x.max() * (1 - act_range_momentum)
self.assertTrue(torch.allclose(act.x_min, expected_x_min, atol=1e-4))
self.assertTrue(torch.allclose(act.x_max, expected_x_max, atol=1e-4))
# scaling factor should follow the symmetric quantization rule
expected_range = torch.max(expected_x_min.abs(), expected_x_max.abs())
expected_scaling_factor = expected_range / (2 ** (activation_bit - 1) - 1)
self.assertTrue(torch.allclose(y_scaling_factor, expected_scaling_factor, atol=1e-4))
# quantization error should not exceed the scaling factor
x = x.clamp(min=-expected_range, max=expected_range)
self.assertTrue(torch.allclose(x, y, atol=expected_scaling_factor))
# output should be integer
self.assertTrue(torch.allclose(y_int, y_int.round(), atol=1e-4))
# Third pass, with eval()
act.eval()
x = torch.tensor([[-1.0, -2.0, -3.0, -4.0], [5.0, 6.0, 7.0, 8.0]]) * 3
# In eval mode, min/max and scaling factor must be fixed
self.assertTrue(torch.allclose(act.x_min, expected_x_min, atol=1e-4))
self.assertTrue(torch.allclose(act.x_max, expected_x_max, atol=1e-4))
self.assertTrue(torch.allclose(y_scaling_factor, expected_scaling_factor, atol=1e-4))
def _test_identity():
# test if identity and identity_scaling_factor are given
# should add the input values
act = QuantAct(activation_bit, act_range_momentum, quant_mode=True)
x = torch.tensor([[-1.0, -2.0, -3.0, -4.0], [5.0, 6.0, 7.0, 8.0]])
y = torch.tensor([[6.0, -7.0, 1.0, -2.0], [3.0, -4.0, -8.0, 5.0]])
x_scaling_factor = torch.tensor(1.0)
y_scaling_factor = torch.tensor(0.5)
z, z_scaling_factor = act(x, x_scaling_factor, y, y_scaling_factor)
z_int = z / z_scaling_factor
self.assertTrue(torch.allclose(x + y, z, atol=0.1))
self.assertTrue(torch.allclose(z_int, z_int.round(), atol=1e-4))
activation_bit = 8
act_range_momentum = 0.95
_test_range()
_test_identity()
def test_quant_linear(self):
def _test(per_channel):
linear_q = QuantLinear(2, 4, quant_mode=True, per_channel=per_channel, weight_bit=weight_bit)
linear_dq = QuantLinear(2, 4, quant_mode=False, per_channel=per_channel, weight_bit=weight_bit)
linear_weight = torch.tensor([[-1.0, 2.0, 3.0, -4.0], [5.0, -6.0, -7.0, 8.0]]).T
linear_q.weight = nn.Parameter(linear_weight)
linear_dq.weight = nn.Parameter(linear_weight)
q, q_scaling_factor = linear_q(x, x_scaling_factor)
q_int = q / q_scaling_factor
dq, dq_scaling_factor = linear_dq(x, x_scaling_factor)
if per_channel:
q_max = linear_weight.abs().max(dim=1).values
else:
q_max = linear_weight.abs().max()
expected_scaling_factor = q_max / (2 ** (weight_bit - 1) - 1)
# scaling factor should follow the symmetric quantization rule
self.assertTrue(torch.allclose(linear_q.fc_scaling_factor, expected_scaling_factor, atol=1e-4))
# output of the normal linear layer and the quantized linear layer should be similar
self.assertTrue(torch.allclose(q, dq, atol=0.5))
# output of the quantized linear layer should be integer
self.assertTrue(torch.allclose(q_int, q_int.round(), atol=1e-4))
weight_bit = 8
x = torch.tensor([[2.0, -5.0], [-3.0, 4.0]])
x_scaling_factor = torch.tensor([1.0])
_test(True)
_test(False)
def test_int_gelu(self):
gelu_q = IntGELU(quant_mode=True)
gelu_dq = nn.GELU()
x_int = torch.arange(-10000, 10001, 1)
x_scaling_factor = torch.tensor(0.001)
x = x_int * x_scaling_factor
q, q_scaling_factor = gelu_q(x, x_scaling_factor)
q_int = q / q_scaling_factor
dq = gelu_dq(x)
# output of the normal GELU and the quantized GELU should be similar
self.assertTrue(torch.allclose(q, dq, atol=0.5))
# output of the quantized GELU layer should be integer
self.assertTrue(torch.allclose(q_int, q_int.round(), atol=1e-4))
def test_force_dequant_gelu(self):
x_int = torch.arange(-10000, 10001, 1)
x_scaling_factor = torch.tensor(0.001)
x = x_int * x_scaling_factor
gelu_dq = IntGELU(quant_mode=False)
gelu_fdqs_dict = {
True: [
IntGELU(quant_mode=True, force_dequant="nonlinear"),
IntGELU(quant_mode=True, force_dequant="gelu"),
],
False: [
IntGELU(quant_mode=True, force_dequant="none"),
IntGELU(quant_mode=True, force_dequant="softmax"),
IntGELU(quant_mode=True, force_dequant="layernorm"),
],
}
dq, dq_scaling_factor = gelu_dq(x, x_scaling_factor)
for label, gelu_fdqs in gelu_fdqs_dict.items():
for gelu_fdq in gelu_fdqs:
q, q_scaling_factor = gelu_fdq(x, x_scaling_factor)
if label:
self.assertTrue(torch.allclose(q, dq, atol=1e-4))
else:
self.assertFalse(torch.allclose(q, dq, atol=1e-4))
def test_int_softmax(self):
output_bit = 8
softmax_q = IntSoftmax(output_bit, quant_mode=True)
softmax_dq = nn.Softmax()
def _test(array):
x_int = torch.tensor(array)
x_scaling_factor = torch.tensor(0.1)
x = x_int * x_scaling_factor
q, q_scaling_factor = softmax_q(x, x_scaling_factor)
q_int = q / q_scaling_factor
dq = softmax_dq(x)
# output of the normal Softmax and the quantized Softmax should be similar
self.assertTrue(torch.allclose(q, dq, atol=0.5))
# output of the quantized GELU layer should be integer
self.assertTrue(torch.allclose(q_int, q_int.round(), atol=1e-4))
# Output of the quantize Softmax should not exceed the output_bit
self.assertTrue(q.abs().max() < 2**output_bit)
array = [[i + j for j in range(10)] for i in range(-10, 10)]
_test(array)
array = [[i + j for j in range(50)] for i in range(-10, 10)]
_test(array)
array = [[i + 100 * j for j in range(2)] for i in range(-10, 10)]
_test(array)
def test_force_dequant_softmax(self):
output_bit = 8
array = [[i + j for j in range(10)] for i in range(-10, 10)]
x_int = torch.tensor(array)
x_scaling_factor = torch.tensor(0.1)
x = x_int * x_scaling_factor
softmax_dq = IntSoftmax(output_bit, quant_mode=False)
softmax_fdqs_dict = {
True: [
IntSoftmax(output_bit, quant_mode=True, force_dequant="nonlinear"),
IntSoftmax(output_bit, quant_mode=True, force_dequant="softmax"),
],
False: [
IntSoftmax(output_bit, quant_mode=True, force_dequant="none"),
IntSoftmax(output_bit, quant_mode=True, force_dequant="gelu"),
IntSoftmax(output_bit, quant_mode=True, force_dequant="layernorm"),
],
}
dq, dq_scaling_factor = softmax_dq(x, x_scaling_factor)
for label, softmax_fdqs in softmax_fdqs_dict.items():
for softmax_fdq in softmax_fdqs:
q, q_scaling_factor = softmax_fdq(x, x_scaling_factor)
if label:
self.assertTrue(torch.allclose(q, dq, atol=1e-4))
else:
self.assertFalse(torch.allclose(q, dq, atol=1e-4))
def test_int_layernorm(self):
output_bit = 8
# some random matrix
array = [[[i * j * j + j for j in range(5, 15)]] for i in range(-10, 10)]
x_int = torch.tensor(array)
x_scaling_factor = torch.tensor(0.1)
x = x_int * x_scaling_factor
ln_q = IntLayerNorm(x.shape[1:], 1e-5, quant_mode=True, output_bit=output_bit)
ln_dq = nn.LayerNorm(x.shape[1:], 1e-5)
ln_q.weight = nn.Parameter(torch.ones(x.shape[1:]))
ln_q.bias = nn.Parameter(torch.ones(x.shape[1:]))
ln_dq.weight = nn.Parameter(torch.ones(x.shape[1:]))
ln_dq.bias = nn.Parameter(torch.ones(x.shape[1:]))
q, q_scaling_factor = ln_q(x, x_scaling_factor)
q_int = q / q_scaling_factor
dq = ln_dq(x)
# output of the normal LN and the quantized LN should be similar
self.assertTrue(torch.allclose(q, dq, atol=0.5))
# output of the quantized GELU layer should be integer
self.assertTrue(torch.allclose(q_int, q_int.round(), atol=1e-4))
def test_force_dequant_layernorm(self):
output_bit = 8
array = [[[i * j * j + j for j in range(5, 15)]] for i in range(-10, 10)]
x_int = torch.tensor(array)
x_scaling_factor = torch.tensor(0.1)
x = x_int * x_scaling_factor
ln_dq = IntLayerNorm(x.shape[1:], 1e-5, quant_mode=False, output_bit=output_bit)
ln_fdqs_dict = {
True: [
IntLayerNorm(x.shape[1:], 1e-5, quant_mode=True, output_bit=output_bit, force_dequant="nonlinear"),
IntLayerNorm(x.shape[1:], 1e-5, quant_mode=True, output_bit=output_bit, force_dequant="layernorm"),
],
False: [
IntLayerNorm(x.shape[1:], 1e-5, quant_mode=True, output_bit=output_bit, force_dequant="none"),
IntLayerNorm(x.shape[1:], 1e-5, quant_mode=True, output_bit=output_bit, force_dequant="gelu"),
IntLayerNorm(x.shape[1:], 1e-5, quant_mode=True, output_bit=output_bit, force_dequant="softmax"),
],
}
ln_dq.weight = nn.Parameter(torch.ones(x.shape[1:]))
ln_dq.bias = nn.Parameter(torch.ones(x.shape[1:]))
dq, dq_scaling_factor = ln_dq(x, x_scaling_factor)
for label, ln_fdqs in ln_fdqs_dict.items():
for ln_fdq in ln_fdqs:
ln_fdq.weight = nn.Parameter(torch.ones(x.shape[1:]))
ln_fdq.bias = nn.Parameter(torch.ones(x.shape[1:]))
q, q_scaling_factor = ln_fdq(x, x_scaling_factor)
if label:
self.assertTrue(torch.allclose(q, dq, atol=1e-4))
else:
self.assertFalse(torch.allclose(q, dq, atol=1e-4))
def quantize(self, model):
# Helper function that quantizes the given model
# Recursively convert all the `quant_mode` attributes as `True`
if hasattr(model, "quant_mode"):
model.quant_mode = True
elif isinstance(model, nn.Sequential):
for n, m in model.named_children():
self.quantize(m)
elif isinstance(model, nn.ModuleList):
for n in model:
self.quantize(n)
else:
for attr in dir(model):
mod = getattr(model, attr)
if isinstance(mod, nn.Module) and mod != model:
self.quantize(mod)
@slow
def test_inference_masked_lm(self):
# I-BERT should be "equivalent" to RoBERTa if not quantized
# Test coped from `test_modeling_roberta.py`
model = IBertForMaskedLM.from_pretrained("kssteven/ibert-roberta-base")
input_ids = torch.tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]])
output = model(input_ids)[0]
expected_shape = torch.Size((1, 11, 50265))
self.assertEqual(output.shape, expected_shape)
expected_slice = torch.tensor(
[[[33.8802, -4.3103, 22.7761], [4.6539, -2.8098, 13.6253], [1.8228, -3.6898, 8.8600]]]
)
self.assertTrue(torch.allclose(output[:, :3, :3], expected_slice, atol=1e-4))
# I-BERT should be "similar" to RoBERTa if quantized
self.quantize(model)
output = model(input_ids)[0]
self.assertEqual(output.shape, expected_shape)
self.assertTrue(torch.allclose(output[:, :3, :3], expected_slice, atol=0.1))
@slow
def test_inference_classification_head(self):
# I-BERT should be "equivalent" to RoBERTa if not quantized
# Test coped from `test_modeling_roberta.py`
model = IBertForSequenceClassification.from_pretrained("kssteven/ibert-roberta-large-mnli")
input_ids = torch.tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]])
output = model(input_ids)[0]
expected_shape = torch.Size((1, 3))
self.assertEqual(output.shape, expected_shape)
expected_tensor = torch.tensor([[-0.9469, 0.3913, 0.5118]])
self.assertTrue(torch.allclose(output, expected_tensor, atol=1e-4))
# I-BERT should be "similar" to RoBERTa if quantized
self.quantize(model)
output = model(input_ids)[0]
self.assertEqual(output.shape, expected_shape)
self.assertTrue(torch.allclose(output, expected_tensor, atol=0.1))
| IBertModelIntegrationTest |
python | matplotlib__matplotlib | lib/matplotlib/tri/_triangulation.py | {
"start": 62,
"end": 9784
} | class ____:
"""
An unstructured triangular grid consisting of npoints points and
ntri triangles. The triangles can either be specified by the user
or automatically generated using a Delaunay triangulation.
Parameters
----------
x, y : (npoints,) array-like
Coordinates of grid points.
triangles : (ntri, 3) array-like of int, optional
For each triangle, the indices of the three points that make
up the triangle, ordered in an anticlockwise manner. If not
specified, the Delaunay triangulation is calculated.
mask : (ntri,) array-like of bool, optional
Which triangles are masked out.
Attributes
----------
triangles : (ntri, 3) array of int
For each triangle, the indices of the three points that make
up the triangle, ordered in an anticlockwise manner. If you want to
take the *mask* into account, use `get_masked_triangles` instead.
mask : (ntri, 3) array of bool or None
Masked out triangles.
is_delaunay : bool
Whether the Triangulation is a calculated Delaunay
triangulation (where *triangles* was not specified) or not.
Notes
-----
For a Triangulation to be valid it must not have duplicate points,
triangles formed from colinear points, or overlapping triangles.
"""
def __init__(self, x, y, triangles=None, mask=None):
from matplotlib import _qhull
self.x = np.asarray(x, dtype=np.float64)
self.y = np.asarray(y, dtype=np.float64)
if self.x.shape != self.y.shape or self.x.ndim != 1:
raise ValueError("x and y must be equal-length 1D arrays, but "
f"found shapes {self.x.shape!r} and "
f"{self.y.shape!r}")
self.mask = None
self._edges = None
self._neighbors = None
self.is_delaunay = False
if triangles is None:
# No triangulation specified, so use matplotlib._qhull to obtain
# Delaunay triangulation.
self.triangles, self._neighbors = _qhull.delaunay(x, y, sys.flags.verbose)
self.is_delaunay = True
else:
# Triangulation specified. Copy, since we may correct triangle
# orientation.
try:
self.triangles = np.array(triangles, dtype=np.int32, order='C')
except ValueError as e:
raise ValueError('triangles must be a (N, 3) int array, not '
f'{triangles!r}') from e
if self.triangles.ndim != 2 or self.triangles.shape[1] != 3:
raise ValueError(
'triangles must be a (N, 3) int array, but found shape '
f'{self.triangles.shape!r}')
if self.triangles.max() >= len(self.x):
raise ValueError(
'triangles are indices into the points and must be in the '
f'range 0 <= i < {len(self.x)} but found value '
f'{self.triangles.max()}')
if self.triangles.min() < 0:
raise ValueError(
'triangles are indices into the points and must be in the '
f'range 0 <= i < {len(self.x)} but found value '
f'{self.triangles.min()}')
# Underlying C++ object is not created until first needed.
self._cpp_triangulation = None
# Default TriFinder not created until needed.
self._trifinder = None
self.set_mask(mask)
def calculate_plane_coefficients(self, z):
"""
Calculate plane equation coefficients for all unmasked triangles from
the point (x, y) coordinates and specified z-array of shape (npoints).
The returned array has shape (npoints, 3) and allows z-value at (x, y)
position in triangle tri to be calculated using
``z = array[tri, 0] * x + array[tri, 1] * y + array[tri, 2]``.
"""
return self.get_cpp_triangulation().calculate_plane_coefficients(z)
@property
def edges(self):
"""
Return integer array of shape (nedges, 2) containing all edges of
non-masked triangles.
Each row defines an edge by its start point index and end point
index. Each edge appears only once, i.e. for an edge between points
*i* and *j*, there will only be either *(i, j)* or *(j, i)*.
"""
if self._edges is None:
self._edges = self.get_cpp_triangulation().get_edges()
return self._edges
def get_cpp_triangulation(self):
"""
Return the underlying C++ Triangulation object, creating it
if necessary.
"""
from matplotlib import _tri
if self._cpp_triangulation is None:
self._cpp_triangulation = _tri.Triangulation(
# For unset arrays use empty tuple which has size of zero.
self.x, self.y, self.triangles,
self.mask if self.mask is not None else (),
self._edges if self._edges is not None else (),
self._neighbors if self._neighbors is not None else (),
not self.is_delaunay)
return self._cpp_triangulation
def get_masked_triangles(self):
"""
Return an array of triangles taking the mask into account.
"""
if self.mask is not None:
return self.triangles[~self.mask]
else:
return self.triangles
@staticmethod
def get_from_args_and_kwargs(*args, **kwargs):
"""
Return a Triangulation object from the args and kwargs, and
the remaining args and kwargs with the consumed values removed.
There are two alternatives: either the first argument is a
Triangulation object, in which case it is returned, or the args
and kwargs are sufficient to create a new Triangulation to
return. In the latter case, see Triangulation.__init__ for
the possible args and kwargs.
"""
if isinstance(args[0], Triangulation):
triangulation, *args = args
if 'triangles' in kwargs:
_api.warn_external(
"Passing the keyword 'triangles' has no effect when also "
"passing a Triangulation")
if 'mask' in kwargs:
_api.warn_external(
"Passing the keyword 'mask' has no effect when also "
"passing a Triangulation")
else:
x, y, triangles, mask, args, kwargs = \
Triangulation._extract_triangulation_params(args, kwargs)
triangulation = Triangulation(x, y, triangles, mask)
return triangulation, args, kwargs
@staticmethod
def _extract_triangulation_params(args, kwargs):
x, y, *args = args
# Check triangles in kwargs then args.
triangles = kwargs.pop('triangles', None)
from_args = False
if triangles is None and args:
triangles = args[0]
from_args = True
if triangles is not None:
try:
triangles = np.asarray(triangles, dtype=np.int32)
except ValueError:
triangles = None
if triangles is not None and (triangles.ndim != 2 or
triangles.shape[1] != 3):
triangles = None
if triangles is not None and from_args:
args = args[1:] # Consumed first item in args.
# Check for mask in kwargs.
mask = kwargs.pop('mask', None)
return x, y, triangles, mask, args, kwargs
def get_trifinder(self):
"""
Return the default `matplotlib.tri.TriFinder` of this
triangulation, creating it if necessary. This allows the same
TriFinder object to be easily shared.
"""
if self._trifinder is None:
# Default TriFinder class.
from matplotlib.tri._trifinder import TrapezoidMapTriFinder
self._trifinder = TrapezoidMapTriFinder(self)
return self._trifinder
@property
def neighbors(self):
"""
Return integer array of shape (ntri, 3) containing neighbor triangles.
For each triangle, the indices of the three triangles that
share the same edges, or -1 if there is no such neighboring
triangle. ``neighbors[i, j]`` is the triangle that is the neighbor
to the edge from point index ``triangles[i, j]`` to point index
``triangles[i, (j+1)%3]``.
"""
if self._neighbors is None:
self._neighbors = self.get_cpp_triangulation().get_neighbors()
return self._neighbors
def set_mask(self, mask):
"""
Set or clear the mask array.
Parameters
----------
mask : None or bool array of length ntri
"""
if mask is None:
self.mask = None
else:
self.mask = np.asarray(mask, dtype=bool)
if self.mask.shape != (self.triangles.shape[0],):
raise ValueError('mask array must have same length as '
'triangles array')
# Set mask in C++ Triangulation.
if self._cpp_triangulation is not None:
self._cpp_triangulation.set_mask(
self.mask if self.mask is not None else ())
# Clear derived fields so they are recalculated when needed.
self._edges = None
self._neighbors = None
# Recalculate TriFinder if it exists.
if self._trifinder is not None:
self._trifinder._initialize()
| Triangulation |
python | pandas-dev__pandas | pandas/tests/indexes/base_class/test_where.py | {
"start": 76,
"end": 341
} | class ____:
def test_where_intlike_str_doesnt_cast_ints(self):
idx = Index(range(3))
mask = np.array([True, False, True])
res = idx.where(mask, "2")
expected = Index([0, "2", 2])
tm.assert_index_equal(res, expected)
| TestWhere |
python | doocs__leetcode | solution/0300-0399/0382.Linked List Random Node/Solution.py | {
"start": 151,
"end": 615
} | class ____:
def __init__(self, head: Optional[ListNode]):
self.head = head
def getRandom(self) -> int:
n = ans = 0
head = self.head
while head:
n += 1
x = random.randint(1, n)
if n == x:
ans = head.val
head = head.next
return ans
# Your Solution object will be instantiated and called as such:
# obj = Solution(head)
# param_1 = obj.getRandom()
| Solution |
python | jazzband__django-polymorphic | src/polymorphic/tests/models.py | {
"start": 4706,
"end": 4859
} | class ____(ShowFieldTypeAndContent, Model2A):
objects = MyManagerQuerySet.as_manager()
field4 = models.CharField(max_length=30)
| ModelWithMyManager2 |
python | ray-project__ray | python/ray/tune/progress_reporter.py | {
"start": 15985,
"end": 16582
} | class ____:
"""Remote reporter abstract mixin class.
Subclasses of this class will use a Ray Queue to display output
on the driver side when running Ray Client."""
@property
def output_queue(self) -> Queue:
return getattr(self, "_output_queue", None)
@output_queue.setter
def output_queue(self, value: Queue):
self._output_queue = value
def display(self, string: str) -> None:
"""Display the progress string.
Args:
string: String to display.
"""
raise NotImplementedError
@PublicAPI
| RemoteReporterMixin |
python | walkccc__LeetCode | solutions/211. Add and Search Word - Data structure design/211.py | {
"start": 108,
"end": 762
} | class ____:
def __init__(self):
self.root = TrieNode()
def addWord(self, word: str) -> None:
node: TrieNode = self.root
for c in word:
node = node.children.setdefault(c, TrieNode())
node.isWord = True
def search(self, word: str) -> bool:
return self._dfs(word, 0, self.root)
def _dfs(self, word: str, s: int, node: TrieNode) -> bool:
if s == len(word):
return node.isWord
if word[s] != '.':
child: TrieNode = node.children.get(word[s], None)
return self._dfs(word, s + 1, child) if child else False
return any(self._dfs(word, s + 1, child) for child in node.children.values())
| WordDictionary |
python | django__django | tests/expressions/tests.py | {
"start": 112747,
"end": 113317
} | class ____(SimpleTestCase):
def test_empty_group_by(self):
expr = ExpressionWrapper(Value(3), output_field=IntegerField())
self.assertEqual(expr.get_group_by_cols(), [])
def test_non_empty_group_by(self):
value = Value("f")
value.output_field = None
expr = ExpressionWrapper(Lower(value), output_field=IntegerField())
group_by_cols = expr.get_group_by_cols()
self.assertEqual(group_by_cols, [expr.expression])
self.assertEqual(group_by_cols[0].output_field, expr.output_field)
| ExpressionWrapperTests |
python | docker__docker-py | tests/integration/api_exec_test.py | {
"start": 270,
"end": 8273
} | class ____(BaseAPIIntegrationTest):
def test_execute_command_with_proxy_env(self):
# Set a custom proxy config on the client
self.client._proxy_configs = ProxyConfig(
ftp='a', https='b', http='c', no_proxy='d'
)
container = self.client.create_container(
TEST_IMG, 'cat', detach=True, stdin_open=True,
)
self.client.start(container)
self.tmp_containers.append(container)
cmd = 'sh -c "env | grep -i proxy"'
# First, just make sure the environment variables from the custom
# config are set
res = self.client.exec_create(container, cmd=cmd)
output = self.client.exec_start(res).decode('utf-8').split('\n')
expected = [
'ftp_proxy=a', 'https_proxy=b', 'http_proxy=c', 'no_proxy=d',
'FTP_PROXY=a', 'HTTPS_PROXY=b', 'HTTP_PROXY=c', 'NO_PROXY=d'
]
for item in expected:
assert item in output
# Overwrite some variables with a custom environment
env = {'https_proxy': 'xxx', 'HTTPS_PROXY': 'XXX'}
res = self.client.exec_create(container, cmd=cmd, environment=env)
output = self.client.exec_start(res).decode('utf-8').split('\n')
expected = [
'ftp_proxy=a', 'https_proxy=xxx', 'http_proxy=c', 'no_proxy=d',
'FTP_PROXY=a', 'HTTPS_PROXY=XXX', 'HTTP_PROXY=c', 'NO_PROXY=d'
]
for item in expected:
assert item in output
def test_execute_command(self):
container = self.client.create_container(TEST_IMG, 'cat',
detach=True, stdin_open=True)
id = container['Id']
self.client.start(id)
self.tmp_containers.append(id)
res = self.client.exec_create(id, ['echo', 'hello'])
assert 'Id' in res
exec_log = self.client.exec_start(res)
assert exec_log == b'hello\n'
def test_exec_command_string(self):
container = self.client.create_container(TEST_IMG, 'cat',
detach=True, stdin_open=True)
id = container['Id']
self.client.start(id)
self.tmp_containers.append(id)
res = self.client.exec_create(id, 'echo hello world')
assert 'Id' in res
exec_log = self.client.exec_start(res)
assert exec_log == b'hello world\n'
def test_exec_command_as_user(self):
container = self.client.create_container(TEST_IMG, 'cat',
detach=True, stdin_open=True)
id = container['Id']
self.client.start(id)
self.tmp_containers.append(id)
res = self.client.exec_create(id, 'whoami', user='postgres')
assert 'Id' in res
exec_log = self.client.exec_start(res)
assert exec_log == b'postgres\n'
def test_exec_command_as_root(self):
container = self.client.create_container(TEST_IMG, 'cat',
detach=True, stdin_open=True)
id = container['Id']
self.client.start(id)
self.tmp_containers.append(id)
res = self.client.exec_create(id, 'whoami')
assert 'Id' in res
exec_log = self.client.exec_start(res)
assert exec_log == b'root\n'
def test_exec_command_streaming(self):
container = self.client.create_container(TEST_IMG, 'cat',
detach=True, stdin_open=True)
id = container['Id']
self.tmp_containers.append(id)
self.client.start(id)
exec_id = self.client.exec_create(id, ['echo', 'hello\nworld'])
assert 'Id' in exec_id
res = b''
for chunk in self.client.exec_start(exec_id, stream=True):
res += chunk
assert res == b'hello\nworld\n'
def test_exec_start_socket(self):
container = self.client.create_container(TEST_IMG, 'cat',
detach=True, stdin_open=True)
container_id = container['Id']
self.client.start(container_id)
self.tmp_containers.append(container_id)
line = 'yay, interactive exec!'
# `echo` appends CRLF, `printf` doesn't
exec_id = self.client.exec_create(
container_id, ['printf', line], tty=True)
assert 'Id' in exec_id
socket = self.client.exec_start(exec_id, socket=True)
self.addCleanup(socket.close)
(stream, next_size) = next_frame_header(socket)
assert stream == 1 # stdout (0 = stdin, 1 = stdout, 2 = stderr)
assert next_size == len(line)
data = read_exactly(socket, next_size)
assert data.decode('utf-8') == line
def test_exec_start_detached(self):
container = self.client.create_container(TEST_IMG, 'cat',
detach=True, stdin_open=True)
container_id = container['Id']
self.client.start(container_id)
self.tmp_containers.append(container_id)
exec_id = self.client.exec_create(
container_id, ['printf', "asdqwe"])
assert 'Id' in exec_id
response = self.client.exec_start(exec_id, detach=True)
assert response == ""
def test_exec_inspect(self):
container = self.client.create_container(TEST_IMG, 'cat',
detach=True, stdin_open=True)
id = container['Id']
self.client.start(id)
self.tmp_containers.append(id)
exec_id = self.client.exec_create(id, ['mkdir', '/does/not/exist'])
assert 'Id' in exec_id
self.client.exec_start(exec_id)
exec_info = self.client.exec_inspect(exec_id)
assert 'ExitCode' in exec_info
assert exec_info['ExitCode'] != 0
@requires_api_version('1.25')
def test_exec_command_with_env(self):
container = self.client.create_container(TEST_IMG, 'cat',
detach=True, stdin_open=True)
id = container['Id']
self.client.start(id)
self.tmp_containers.append(id)
res = self.client.exec_create(id, 'env', environment=["X=Y"])
assert 'Id' in res
exec_log = self.client.exec_start(res)
assert b'X=Y\n' in exec_log
@requires_api_version('1.35')
def test_exec_command_with_workdir(self):
container = self.client.create_container(
TEST_IMG, 'cat', detach=True, stdin_open=True
)
self.tmp_containers.append(container)
self.client.start(container)
res = self.client.exec_create(container, 'pwd', workdir='/var/opt')
exec_log = self.client.exec_start(res)
assert exec_log == b'/var/opt\n'
def test_detach_with_default(self):
container = self.client.create_container(
TEST_IMG, 'cat', detach=True, stdin_open=True
)
id = container['Id']
self.client.start(id)
self.tmp_containers.append(id)
exec_id = self.client.exec_create(
id, 'cat', stdin=True, tty=True, stdout=True
)
sock = self.client.exec_start(exec_id, tty=True, socket=True)
self.addCleanup(sock.close)
assert_cat_socket_detached_with_keys(
sock, [ctrl_with('p'), ctrl_with('q')]
)
def test_detach_with_config_file(self):
self.client._general_configs['detachKeys'] = 'ctrl-p'
container = self.client.create_container(
TEST_IMG, 'cat', detach=True, stdin_open=True
)
id = container['Id']
self.client.start(id)
self.tmp_containers.append(id)
exec_id = self.client.exec_create(
id, 'cat', stdin=True, tty=True, stdout=True
)
sock = self.client.exec_start(exec_id, tty=True, socket=True)
self.addCleanup(sock.close)
assert_cat_socket_detached_with_keys(sock, [ctrl_with('p')])
| ExecTest |
python | pdm-project__pdm | src/pdm/cli/commands/new.py | {
"start": 172,
"end": 811
} | class ____(InitCommand):
"""Create a new Python project at <project_path>"""
supports_other_generator = False
arguments = (verbose_option,)
def add_arguments(self, parser: argparse.ArgumentParser) -> None:
super().add_arguments(parser)
parser.add_argument("project_path", help="The path to create the new project")
def handle(self, project: Project, options: argparse.Namespace) -> None:
new_project = project.core.create_project(
options.project_path, global_config=options.config or os.getenv("PDM_CONFIG_FILE")
)
return super().handle(new_project, options)
| Command |
python | paramiko__paramiko | tests/test_transport.py | {
"start": 38834,
"end": 41747
} | class ____(unittest.TestCase):
def test_preferred_lists_default_to_private_attribute_contents(self):
t = Transport(sock=Mock())
assert t.preferred_ciphers == t._preferred_ciphers
assert t.preferred_macs == t._preferred_macs
assert t.preferred_keys == tuple(
t._preferred_keys
+ tuple(
"{}-cert-v01@openssh.com".format(x) for x in t._preferred_keys
)
)
assert t.preferred_kex == t._preferred_kex
def test_preferred_lists_filter_disabled_algorithms(self):
t = Transport(
sock=Mock(),
disabled_algorithms={
"ciphers": ["aes128-cbc"],
"macs": ["hmac-md5"],
"keys": ["ssh-rsa"],
"kex": ["diffie-hellman-group14-sha256"],
},
)
assert "aes128-cbc" in t._preferred_ciphers
assert "aes128-cbc" not in t.preferred_ciphers
assert "hmac-md5" in t._preferred_macs
assert "hmac-md5" not in t.preferred_macs
assert "ssh-rsa" in t._preferred_keys
assert "ssh-rsa" not in t.preferred_keys
assert "ssh-rsa-cert-v01@openssh.com" not in t.preferred_keys
assert "diffie-hellman-group14-sha256" in t._preferred_kex
assert "diffie-hellman-group14-sha256" not in t.preferred_kex
def test_implementation_refers_to_public_algo_lists(self):
t = Transport(
sock=Mock(),
disabled_algorithms={
"ciphers": ["aes128-cbc"],
"macs": ["hmac-md5"],
"keys": ["ssh-rsa"],
"kex": ["diffie-hellman-group14-sha256"],
"compression": ["zlib"],
},
)
# Enable compression cuz otherwise disabling one option for it makes no
# sense...
t.use_compression(True)
# Effectively a random spot check, but kex init touches most/all of the
# algorithm lists so it's a good spot.
t._send_message = Mock()
t._send_kex_init()
# Cribbed from Transport._parse_kex_init, which didn't feel worth
# refactoring given all the vars involved :(
m = t._send_message.call_args[0][0]
m.rewind()
m.get_byte() # the msg type
m.get_bytes(16) # cookie, discarded
kexen = m.get_list()
server_keys = m.get_list()
ciphers = m.get_list()
m.get_list()
macs = m.get_list()
m.get_list()
compressions = m.get_list()
# OK, now we can actually check that our disabled algos were not
# included (as this message includes the full lists)
assert "aes128-cbc" not in ciphers
assert "hmac-md5" not in macs
assert "ssh-rsa" not in server_keys
assert "diffie-hellman-group14-sha256" not in kexen
assert "zlib" not in compressions
| AlgorithmDisablingTests |
python | realpython__materials | geoshops/nearbyshops/admin.py | {
"start": 132,
"end": 202
} | class ____(OSMGeoAdmin):
list_display = ("name", "location")
| ShopAdmin |
python | crytic__slither | slither/utils/halstead.py | {
"start": 1204,
"end": 4673
} | class ____:
"""Class to hold the Halstead metrics for a single contract."""
contract: Contract
all_operators: List[str] = field(default_factory=list)
all_operands: List[str] = field(default_factory=list)
n1: int = 0
n2: int = 0
N1: int = 0
N2: int = 0
n: int = 0
N: int = 0
S: float = 0
V: float = 0
D: float = 0
E: float = 0
T: float = 0
B: float = 0
def __post_init__(self) -> None:
"""Operators and operands can be passed in as constructor args to avoid computing
them based on the contract. Useful for computing metrics for ALL_CONTRACTS"""
if len(self.all_operators) == 0:
if not hasattr(self.contract, "functions"):
return
self.populate_operators_and_operands()
if len(self.all_operators) > 0:
self.compute_metrics()
def to_dict(self) -> Dict[str, float]:
"""Return the metrics as a dictionary."""
return OrderedDict(
{
"Total Operators": self.N1,
"Unique Operators": self.n1,
"Total Operands": self.N2,
"Unique Operands": self.n2,
"Vocabulary": str(self.n1 + self.n2),
"Program Length": str(self.N1 + self.N2),
"Estimated Length": f"{self.S:.0f}",
"Volume": f"{self.V:.0f}",
"Difficulty": f"{self.D:.0f}",
"Effort": f"{self.E:.0f}",
"Time": f"{self.T:.0f}",
"Estimated Bugs": f"{self.B:.3f}",
}
)
def populate_operators_and_operands(self) -> None:
"""Populate the operators and operands lists."""
operators = []
operands = []
for func in self.contract.functions:
for node in func.nodes:
for operation in node.irs:
# use operation.expression.type to get the unique operator type
encoded_operator = encode_ir_for_halstead(operation)
operators.append(encoded_operator)
# use operation.used to get the operands of the operation ignoring the temporary variables
operands.extend(
[op for op in operation.used if not isinstance(op, TemporaryVariable)]
)
self.all_operators.extend(operators)
self.all_operands.extend(operands)
def compute_metrics(self, all_operators=None, all_operands=None) -> None:
"""Compute the Halstead metrics."""
if all_operators is None:
all_operators = self.all_operators
all_operands = self.all_operands
# core metrics
self.n1 = len(set(all_operators))
self.n2 = len(set(all_operands))
self.N1 = len(all_operators)
self.N2 = len(all_operands)
if any(number <= 0 for number in [self.n1, self.n2, self.N1, self.N2]):
raise ValueError("n1 and n2 must be greater than 0")
# extended metrics 1
self.n = self.n1 + self.n2
self.N = self.N1 + self.N2
self.S = self.n1 * math.log2(self.n1) + self.n2 * math.log2(self.n2)
self.V = self.N * math.log2(self.n)
# extended metrics 2
self.D = (self.n1 / 2) * (self.N2 / self.n2)
self.E = self.D * self.V
self.T = self.E / 18
self.B = (self.E ** (2 / 3)) / 3000
@dataclass
| HalsteadContractMetrics |
python | pandas-dev__pandas | pandas/tests/tools/test_to_timedelta.py | {
"start": 392,
"end": 11254
} | class ____:
def test_to_timedelta_none(self):
# GH#23055
assert to_timedelta(None) is pd.NaT
def test_to_timedelta_dt64_raises(self):
# Passing datetime64-dtype data to TimedeltaIndex is no longer
# supported GH#29794
msg = r"dtype datetime64\[ns\] cannot be converted to timedelta64\[ns\]"
ser = Series([pd.NaT], dtype="M8[ns]")
with pytest.raises(TypeError, match=msg):
to_timedelta(ser)
with pytest.raises(TypeError, match=msg):
ser.to_frame().apply(to_timedelta)
def test_to_timedelta_readonly(self, writable):
# GH#34857
arr = np.array([], dtype=object)
arr.setflags(write=writable)
result = to_timedelta(arr)
expected = to_timedelta([])
tm.assert_index_equal(result, expected)
def test_to_timedelta_null(self):
result = to_timedelta(["", ""])
assert isna(result).all()
def test_to_timedelta_same_np_timedelta64(self):
# pass thru
result = to_timedelta(np.array([np.timedelta64(1, "s")]))
expected = pd.Index(np.array([np.timedelta64(1, "s")]))
tm.assert_index_equal(result, expected)
def test_to_timedelta_series(self):
# Series
expected = Series(
[timedelta(days=1), timedelta(days=1, seconds=1)], dtype="m8[ns]"
)
msg = "'d' is deprecated and will be removed in a future version."
with tm.assert_produces_warning(Pandas4Warning, match=msg):
result = to_timedelta(Series(["1d", "1days 00:00:01"]))
tm.assert_series_equal(result, expected)
def test_to_timedelta_units(self):
# with units
result = TimedeltaIndex(
[np.timedelta64(0, "ns"), np.timedelta64(10, "s").astype("m8[ns]")]
)
expected = to_timedelta([0, 10], unit="s")
tm.assert_index_equal(result, expected)
@pytest.mark.parametrize(
"dtype, unit",
[
["int64", "s"],
["int64", "m"],
["int64", "h"],
["timedelta64[s]", "s"],
["timedelta64[D]", "D"],
],
)
def test_to_timedelta_units_dtypes(self, dtype, unit):
# arrays of various dtypes
arr = np.array([1] * 5, dtype=dtype)
result = to_timedelta(arr, unit=unit)
exp_dtype = "m8[ns]" if dtype == "int64" else "m8[s]"
expected = TimedeltaIndex([np.timedelta64(1, unit)] * 5, dtype=exp_dtype)
tm.assert_index_equal(result, expected)
def test_to_timedelta_oob_non_nano(self):
arr = np.array([pd.NaT._value + 1], dtype="timedelta64[m]")
msg = (
"Cannot convert -9223372036854775807 minutes to "
r"timedelta64\[s\] without overflow"
)
with pytest.raises(OutOfBoundsTimedelta, match=msg):
to_timedelta(arr)
with pytest.raises(OutOfBoundsTimedelta, match=msg):
TimedeltaIndex(arr)
with pytest.raises(OutOfBoundsTimedelta, match=msg):
TimedeltaArray._from_sequence(arr, dtype="m8[s]")
@pytest.mark.parametrize("box", [lambda x: x, pd.DataFrame])
@pytest.mark.parametrize("errors", ["raise", "coerce"])
def test_to_timedelta_dataframe(self, box, errors):
# GH 11776
arg = box(np.arange(10).reshape(2, 5))
with pytest.raises(TypeError, match="1-d array"):
to_timedelta(arg, errors=errors)
def test_to_timedelta_invalid_errors(self):
# bad value for errors parameter
msg = "errors must be one of"
with pytest.raises(ValueError, match=msg):
to_timedelta(["foo"], errors="never")
@pytest.mark.parametrize("arg", [[1, 2], 1])
def test_to_timedelta_invalid_unit(self, arg):
# these will error
msg = "invalid unit abbreviation: foo"
with pytest.raises(ValueError, match=msg):
to_timedelta(arg, unit="foo")
def test_to_timedelta_time(self):
# time not supported ATM
msg = (
"Value must be Timedelta, string, integer, float, timedelta or convertible"
)
with pytest.raises(ValueError, match=msg):
to_timedelta(time(second=1))
assert to_timedelta(time(second=1), errors="coerce") is pd.NaT
def test_to_timedelta_bad_value(self):
msg = "Could not convert 'foo' to NumPy timedelta"
with pytest.raises(ValueError, match=msg):
to_timedelta(["foo", "bar"])
def test_to_timedelta_bad_value_coerce(self):
tm.assert_index_equal(
TimedeltaIndex([pd.NaT, pd.NaT]),
to_timedelta(["foo", "bar"], errors="coerce"),
)
tm.assert_index_equal(
TimedeltaIndex(["1 day", pd.NaT, "1 min"]),
to_timedelta(["1 day", "bar", "1 min"], errors="coerce"),
)
@pytest.mark.parametrize(
"val, errors",
[
("1M", True),
("1 M", True),
("1Y", True),
("1 Y", True),
("1y", True),
("1 y", True),
("1m", False),
("1 m", False),
("1 day", False),
("2day", False),
],
)
def test_unambiguous_timedelta_values(self, val, errors):
# GH36666 Deprecate use of strings denoting units with 'M', 'Y', 'm' or 'y'
# in pd.to_timedelta
msg = "Units 'M', 'Y' and 'y' do not represent unambiguous timedelta"
if errors:
with pytest.raises(ValueError, match=msg):
to_timedelta(val)
else:
# check it doesn't raise
to_timedelta(val)
def test_to_timedelta_via_apply(self):
# GH 5458
expected = Series([np.timedelta64(1, "s")], dtype="m8[ns]")
result = Series(["00:00:01"]).apply(to_timedelta)
tm.assert_series_equal(result, expected)
result = Series([to_timedelta("00:00:01")])
tm.assert_series_equal(result, expected)
def test_to_timedelta_inference_without_warning(self):
# GH#41731 inference produces a warning in the Series constructor,
# but _not_ in to_timedelta
vals = ["00:00:01", pd.NaT]
with tm.assert_produces_warning(None):
result = to_timedelta(vals)
expected = TimedeltaIndex([pd.Timedelta(seconds=1), pd.NaT])
tm.assert_index_equal(result, expected)
def test_to_timedelta_on_missing_values(self):
# GH5438
timedelta_NaT = np.timedelta64("NaT")
actual = to_timedelta(Series(["00:00:01", np.nan]))
expected = Series(
[np.timedelta64(1000000000, "ns"), timedelta_NaT],
dtype=f"{tm.ENDIAN}m8[ns]",
)
tm.assert_series_equal(actual, expected)
ser = Series(["00:00:01", pd.NaT], dtype="m8[ns]")
actual = to_timedelta(ser)
tm.assert_series_equal(actual, expected)
@pytest.mark.parametrize("val", [np.nan, pd.NaT, pd.NA])
def test_to_timedelta_on_missing_values_scalar(self, val):
actual = to_timedelta(val)
assert actual._value == np.timedelta64("NaT").astype("int64")
@pytest.mark.parametrize("val", [np.nan, pd.NaT, pd.NA])
def test_to_timedelta_on_missing_values_list(self, val):
actual = to_timedelta([val])
assert actual[0]._value == np.timedelta64("NaT").astype("int64")
@pytest.mark.skipif(WASM, reason="No fp exception support in WASM")
@pytest.mark.xfail(not IS64, reason="Floating point error")
def test_to_timedelta_float(self):
# https://github.com/pandas-dev/pandas/issues/25077
arr = np.arange(0, 1, 1e-6)[-10:]
result = to_timedelta(arr, unit="s")
expected_asi8 = np.arange(999990000, 10**9, 1000, dtype="int64")
tm.assert_numpy_array_equal(result.asi8, expected_asi8)
def test_to_timedelta_coerce_strings_unit(self):
arr = np.array([1, 2, "error"], dtype=object)
result = to_timedelta(arr, unit="ns", errors="coerce")
expected = to_timedelta([1, 2, pd.NaT], unit="ns")
tm.assert_index_equal(result, expected)
@pytest.mark.parametrize(
"expected_val, result_val", [[timedelta(days=2), 2], [None, None]]
)
def test_to_timedelta_nullable_int64_dtype(self, expected_val, result_val):
# GH 35574
expected = Series([timedelta(days=1), expected_val], dtype="m8[ns]")
result = to_timedelta(Series([1, result_val], dtype="Int64"), unit="days")
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize(
("input", "expected"),
[
("8:53:08.71800000001", "8:53:08.718"),
("8:53:08.718001", "8:53:08.718001"),
("8:53:08.7180000001", "8:53:08.7180000001"),
("-8:53:08.71800000001", "-8:53:08.718"),
("8:53:08.7180000089", "8:53:08.718000008"),
],
)
@pytest.mark.parametrize("func", [pd.Timedelta, to_timedelta])
def test_to_timedelta_precision_over_nanos(self, input, expected, func):
# GH: 36738
expected = pd.Timedelta(expected)
result = func(input)
assert result == expected
def test_to_timedelta_zerodim(self, fixed_now_ts):
# ndarray.item() incorrectly returns int for dt64[ns] and td64[ns]
dt64 = fixed_now_ts.to_datetime64()
arg = np.array(dt64)
msg = (
"Value must be Timedelta, string, integer, float, timedelta "
"or convertible, not datetime64"
)
with pytest.raises(ValueError, match=msg):
to_timedelta(arg)
arg2 = arg.view("m8[ns]")
result = to_timedelta(arg2)
assert isinstance(result, pd.Timedelta)
assert result._value == dt64.view("i8")
def test_to_timedelta_numeric_ea(self, any_numeric_ea_dtype):
# GH#48796
ser = Series([1, pd.NA], dtype=any_numeric_ea_dtype)
result = to_timedelta(ser)
expected = Series([pd.Timedelta(1, unit="ns"), pd.NaT])
tm.assert_series_equal(result, expected)
def test_to_timedelta_fraction(self):
result = to_timedelta(1.0 / 3, unit="h")
expected = pd.Timedelta("0 days 00:19:59.999999998")
assert result == expected
def test_from_numeric_arrow_dtype(any_numeric_ea_dtype):
# GH 52425
pytest.importorskip("pyarrow")
ser = Series([1, 2], dtype=f"{any_numeric_ea_dtype.lower()}[pyarrow]")
result = to_timedelta(ser)
expected = Series([1, 2], dtype="timedelta64[ns]")
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("unit", ["ns", "ms"])
def test_from_timedelta_arrow_dtype(unit):
# GH 54298
pytest.importorskip("pyarrow")
expected = Series([timedelta(1)], dtype=f"duration[{unit}][pyarrow]")
result = to_timedelta(expected)
tm.assert_series_equal(result, expected)
| TestTimedeltas |
python | huggingface__transformers | src/transformers/models/unispeech_sat/modeling_unispeech_sat.py | {
"start": 21676,
"end": 23429
} | class ____(GradientCheckpointingLayer):
def __init__(self, config):
super().__init__()
self.attention = UniSpeechSatAttention(
embed_dim=config.hidden_size,
num_heads=config.num_attention_heads,
dropout=config.attention_dropout,
is_decoder=False,
config=config,
)
self.dropout = nn.Dropout(config.hidden_dropout)
self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.feed_forward = UniSpeechSatFeedForward(config)
self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
if getattr(config, "adapter_attn_dim", None) is not None:
self.adapter_layer = UniSpeechSatAttnAdapterLayer(config)
else:
self.adapter_layer = None
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
output_attentions: bool = False,
):
attn_residual = hidden_states
hidden_states = self.layer_norm(hidden_states)
hidden_states, attn_weights, _ = self.attention(
hidden_states, attention_mask=attention_mask, output_attentions=output_attentions
)
hidden_states = self.dropout(hidden_states)
hidden_states = attn_residual + hidden_states
hidden_states = hidden_states + self.feed_forward(self.final_layer_norm(hidden_states))
if self.adapter_layer is not None:
hidden_states = hidden_states + self.adapter_layer(hidden_states)
outputs = (hidden_states,)
if output_attentions:
outputs += (attn_weights,)
return outputs
| UniSpeechSatEncoderLayerStableLayerNorm |
python | astropy__astropy | astropy/io/fits/column.py | {
"start": 15613,
"end": 18219
} | class ____:
"""
Descriptor for attributes of `Column` that are associated with keywords
in the FITS header and describe properties of the column as specified in
the FITS standard.
Each `ColumnAttribute` may have a ``validator`` method defined on it.
This validates values set on this attribute to ensure that they meet the
FITS standard. Invalid values will raise a warning and will not be used in
formatting the column. The validator should take two arguments--the
`Column` it is being assigned to, and the new value for the attribute, and
it must raise an `AssertionError` if the value is invalid.
The `ColumnAttribute` itself is a decorator that can be used to define the
``validator`` for each column attribute. For example::
@ColumnAttribute('TTYPE')
def name(col, name):
if not isinstance(name, str):
raise AssertionError
The actual object returned by this decorator is the `ColumnAttribute`
instance though, not the ``name`` function. As such ``name`` is not a
method of the class it is defined in.
The setter for `ColumnAttribute` also updates the header of any table
HDU this column is attached to in order to reflect the change. The
``validator`` should ensure that the value is valid for inclusion in a FITS
header.
"""
def __init__(self, keyword):
self._keyword = keyword
self._validator = None
# The name of the attribute associated with this keyword is currently
# determined from the KEYWORD_NAMES/ATTRIBUTES lists. This could be
# make more flexible in the future, for example, to support custom
# column attributes.
self._attr = "_" + KEYWORD_TO_ATTRIBUTE[self._keyword]
def __get__(self, obj, objtype=None):
if obj is None:
return self
else:
return getattr(obj, self._attr)
def __set__(self, obj, value):
if self._validator is not None:
self._validator(obj, value)
old_value = getattr(obj, self._attr, None)
setattr(obj, self._attr, value)
obj._notify("column_attribute_changed", obj, self._attr[1:], old_value, value)
def __call__(self, func):
"""
Set the validator for this column attribute.
Returns ``self`` so that this can be used as a decorator, as described
in the docs for this class.
"""
self._validator = func
return self
def __repr__(self):
return f"{self.__class__.__name__}('{self._keyword}')"
| ColumnAttribute |
python | numpy__numpy | tools/swig/test/testFlat.py | {
"start": 5240,
"end": 5501
} | class ____(FlatTestCase):
def __init__(self, methodName="runTest"):
FlatTestCase.__init__(self, methodName)
self.typeStr = "float"
self.typeCode = "f"
######################################################################
| floatTestCase |
python | sympy__sympy | sympy/stats/drv.py | {
"start": 6617,
"end": 9520
} | class ____(PSpace):
is_real = True
is_Discrete = True
@property
def pdf(self):
return self.density(*self.symbols)
def where(self, condition):
rvs = random_symbols(condition)
assert all(r.symbol in self.symbols for r in rvs)
if len(rvs) > 1:
raise NotImplementedError(filldedent('''Multivariate discrete
random variables are not yet supported.'''))
conditional_domain = reduce_rational_inequalities_wrap(condition,
rvs[0])
conditional_domain = conditional_domain.intersect(self.domain.set)
return SingleDiscreteDomain(rvs[0].symbol, conditional_domain)
def probability(self, condition):
complement = isinstance(condition, Ne)
if complement:
condition = Eq(condition.args[0], condition.args[1])
try:
_domain = self.where(condition).set
if condition == False or _domain is S.EmptySet:
return S.Zero
if condition == True or _domain == self.domain.set:
return S.One
prob = self.eval_prob(_domain)
except NotImplementedError:
from sympy.stats.rv import density
expr = condition.lhs - condition.rhs
dens = density(expr)
if not isinstance(dens, DiscreteDistribution):
from sympy.stats.drv_types import DiscreteDistributionHandmade
dens = DiscreteDistributionHandmade(dens)
z = Dummy('z', real=True)
space = SingleDiscretePSpace(z, dens)
prob = space.probability(condition.__class__(space.value, 0))
if prob is None:
prob = Probability(condition)
return prob if not complement else S.One - prob
def eval_prob(self, _domain):
sym = list(self.symbols)[0]
if isinstance(_domain, Range):
n = symbols('n', integer=True)
inf, sup, step = (r for r in _domain.args)
summand = ((self.pdf).replace(
sym, n*step))
rv = summation(summand,
(n, inf/step, (sup)/step - 1)).doit()
return rv
elif isinstance(_domain, FiniteSet):
pdf = Lambda(sym, self.pdf)
rv = sum(pdf(x) for x in _domain)
return rv
elif isinstance(_domain, Union):
rv = sum(self.eval_prob(x) for x in _domain.args)
return rv
def conditional_space(self, condition):
# XXX: Converting from set to tuple. The order matters to Lambda
# though so we should be starting with a set...
density = Lambda(tuple(self.symbols), self.pdf/self.probability(condition))
condition = condition.xreplace({rv: rv.symbol for rv in self.values})
domain = ConditionalDiscreteDomain(self.domain, condition)
return DiscretePSpace(domain, density)
| DiscretePSpace |
python | walkccc__LeetCode | solutions/2901. Longest Unequal Adjacent Groups Subsequence II/2901.py | {
"start": 0,
"end": 824
} | class ____:
def getWordsInLongestSubsequence(
self,
n: int,
words: list[str],
groups: list[int],
) -> list[str]:
ans = []
# dp[i] := the length of the longest subsequence ending in `words[i]`
dp = [1] * n
# prev[i] := the best index of words[i]
prev = [-1] * n
for i in range(1, n):
for j in range(i):
if groups[i] == groups[j]:
continue
if len(words[i]) != len(words[j]):
continue
if sum(a != b for a, b in zip(words[i], words[j])) != 1:
continue
if dp[i] < dp[j] + 1:
dp[i] = dp[j] + 1
prev[i] = j
# Find the last index of the subsequence.
index = dp.index(max(dp))
while index != -1:
ans.append(words[index])
index = prev[index]
return ans[::-1]
| Solution |
python | sqlalchemy__sqlalchemy | test/ext/asyncio/test_session.py | {
"start": 34149,
"end": 34187
} | class ____(Session):
pass
| _MySession |
python | mkdocs__mkdocs | mkdocs/config/config_options.py | {
"start": 41946,
"end": 43662
} | class ____(BaseConfigOption[List[types.ModuleType]]):
"""A list of Python scripts to be treated as instances of plugins."""
def __init__(self, plugins_key: str) -> None:
super().__init__()
self.default = []
self.plugins_key = plugins_key
def pre_validation(self, config: Config, key_name: str):
self._base_option = ListOfItems(File(exists=True))
self._base_option.pre_validation(config, key_name)
def run_validation(self, value: object) -> Mapping[str, Any]:
paths = self._base_option.validate(value)
self.warnings.extend(self._base_option.warnings)
assert isinstance(value, list)
hooks = {}
for name, path in zip(value, paths):
hooks[name] = self._load_hook(name, path)
return hooks
@functools.lru_cache(maxsize=None)
def _load_hook(self, name, path):
import importlib.util
spec = importlib.util.spec_from_file_location(name, path)
if spec is None:
raise ValidationError(f"Cannot import path '{path}' as a Python module")
module = importlib.util.module_from_spec(spec)
sys.modules[name] = module
if spec.loader is None:
raise ValidationError(f"Cannot import path '{path}' as a Python module")
old_sys_path = sys.path.copy()
sys.path.insert(0, os.path.dirname(path))
try:
spec.loader.exec_module(module)
finally:
sys.path[:] = old_sys_path
return module
def post_validation(self, config: Config, key_name: str):
plugins = config[self.plugins_key]
for name, hook in config[key_name].items():
plugins[name] = hook
| Hooks |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 832164,
"end": 832964
} | class ____(sgqlc.types.Type):
"""Information about pagination in a connection."""
__schema__ = github_schema
__field_names__ = ("end_cursor", "has_next_page", "has_previous_page", "start_cursor")
end_cursor = sgqlc.types.Field(String, graphql_name="endCursor")
"""When paginating forwards, the cursor to continue."""
has_next_page = sgqlc.types.Field(sgqlc.types.non_null(Boolean), graphql_name="hasNextPage")
"""When paginating forwards, are there more items?"""
has_previous_page = sgqlc.types.Field(sgqlc.types.non_null(Boolean), graphql_name="hasPreviousPage")
"""When paginating backwards, are there more items?"""
start_cursor = sgqlc.types.Field(String, graphql_name="startCursor")
"""When paginating backwards, the cursor to continue."""
| PageInfo |
python | getsentry__sentry | tests/snuba/api/endpoints/test_organization_events_has_measurements.py | {
"start": 247,
"end": 6937
} | class ____(APITestCase, SnubaTestCase):
def setUp(self) -> None:
super().setUp()
self.min_ago = before_now(minutes=1)
self.two_min_ago = before_now(minutes=2)
self.transaction_data = load_data("transaction", timestamp=before_now(minutes=1))
self.features: dict[str, bool] = {}
def do_request(self, query, features=None):
if features is None:
features = {
"organizations:discover-basic": True,
}
features.update(self.features)
self.login_as(user=self.user)
url = reverse(
"sentry-api-0-organization-events-has-measurements",
kwargs={"organization_id_or_slug": self.organization.slug},
)
with self.feature(features):
return self.client.get(url, query, format="json")
def test_without_feature(self) -> None:
response = self.do_request({}, features={"organizations:discover-basic": False})
assert response.status_code == 404, response.content
def test_no_projects(self) -> None:
response = self.do_request({})
assert response.status_code == 200, response.content
assert response.data == {"measurements": False}
def test_more_than_one_project(self) -> None:
project = self.create_project()
response = self.do_request(
{
"project": [self.project.id, project.id],
"transaction": self.transaction_data["transaction"],
"type": "web",
}
)
assert response.status_code == 400, response.content
assert response.data == {
"non_field_errors": [ErrorDetail("Only 1 project allowed.", code="invalid")],
}
def test_no_transaction(self) -> None:
response = self.do_request(
{
"project": [self.project.id],
"type": "web",
}
)
assert response.status_code == 400, response.content
assert response.data == {
"transaction": [ErrorDetail("This field may not be null.", code="null")],
}
def test_no_type(self) -> None:
response = self.do_request(
{
"project": [self.project.id],
"transaction": self.transaction_data["transaction"],
}
)
assert response.status_code == 400, response.content
assert response.data == {
"type": [ErrorDetail("This field may not be null.", code="null")],
}
def test_unknown_type(self) -> None:
response = self.do_request(
{
"project": [self.project.id],
"transaction": self.transaction_data["transaction"],
"type": "foo",
}
)
assert response.status_code == 400, response.content
assert response.data == {
"type": [ErrorDetail('"foo" is not a valid choice.', code="invalid_choice")],
}
def test_no_events(self) -> None:
response = self.do_request(
{
"project": [self.project.id],
"transaction": self.transaction_data["transaction"],
"type": "web",
}
)
assert response.status_code == 200, response.content
assert response.data == {"measurements": False}
def test_has_event_but_no_web_measurements(self) -> None:
# make sure the transaction doesn't have measurements
self.transaction_data["measurements"] = {}
self.store_event(self.transaction_data, self.project.id)
response = self.do_request(
{
"project": [self.project.id],
"transaction": self.transaction_data["transaction"],
"type": "web",
}
)
assert response.status_code == 200, response.content
assert response.data == {"measurements": False}
def test_has_event_and_no_recent_web_measurements(self) -> None:
# make sure the event is older than 7 days
transaction_data = load_data("transaction", timestamp=before_now(days=8))
# make sure the transaction has some web measurements
transaction_data["measurements"] = {"lcp": {"value": 100}}
self.store_event(transaction_data, self.project.id)
response = self.do_request(
{
"project": [self.project.id],
"transaction": self.transaction_data["transaction"],
"type": "web",
}
)
assert response.status_code == 200, response.content
assert response.data == {"measurements": False}
def test_has_event_and_web_measurements(self) -> None:
# make sure the transaction has some web measurements
self.transaction_data["measurements"] = {"lcp": {"value": 100}}
self.store_event(self.transaction_data, self.project.id)
response = self.do_request(
{
"project": [self.project.id],
"transaction": self.transaction_data["transaction"],
"type": "web",
}
)
assert response.status_code == 200, response.content
assert response.data == {"measurements": True}
def test_has_event_and_no_recent_mobile_measurements(self) -> None:
# make sure the event is older than 7 days
transaction_data = load_data("transaction", timestamp=before_now(days=8))
# make sure the transaction has some web measurements
transaction_data["measurements"] = {"app_start_cold": {"value": 100}}
self.store_event(transaction_data, self.project.id)
response = self.do_request(
{
"project": [self.project.id],
"transaction": self.transaction_data["transaction"],
"type": "mobile",
}
)
assert response.status_code == 200, response.content
assert response.data == {"measurements": False}
def test_has_event_and_mobile_measurements(self) -> None:
# make sure the transaction has some mobile measurements
self.transaction_data["measurements"] = {"app_start_cold": {"value": 100}}
self.store_event(self.transaction_data, self.project.id)
response = self.do_request(
{
"project": [self.project.id],
"transaction": self.transaction_data["transaction"],
"type": "mobile",
}
)
assert response.status_code == 200, response.content
assert response.data == {"measurements": True}
| OrganizationEventsHasMeasurementsTest |
python | PyCQA__pylint | tests/functional/a/alternative/alternative_union_syntax_error.py | {
"start": 3334,
"end": 3594
} | class ____:
pass
class_list = [WithForward | DefaultMetaclass]
class_list_reversed_invalid = [WithReverse | DefaultMetaclass] # [unsupported-binary-operation]
class_list_reversed_valid = [DefaultMetaclass | WithReverse]
# Pathological cases
| DefaultMetaclass |
python | numba__numba | numba/core/callconv.py | {
"start": 36635,
"end": 37551
} | class ____(ErrorModel):
"""
In the Numpy error model, floating-point errors don't raise an
exception. The FPU exception state is inspected by Numpy at the
end of a ufunc's execution and a warning is raised if appropriate.
Note there's no easy way to set the FPU exception state from LLVM.
Instructions known to set an FP exception can be optimized away:
https://llvm.org/bugs/show_bug.cgi?id=6050
http://lists.llvm.org/pipermail/llvm-dev/2014-September/076918.html
http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20140929/237997.html
"""
raise_on_fp_zero_division = False
error_models = {
'python': PythonErrorModel,
'numpy': NumpyErrorModel,
}
def create_error_model(model_name, context):
"""
Create an error model instance for the given target context.
"""
return error_models[model_name](context.call_conv)
| NumpyErrorModel |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/memberAccess13.py | {
"start": 123,
"end": 422
} | class ____:
produce: type[Mock] = Mock
reveal_type(MockProducer.produce, expected_text="type[Mock]")
reveal_type(MockProducer().produce, expected_text="type[Mock]")
reveal_type(MockProducer.produce(), expected_text="Mock")
reveal_type(MockProducer().produce(), expected_text="Mock")
| MockProducer |
python | doocs__leetcode | solution/2700-2799/2798.Number of Employees Who Met the Target/Solution.py | {
"start": 0,
"end": 146
} | class ____:
def numberOfEmployeesWhoMetTarget(self, hours: List[int], target: int) -> int:
return sum(x >= target for x in hours)
| Solution |
python | hyperopt__hyperopt | hyperopt/tests/unit/test_tpe.py | {
"start": 14649,
"end": 15047
} | class ____(unittest.TestCase, CasePerDomain):
def work(self):
# -- smoke test that things simply run,
# for each type of several search spaces.
trials = Trials()
fmin(
passthrough,
space=self.bandit.expr,
algo=partial(tpe.suggest, n_EI_candidates=3),
trials=trials,
max_evals=10,
)
| TestSuggest |
python | langchain-ai__langchain | libs/langchain/tests/unit_tests/output_parsers/test_yaml_parser.py | {
"start": 346,
"end": 2629
} | class ____(BaseModel):
action: Actions = Field(description="Action to be performed")
action_input: str = Field(description="Input to be used in the action")
additional_fields: str | None = Field(
description="Additional fields",
default=None,
)
for_new_lines: str = Field(description="To be used to test newlines")
# Prevent pytest from trying to run tests on TestModel
TestModel.__test__ = False # type: ignore[attr-defined]
DEF_RESULT = """```yaml
---
action: Update
action_input: The yamlOutputParser class is powerful
additional_fields: null
for_new_lines: |
not_escape_newline:
escape_newline:
```"""
DEF_RESULT_NO_BACKTICKS = """
action: Update
action_input: The yamlOutputParser class is powerful
additional_fields: null
for_new_lines: |
not_escape_newline:
escape_newline:
"""
# action 'update' with a lowercase 'u' to test schema validation failure.
DEF_RESULT_FAIL = """```yaml
action: update
action_input: The yamlOutputParser class is powerful
additional_fields: null
```"""
DEF_EXPECTED_RESULT = TestModel(
action=Actions.UPDATE,
action_input="The yamlOutputParser class is powerful",
additional_fields=None,
for_new_lines="not_escape_newline:\n escape_newline:\n",
)
@pytest.mark.parametrize("result", [DEF_RESULT, DEF_RESULT_NO_BACKTICKS])
def test_yaml_output_parser(result: str) -> None:
"""Test yamlOutputParser."""
yaml_parser: YamlOutputParser[TestModel] = YamlOutputParser(
pydantic_object=TestModel,
)
model = yaml_parser.parse(result)
print("parse_result:", result) # noqa: T201
assert model == DEF_EXPECTED_RESULT
def test_yaml_output_parser_fail() -> None:
"""Test YamlOutputParser where completion result fails schema validation."""
yaml_parser: YamlOutputParser[TestModel] = YamlOutputParser(
pydantic_object=TestModel,
)
with pytest.raises(OutputParserException) as exc_info:
yaml_parser.parse(DEF_RESULT_FAIL)
assert "Failed to parse TestModel from completion" in str(exc_info.value)
def test_yaml_output_parser_output_type() -> None:
"""Test YamlOutputParser OutputType."""
yaml_parser = YamlOutputParser[TestModel](pydantic_object=TestModel)
assert yaml_parser.OutputType is TestModel
| TestModel |
python | spyder-ide__spyder | spyder/plugins/toolbar/api.py | {
"start": 297,
"end": 513
} | class ____:
File = 'file_toolbar'
Run = 'run_toolbar'
Debug = 'debug_toolbar'
Profile = 'profile_toolbar'
Main = 'main_toolbar'
WorkingDirectory = 'working_directory_toolbar'
| ApplicationToolbars |
python | pydantic__pydantic | pydantic/networks.py | {
"start": 23024,
"end": 25232
} | class ____(_BaseMultiHostUrl):
"""A type that will accept any Postgres DSN.
* User info required
* TLD not required
* Host required
* Supports multiple hosts
If further validation is required, these properties can be used by validators to enforce specific behaviour:
```python
from pydantic import (
BaseModel,
HttpUrl,
PostgresDsn,
ValidationError,
field_validator,
)
class MyModel(BaseModel):
url: HttpUrl
m = MyModel(url='http://www.example.com')
# the repr() method for a url will display all properties of the url
print(repr(m.url))
#> HttpUrl('http://www.example.com/')
print(m.url.scheme)
#> http
print(m.url.host)
#> www.example.com
print(m.url.port)
#> 80
class MyDatabaseModel(BaseModel):
db: PostgresDsn
@field_validator('db')
def check_db_name(cls, v):
assert v.path and len(v.path) > 1, 'database must be provided'
return v
m = MyDatabaseModel(db='postgres://user:pass@localhost:5432/foobar')
print(m.db)
#> postgres://user:pass@localhost:5432/foobar
try:
MyDatabaseModel(db='postgres://user:pass@localhost:5432')
except ValidationError as e:
print(e)
'''
1 validation error for MyDatabaseModel
db
Assertion failed, database must be provided
assert (None)
+ where None = PostgresDsn('postgres://user:pass@localhost:5432').path [type=assertion_error, input_value='postgres://user:pass@localhost:5432', input_type=str]
'''
```
"""
_constraints = UrlConstraints(
host_required=True,
allowed_schemes=[
'postgres',
'postgresql',
'postgresql+asyncpg',
'postgresql+pg8000',
'postgresql+psycopg',
'postgresql+psycopg2',
'postgresql+psycopg2cffi',
'postgresql+py-postgresql',
'postgresql+pygresql',
],
)
@property
def host(self) -> str:
"""The required URL host."""
return self._url.host # pyright: ignore[reportAttributeAccessIssue]
| PostgresDsn |
python | ray-project__ray | python/ray/train/v2/api/context.py | {
"start": 5761,
"end": 6585
} | class ____(TrainContext):
"""Implementation of TrainContext for distributed mode."""
def get_experiment_name(self) -> str:
return get_internal_train_context().get_experiment_name()
def get_world_size(self) -> int:
return get_internal_train_context().get_world_size()
def get_world_rank(self) -> int:
return get_internal_train_context().get_world_rank()
def get_local_rank(self) -> int:
return get_internal_train_context().get_local_rank()
def get_local_world_size(self) -> int:
return get_internal_train_context().get_local_world_size()
def get_node_rank(self) -> int:
return get_internal_train_context().get_node_rank()
def get_storage(self):
return get_internal_train_context().get_storage()
@DeveloperAPI
| DistributedTrainContext |
python | google__jax | jax/_src/memory.py | {
"start": 596,
"end": 745
} | class ____(enum.Enum):
Device = enum.auto()
Host = enum.auto()
Any = enum.auto()
def __repr__(self):
return f"MemorySpace.{self.name}"
| Space |
python | django__django | tests/admin_views/models.py | {
"start": 12029,
"end": 12244
} | class ____(models.Model):
posted = models.DateField(default=link_posted_default)
url = models.URLField()
post = models.ForeignKey("Post", models.CASCADE)
readonly_link_content = models.TextField()
| Link |
python | walkccc__LeetCode | solutions/2131. Longest Palindrome by Concatenating Two Letter Words/2131.py | {
"start": 0,
"end": 393
} | class ____:
def longestPalindrome(self, words: list[str]) -> int:
ans = 0
count = [[0] * 26 for _ in range(26)]
for a, b in words:
i = ord(a) - ord('a')
j = ord(b) - ord('a')
if count[j][i]:
ans += 4
count[j][i] -= 1
else:
count[i][j] += 1
for i in range(26):
if count[i][i]:
return ans + 2
return ans
| Solution |
python | run-llama__llama_index | llama-index-integrations/embeddings/llama-index-embeddings-jinaai/llama_index/embeddings/jinaai/base.py | {
"start": 5345,
"end": 10579
} | class ____(MultiModalEmbedding):
"""
JinaAI class for embeddings.
Args:
model (str): Model for embedding.
Defaults to `jina-embeddings-v3`
"""
api_key: Optional[str] = Field(default=None, description="The JinaAI API key.")
model: str = Field(
default="jina-embeddings-v3",
description="The model to use when calling Jina AI API",
)
_encoding_queries: str = PrivateAttr()
_encoding_documents: str = PrivateAttr()
_task: str = PrivateAttr()
_api: Any = PrivateAttr()
def __init__(
self,
model: str = "jina-embeddings-v3",
embed_batch_size: int = DEFAULT_EMBED_BATCH_SIZE,
api_key: Optional[str] = None,
callback_manager: Optional[CallbackManager] = None,
encoding_queries: Optional[str] = None,
encoding_documents: Optional[str] = None,
task: Optional[str] = None,
dimensions: Optional[int] = None,
late_chunking: Optional[bool] = None,
**kwargs: Any,
) -> None:
super().__init__(
embed_batch_size=embed_batch_size,
callback_manager=callback_manager,
model=model,
api_key=api_key,
**kwargs,
)
self._encoding_queries = encoding_queries or "float"
self._encoding_documents = encoding_documents or "float"
self._task = task
self._dimensions = dimensions
self._late_chunking = late_chunking
assert self._encoding_documents in VALID_ENCODING, (
f"Encoding Documents parameter {self._encoding_documents} not supported. Please choose one of {VALID_ENCODING}"
)
assert self._encoding_queries in VALID_ENCODING, (
f"Encoding Queries parameter {self._encoding_documents} not supported. Please choose one of {VALID_ENCODING}"
)
self._api = _JinaAPICaller(model=model, api_key=api_key)
@classmethod
def class_name(cls) -> str:
return "JinaAIEmbedding"
def _get_query_embedding(self, query: str) -> List[float]:
"""Get query embedding."""
return self._api.get_embeddings(
input=[query],
encoding_type=self._encoding_queries,
task=self._task,
dimensions=self._dimensions,
late_chunking=self._late_chunking,
)[0]
async def _aget_query_embedding(self, query: str) -> List[float]:
"""The asynchronous version of _get_query_embedding."""
result = await self._api.aget_embeddings(
input=[query],
encoding_type=self._encoding_queries,
task=self._task,
dimensions=self._dimensions,
late_chunking=self._late_chunking,
)
return result[0]
def _get_text_embedding(self, text: str) -> List[float]:
"""Get text embedding."""
return self._get_text_embeddings([text])[0]
async def _aget_text_embedding(self, text: str) -> List[float]:
"""Asynchronously get text embedding."""
result = await self._aget_text_embeddings([text])
return result[0]
def _get_text_embeddings(self, texts: List[str]) -> List[List[float]]:
return self._api.get_embeddings(
input=texts,
encoding_type=self._encoding_documents,
task=self._task,
dimensions=self._dimensions,
late_chunking=self._late_chunking,
)
async def _aget_text_embeddings(
self,
texts: List[str],
) -> List[List[float]]:
return await self._api.aget_embeddings(
input=texts,
encoding_type=self._encoding_documents,
task=self._task,
dimensions=self._dimensions,
late_chunking=self._late_chunking,
)
def _get_image_embedding(self, img_file_path: ImageType) -> List[float]:
if is_local(img_file_path):
input = [{"bytes": get_bytes_str(img_file_path)}]
else:
input = [{"url": img_file_path}]
return self._api.get_embeddings(input=input)[0]
async def _aget_image_embedding(self, img_file_path: ImageType) -> List[float]:
if is_local(img_file_path):
input = [{"bytes": get_bytes_str(img_file_path)}]
else:
input = [{"url": img_file_path}]
return await self._api.aget_embeddings(input=input)[0]
def _get_image_embeddings(
self, img_file_paths: List[ImageType]
) -> List[List[float]]:
input = []
for img_file_path in img_file_paths:
if is_local(img_file_path):
input.append({"bytes": get_bytes_str(img_file_path)})
else:
input.append({"url": img_file_path})
return self._api.get_embeddings(input=input)
async def _aget_image_embeddings(
self, img_file_paths: List[ImageType]
) -> List[List[float]]:
input = []
for img_file_path in img_file_paths:
if is_local(img_file_path):
input.append({"bytes": get_bytes_str(img_file_path)})
else:
input.append({"url": img_file_path})
return await self._api.aget_embeddings(input=input)
| JinaEmbedding |
python | numpy__numpy | numpy/polynomial/polynomial.py | {
"start": 50419,
"end": 52667
} | class ____(ABCPolyBase):
"""A power series class.
The Polynomial class provides the standard Python numerical methods
'+', '-', '*', '//', '%', 'divmod', '**', and '()' as well as the
attributes and methods listed below.
Parameters
----------
coef : array_like
Polynomial coefficients in order of increasing degree, i.e.,
``(1, 2, 3)`` give ``1 + 2*x + 3*x**2``.
domain : (2,) array_like, optional
Domain to use. The interval ``[domain[0], domain[1]]`` is mapped
to the interval ``[window[0], window[1]]`` by shifting and scaling.
The default value is [-1., 1.].
window : (2,) array_like, optional
Window, see `domain` for its use. The default value is [-1., 1.].
symbol : str, optional
Symbol used to represent the independent variable in string
representations of the polynomial expression, e.g. for printing.
The symbol must be a valid Python identifier. Default value is 'x'.
.. versionadded:: 1.24
"""
# Virtual Functions
_add = staticmethod(polyadd)
_sub = staticmethod(polysub)
_mul = staticmethod(polymul)
_div = staticmethod(polydiv)
_pow = staticmethod(polypow)
_val = staticmethod(polyval)
_int = staticmethod(polyint)
_der = staticmethod(polyder)
_fit = staticmethod(polyfit)
_line = staticmethod(polyline)
_roots = staticmethod(polyroots)
_fromroots = staticmethod(polyfromroots)
# Virtual properties
domain = np.array(polydomain)
window = np.array(polydomain)
basis_name = None
@classmethod
def _str_term_unicode(cls, i, arg_str):
if i == '1':
return f"·{arg_str}"
else:
return f"·{arg_str}{i.translate(cls._superscript_mapping)}"
@staticmethod
def _str_term_ascii(i, arg_str):
if i == '1':
return f" {arg_str}"
else:
return f" {arg_str}**{i}"
@staticmethod
def _repr_latex_term(i, arg_str, needs_parens):
if needs_parens:
arg_str = rf"\left({arg_str}\right)"
if i == 0:
return '1'
elif i == 1:
return arg_str
else:
return f"{arg_str}^{{{i}}}"
| Polynomial |
python | kamyu104__LeetCode-Solutions | Python/intersection-of-multiple-arrays.py | {
"start": 123,
"end": 595
} | class ____(object):
def intersection(self, nums):
"""
:type nums: List[List[int]]
:rtype: List[int]
"""
MAX_NUM = 1000
cnt = [0]*(MAX_NUM+1)
for num in nums:
for x in num:
cnt[x] += 1
return [i for i in xrange(1, MAX_NUM+1) if cnt[i] == len(nums)]
# Time: O(n * l + r), n = len(nums), l = len(nums[0]), r = max(nums)-min(nums)
# Space: O(l)
# hash table, counting sort
| Solution |
python | PyCQA__pylint | tests/functional/i/invalid/invalid_str_returned.py | {
"start": 708,
"end": 829
} | class ____:
""" __str__ returns int """
def __str__(self): # [invalid-str-returned]
return 1
| SecondBadStr |
python | GokuMohandas__MadeWithML | madewithml/predict.py | {
"start": 1357,
"end": 5393
} | class ____:
def __init__(self, preprocessor, model):
self.preprocessor = preprocessor
self.model = model
self.model.eval()
def __call__(self, batch):
results = self.model.predict(collate_fn(batch))
return {"output": results}
def predict_proba(self, batch):
results = self.model.predict_proba(collate_fn(batch))
return {"output": results}
def get_preprocessor(self):
return self.preprocessor
@classmethod
def from_checkpoint(cls, checkpoint):
metadata = checkpoint.get_metadata()
preprocessor = CustomPreprocessor(class_to_index=metadata["class_to_index"])
model = FinetunedLLM.load(Path(checkpoint.path, "args.json"), Path(checkpoint.path, "model.pt"))
return cls(preprocessor=preprocessor, model=model)
def predict_proba(
ds: ray.data.dataset.Dataset,
predictor: TorchPredictor,
) -> List: # pragma: no cover, tested with inference workload
"""Predict tags (with probabilities) for input data from a dataframe.
Args:
df (pd.DataFrame): dataframe with input features.
predictor (TorchPredictor): loaded predictor from a checkpoint.
Returns:
List: list of predicted labels.
"""
preprocessor = predictor.get_preprocessor()
preprocessed_ds = preprocessor.transform(ds)
outputs = preprocessed_ds.map_batches(predictor.predict_proba)
y_prob = np.array([d["output"] for d in outputs.take_all()])
results = []
for i, prob in enumerate(y_prob):
tag = preprocessor.index_to_class[prob.argmax()]
results.append({"prediction": tag, "probabilities": format_prob(prob, preprocessor.index_to_class)})
return results
@app.command()
def get_best_run_id(experiment_name: str = "", metric: str = "", mode: str = "") -> str: # pragma: no cover, mlflow logic
"""Get the best run_id from an MLflow experiment.
Args:
experiment_name (str): name of the experiment.
metric (str): metric to filter by.
mode (str): direction of metric (ASC/DESC).
Returns:
str: best run id from experiment.
"""
sorted_runs = mlflow.search_runs(
experiment_names=[experiment_name],
order_by=[f"metrics.{metric} {mode}"],
)
run_id = sorted_runs.iloc[0].run_id
print(run_id)
return run_id
def get_best_checkpoint(run_id: str) -> TorchCheckpoint: # pragma: no cover, mlflow logic
"""Get the best checkpoint from a specific run.
Args:
run_id (str): ID of the run to get the best checkpoint from.
Returns:
TorchCheckpoint: Best checkpoint from the run.
"""
artifact_dir = urlparse(mlflow.get_run(run_id).info.artifact_uri).path # get path from mlflow
results = Result.from_path(artifact_dir)
return results.best_checkpoints[0][0]
@app.command()
def predict(
run_id: Annotated[str, typer.Option(help="id of the specific run to load from")] = None,
title: Annotated[str, typer.Option(help="project title")] = None,
description: Annotated[str, typer.Option(help="project description")] = None,
) -> Dict: # pragma: no cover, tested with inference workload
"""Predict the tag for a project given it's title and description.
Args:
run_id (str): id of the specific run to load from. Defaults to None.
title (str, optional): project title. Defaults to "".
description (str, optional): project description. Defaults to "".
Returns:
Dict: prediction results for the input data.
"""
# Load components
best_checkpoint = get_best_checkpoint(run_id=run_id)
predictor = TorchPredictor.from_checkpoint(best_checkpoint)
# Predict
sample_ds = ray.data.from_items([{"title": title, "description": description, "tag": "other"}])
results = predict_proba(ds=sample_ds, predictor=predictor)
logger.info(json.dumps(results, cls=NumpyEncoder, indent=2))
return results
if __name__ == "__main__": # pragma: no cover, application
app()
| TorchPredictor |
python | nedbat__coveragepy | coverage/debug.py | {
"start": 4029,
"end": 12140
} | class ____(NoDebugging):
"""A DebugControl that won't write anywhere."""
def write(self, msg: str, *, exc: BaseException | None = None) -> None:
pass
def info_header(label: str) -> str:
"""Make a nice header string."""
return "--{:-<60s}".format(" " + label + " ")
def info_formatter(info: Iterable[tuple[str, Any]]) -> Iterable[str]:
"""Produce a sequence of formatted lines from info.
`info` is a sequence of pairs (label, data). The produced lines are
nicely formatted, ready to print.
"""
info = list(info)
if not info:
return
LABEL_LEN = 30
assert all(len(l) < LABEL_LEN for l, _ in info)
for label, data in info:
if data == []:
data = "-none-"
prefix = f"{label:>{LABEL_LEN}}: "
match data:
case tuple() if len(str(data)) < 30:
yield f"{prefix}{data}"
case tuple() | list() | set():
for e in data:
yield f"{prefix}{e}"
prefix = " " * (LABEL_LEN + 2)
case _:
yield f"{prefix}{data}"
def write_formatted_info(
write: Callable[[str], None],
header: str,
info: Iterable[tuple[str, Any]],
) -> None:
"""Write a sequence of (label,data) pairs nicely.
`write` is a function write(str) that accepts each line of output.
`header` is a string to start the section. `info` is a sequence of
(label, data) pairs, where label is a str, and data can be a single
value, or a list/set/tuple.
"""
write(info_header(header))
for line in info_formatter(info):
write(f" {line}")
def exc_one_line(exc: Exception) -> str:
"""Get a one-line summary of an exception, including class name and message."""
lines = traceback.format_exception_only(type(exc), exc)
return "|".join(l.rstrip() for l in lines)
_FILENAME_REGEXES: list[tuple[str, str]] = [
(r".*[/\\]pytest-of-.*[/\\]pytest-\d+([/\\]popen-gw\d+)?", "tmp:"),
]
_FILENAME_SUBS: list[tuple[str, str]] = []
@overload
def short_filename(filename: str) -> str:
pass
@overload
def short_filename(filename: None) -> None:
pass
def short_filename(filename: str | None) -> str | None:
"""Shorten a file name. Directories are replaced by prefixes like 'syspath:'"""
if not _FILENAME_SUBS:
for pathdir in sys.path:
_FILENAME_SUBS.append((pathdir, "syspath:"))
import coverage
_FILENAME_SUBS.append((os.path.dirname(coverage.__file__), "cov:"))
_FILENAME_SUBS.sort(key=(lambda pair: len(pair[0])), reverse=True)
if filename is not None:
for pat, sub in _FILENAME_REGEXES:
filename = re.sub(pat, sub, filename)
for before, after in _FILENAME_SUBS:
filename = filename.replace(before, after)
return filename
def file_summary(filename: str) -> str:
"""A one-line summary of a file, for log messages."""
try:
s = os.stat(filename)
except FileNotFoundError:
summary = "does not exist"
except Exception as e:
summary = f"error: {e}"
else:
mod = datetime.datetime.fromtimestamp(s.st_mtime)
summary = f"{s.st_size} bytes, modified {mod}"
return summary
def short_stack(
skip: int = 0,
full: bool = False,
frame_ids: bool = False,
short_filenames: bool = False,
) -> str:
"""Return a string summarizing the call stack.
The string is multi-line, with one line per stack frame. Each line shows
the function name, the file name, and the line number:
...
start_import_stop : /Users/ned/coverage/trunk/tests/coveragetest.py:95
import_local_file : /Users/ned/coverage/trunk/tests/coveragetest.py:81
import_local_file : /Users/ned/coverage/trunk/coverage/backward.py:159
...
`skip` is the number of closest immediate frames to skip, so that debugging
functions can call this and not be included in the result.
If `full` is true, then include all frames. Otherwise, initial "boring"
frames (ones in site-packages and earlier) are omitted.
`short_filenames` will shorten filenames using `short_filename`, to reduce
the amount of repetitive noise in stack traces.
"""
# Regexes in initial frames that we don't care about.
# fmt: off
BORING_PRELUDE = [
"<string>", # pytest-xdist has string execution.
r"\bigor.py$", # Our test runner.
r"\bsite-packages\b", # pytest etc getting to our tests.
]
# fmt: on
stack: Iterable[inspect.FrameInfo] = inspect.stack()[:skip:-1]
if not full:
for pat in BORING_PRELUDE:
stack = itertools.dropwhile(
(lambda fi, pat=pat: re.search(pat, fi.filename)), # type: ignore[misc]
stack,
)
lines = []
for frame_info in stack:
line = f"{frame_info.function:>30s} : "
if frame_ids:
line += f"{id(frame_info.frame):#x} "
filename = frame_info.filename
if short_filenames:
filename = short_filename(filename)
line += f"{filename}:{frame_info.lineno}"
lines.append(line)
return "\n".join(lines)
def dump_stack_frames(out: TWritable, skip: int = 0) -> None:
"""Print a summary of the stack to `out`."""
out.write(short_stack(skip=skip + 1) + "\n")
def clipped_repr(text: str, numchars: int = 50) -> str:
"""`repr(text)`, but limited to `numchars`."""
r = reprlib.Repr()
r.maxstring = numchars
return r.repr(text)
def short_id(id64: int) -> int:
"""Given a 64-bit id, make a shorter 16-bit one."""
id16 = 0
for offset in range(0, 64, 16):
id16 ^= id64 >> offset
return id16 & 0xFFFF
def add_pid_and_tid(text: str) -> str:
"""A filter to add pid and tid to debug messages."""
# Thread ids are useful, but too long. Make a shorter one.
tid = f"{short_id(_thread.get_ident()):04x}"
text = f"{os.getpid():5d}.{tid}: {text}"
return text
AUTO_REPR_IGNORE = {"$coverage.object_id"}
def auto_repr(self: Any) -> str:
"""A function implementing an automatic __repr__ for debugging."""
show_attrs = (
(k, v)
for k, v in self.__dict__.items()
if getattr(v, "show_repr_attr", True)
and not inspect.ismethod(v)
and k not in AUTO_REPR_IGNORE
)
return "<{klass} @{id:#x}{attrs}>".format(
klass=self.__class__.__name__,
id=id(self),
attrs="".join(f" {k}={v!r}" for k, v in show_attrs),
)
def simplify(v: Any) -> Any: # pragma: debugging
"""Turn things which are nearly dict/list/etc into dict/list/etc."""
if isinstance(v, dict):
return {k: simplify(vv) for k, vv in v.items()}
elif isinstance(v, (list, tuple)):
return type(v)(simplify(vv) for vv in v)
elif hasattr(v, "__dict__"):
return simplify({"." + k: v for k, v in v.__dict__.items()})
else:
return v
def ppformat(v: Any) -> str: # pragma: debugging
"""Debug helper to pretty-print data, including SimpleNamespace objects."""
return pprint.pformat(simplify(v), indent=4, compact=True, sort_dicts=True, width=140)
def pp(v: Any) -> None: # pragma: debugging
"""Debug helper to pretty-print data, including SimpleNamespace objects."""
print(ppformat(v))
def filter_text(text: str, filters: Iterable[Callable[[str], str]]) -> str:
"""Run `text` through a series of filters.
`filters` is a list of functions. Each takes a string and returns a
string. Each is run in turn. After each filter, the text is split into
lines, and each line is passed through the next filter.
Returns: the final string that results after all of the filters have
run.
"""
clean_text = text.rstrip()
ending = text[len(clean_text) :]
text = clean_text
for filter_fn in filters:
lines = []
for line in text.splitlines():
lines.extend(filter_fn(line).splitlines())
text = "\n".join(lines)
return text + ending
| DevNullDebug |
python | viewflow__viewflow | viewflow/workflow/nodes/join.py | {
"start": 229,
"end": 4504
} | class ____(mixins.NextNodeActivationMixin, Activation):
"""Activation for parallel Join node."""
type: str = "join"
def __init__(self, *args, **kwargs): # noqa D102
self.next_task = None
super().__init__(*args, **kwargs)
@classmethod
def create(cls, flow_task, prev_activation, token, data=None, seed=None):
"""
Join and, if all incoming paths are completed, continue execution.
Join task is created on the first activation. Subsequent
activations will look for an existing Join Task instance.
"""
flow_class = flow_task.flow_class
task_class = flow_class.task_class
# lookup for an active join task instance
tasks = task_class._default_manager.filter(
flow_task=flow_task,
process=prev_activation.process,
status__in=[STATUS.NEW, STATUS.STARTED],
)
if len(tasks) > 1:
raise FlowRuntimeError("More than one join instance for process found")
task = tasks.first()
if not task:
# Create new Join Node
if token.is_split_token():
token = token.get_base_split_token()
task = flow_class.task_class(
process=prev_activation.process,
flow_task=flow_task,
token=token,
)
task.data = data if data is not None else {}
task.seed = seed
task.save()
else:
# todo resolve task_data and seed
pass
task.previous.add(prev_activation.task)
activation = cls(task)
return activation
@Activation.status.transition(source=STATUS.NEW, target=STATUS.STARTED)
@Activation.status.transition(source=STATUS.STARTED)
def activate(self):
if self.task.started is None:
self.task.started = now()
self.task.save()
@Activation.status.transition(
source=STATUS.STARTED, target=STATUS.DONE, conditions=[this.is_done]
)
def complete(self):
"""Complete the join task and create next."""
# with self.exception_guard(): TODO exception guard on join ??
super().complete.original()
def cancel_active_tasks(self, active_tasks):
activations = [task.flow_task.activation_class(task) for task in active_tasks]
not_cancellable = [
activation
for activation in activations
if not activation.cancel.can_proceed()
]
if not_cancellable:
raise FlowRuntimeError(
"Can't cancel {}".format(
",".join(activation.task for activation in not_cancellable)
)
)
for activation in activations:
activation.cancel()
def is_done(self):
"""
Check that process can be continued further.
Join check the all task state in db with the common token prefix.
Join node would continue execution if all incoming tasks are DONE or CANCELED.
"""
join_prefixes = set(
prev.token.get_common_split_prefix(self.task.token, prev.pk)
for prev in self.task.previous.exclude(
status__in=[STATUS.CANCELED, STATUS.REVIVED]
).all()
)
if len(join_prefixes) > 1:
raise FlowRuntimeError(
f"Multiple tokens {join_prefixes} came to join { self.flow_task.name}"
)
join_token_prefix = next(iter(join_prefixes))
active_tasks = self.flow_class.task_class._default_manager.filter(
process=self.process, token__startswith=join_token_prefix
).exclude(status__in=[STATUS.DONE, STATUS.CANCELED, STATUS.REVIVED])
if self.flow_task._continue_on_condition:
continue_result = self.flow_task._continue_on_condition(self, active_tasks)
if continue_result:
self.cancel_active_tasks(active_tasks)
return True
return not active_tasks.exists()
@Activation.status.transition(
source=[STATUS.NEW, STATUS.STARTED], target=STATUS.CANCELED
)
def cancel(self):
self.task.finished = now()
self.task.save()
| JoinActivation |
python | gevent__gevent | src/greentest/3.14/test_httpservers.py | {
"start": 2776,
"end": 3646
} | class ____(unittest.TestCase):
# Optional tuple (certfile, keyfile, password) to use for HTTPS servers.
tls = None
def setUp(self):
self._threads = threading_helper.threading_setup()
os.environ = os_helper.EnvironmentVarGuard()
self.server_started = threading.Event()
self.thread = TestServerThread(self, self.request_handler, self.tls)
self.thread.start()
self.server_started.wait()
def tearDown(self):
self.thread.stop()
self.thread = None
os.environ.__exit__()
threading_helper.threading_cleanup(*self._threads)
def request(self, uri, method='GET', body=None, headers={}):
self.connection = http.client.HTTPConnection(self.HOST, self.PORT)
self.connection.request(method, uri, body, headers)
return self.connection.getresponse()
| BaseTestCase |
python | huggingface__transformers | src/transformers/models/esm/configuration_esm.py | {
"start": 871,
"end": 2574
} | class ____:
"""
Args:
sequence_dim:
Single representation channel dimension
pairwise_dim:
Pair representation channel dimension
ipa_dim:
IPA hidden channel dimension
resnet_dim:
Angle resnet (Alg. 23 lines 11-14) hidden channel dimension
num_heads_ipa:
Number of IPA heads
num_qk_points:
Number of query/key points to generate during IPA
num_v_points:
Number of value points to generate during IPA
dropout_rate:
Dropout rate used throughout the layer
num_blocks:
Number of structure module blocks
num_transition_layers:
Number of layers in the single representation transition (Alg. 23 lines 8-9)
num_resnet_blocks:
Number of blocks in the angle resnet
num_angles:
Number of angles to generate in the angle resnet
trans_scale_factor:
Scale of single representation transition hidden dimension
epsilon:
Small number used in angle resnet normalization
inf:
Large number used for attention masking
"""
sequence_dim: int = 384
pairwise_dim: int = 128
ipa_dim: int = 16
resnet_dim: int = 128
num_heads_ipa: int = 12
num_qk_points: int = 4
num_v_points: int = 8
dropout_rate: float = 0.1
num_blocks: int = 8
num_transition_layers: int = 1
num_resnet_blocks: int = 2
num_angles: int = 7
trans_scale_factor: int = 10
epsilon: float = 1e-8
inf: float = 1e5
def to_dict(self):
return asdict(self)
@dataclass
| StructureModuleConfig |
python | coleifer__peewee | tests/pwiz_integration.py | {
"start": 853,
"end": 1095
} | class ____(TestModel):
spaces = CharField(column_name='s p aces')
symbols = CharField(column_name='w/-nug!')
camelCaseName = CharField(column_name='camelCaseName')
class Meta:
table_name = 'oddColumnNames'
| OddColumnNames |
python | scipy__scipy | scipy/interpolate/tests/test_fitpack2.py | {
"start": 17361,
"end": 23257
} | class ____:
# NOTE: The systems in this test class are rank-deficient
def test_linear_constant(self):
x = [1,1,1,2,2,2,3,3,3]
y = [1,2,3,1,2,3,1,2,3]
z = [3,3,3,3,3,3,3,3,3]
s = 0.1
tx = [1+s,3-s]
ty = [1+s,3-s]
with pytest.warns(UserWarning, match="\nThe coefficients of the spline") as r:
lut = LSQBivariateSpline(x,y,z,tx,ty,kx=1,ky=1)
assert len(r) == 1
assert_almost_equal(lut(2, 2), np.asarray(3.))
def test_bilinearity(self):
x = [1,1,1,2,2,2,3,3,3]
y = [1,2,3,1,2,3,1,2,3]
z = [0,7,8,3,4,7,1,3,4]
s = 0.1
tx = [1+s,3-s]
ty = [1+s,3-s]
with pytest.warns(UserWarning, match="\nThe coefficients of the spline"):
# This seems to fail (ier=1, see ticket 1642).
lut = LSQBivariateSpline(x,y,z,tx,ty,kx=1,ky=1)
tx, ty = lut.get_knots()
for xa, xb in zip(tx[:-1], tx[1:]):
for ya, yb in zip(ty[:-1], ty[1:]):
for t in [0.1, 0.5, 0.9]:
for s in [0.3, 0.4, 0.7]:
xp = xa*(1-t) + xb*t
yp = ya*(1-s) + yb*s
zp = (+ lut(xa, ya)*(1-t)*(1-s)
+ lut(xb, ya)*t*(1-s)
+ lut(xa, yb)*(1-t)*s
+ lut(xb, yb)*t*s)
assert_almost_equal(lut(xp,yp), zp)
def test_integral(self):
x = [1,1,1,2,2,2,8,8,8]
y = [1,2,3,1,2,3,1,2,3]
z = array([0,7,8,3,4,7,1,3,4])
s = 0.1
tx = [1+s,3-s]
ty = [1+s,3-s]
with pytest.warns(UserWarning, match="\nThe coefficients of the spline") as r:
lut = LSQBivariateSpline(x, y, z, tx, ty, kx=1, ky=1)
assert len(r) == 1
tx, ty = lut.get_knots()
tz = lut(tx, ty)
trpz = .25*(diff(tx)[:,None]*diff(ty)[None,:]
* (tz[:-1,:-1]+tz[1:,:-1]+tz[:-1,1:]+tz[1:,1:])).sum()
assert_almost_equal(np.asarray(lut.integral(tx[0], tx[-1], ty[0], ty[-1])),
np.asarray(trpz))
def test_empty_input(self):
# Test whether empty inputs returns an empty output. Ticket 1014
x = [1,1,1,2,2,2,3,3,3]
y = [1,2,3,1,2,3,1,2,3]
z = [3,3,3,3,3,3,3,3,3]
s = 0.1
tx = [1+s,3-s]
ty = [1+s,3-s]
with pytest.warns(UserWarning, match="\nThe coefficients of the spline") as r:
lut = LSQBivariateSpline(x, y, z, tx, ty, kx=1, ky=1)
assert len(r) == 1
xp_assert_equal(lut([], []), np.zeros((0,0)))
xp_assert_equal(lut([], [], grid=False), np.zeros((0,)))
def test_invalid_input(self):
s = 0.1
tx = [1 + s, 3 - s]
ty = [1 + s, 3 - s]
with assert_raises(ValueError) as info:
x = np.linspace(1.0, 10.0)
y = np.linspace(1.0, 10.0)
z = np.linspace(1.0, 10.0, num=10)
LSQBivariateSpline(x, y, z, tx, ty)
assert "x, y, and z should have a same length" in str(info.value)
with assert_raises(ValueError) as info:
x = np.linspace(1.0, 10.0)
y = np.linspace(1.0, 10.0)
z = np.linspace(1.0, 10.0)
w = np.linspace(1.0, 10.0, num=20)
LSQBivariateSpline(x, y, z, tx, ty, w=w)
assert "x, y, z, and w should have a same length" in str(info.value)
with assert_raises(ValueError) as info:
w = np.linspace(-1.0, 10.0)
LSQBivariateSpline(x, y, z, tx, ty, w=w)
assert "w should be positive" in str(info.value)
with assert_raises(ValueError) as info:
bbox = (-100, 100, -100)
LSQBivariateSpline(x, y, z, tx, ty, bbox=bbox)
assert "bbox shape should be (4,)" in str(info.value)
with assert_raises(ValueError) as info:
LSQBivariateSpline(x, y, z, tx, ty, kx=10, ky=10)
assert "The length of x, y and z should be at least (kx+1) * (ky+1)" in \
str(info.value)
with assert_raises(ValueError) as exc_info:
LSQBivariateSpline(x, y, z, tx, ty, eps=0.0)
assert "eps should be between (0, 1)" in str(exc_info.value)
with assert_raises(ValueError) as exc_info:
LSQBivariateSpline(x, y, z, tx, ty, eps=1.0)
assert "eps should be between (0, 1)" in str(exc_info.value)
def test_array_like_input(self):
s = 0.1
tx = np.array([1 + s, 3 - s])
ty = np.array([1 + s, 3 - s])
x = np.linspace(1.0, 10.0)
y = np.linspace(1.0, 10.0)
z = np.linspace(1.0, 10.0)
w = np.linspace(1.0, 10.0)
bbox = np.array([1.0, 10.0, 1.0, 10.0])
with pytest.warns(UserWarning, match="\nThe coefficients of the spline") as r:
# np.array input
spl1 = LSQBivariateSpline(x, y, z, tx, ty, w=w, bbox=bbox)
# list input
spl2 = LSQBivariateSpline(x.tolist(), y.tolist(), z.tolist(),
tx.tolist(), ty.tolist(), w=w.tolist(),
bbox=bbox)
xp_assert_close(spl1(2.0, 2.0), spl2(2.0, 2.0))
assert len(r) == 2
def test_unequal_length_of_knots(self):
"""Test for the case when the input knot-location arrays in x and y are
of different lengths.
"""
x, y = np.mgrid[0:100, 0:100]
x = x.ravel()
y = y.ravel()
z = 3.0 * np.ones_like(x)
tx = np.linspace(0.1, 98.0, 29)
ty = np.linspace(0.1, 98.0, 33)
with pytest.warns(UserWarning, match="\nThe coefficients of the spline") as r:
lut = LSQBivariateSpline(x,y,z,tx,ty)
assert len(r) == 1
assert_almost_equal(lut(x, y, grid=False), z)
| TestLSQBivariateSpline |
python | ansible__ansible | test/integration/targets/jinja_plugins/collections/ansible_collections/foo/bar/plugins/test/good_collection_test.py | {
"start": 180,
"end": 299
} | class ____:
def tests(self):
return {
'world': lambda x: x.lower() == 'world',
}
| TestModule |
python | bokeh__bokeh | tests/unit/bokeh/embed/test_server__embed.py | {
"start": 10723,
"end": 10944
} | class ____:
def test_root(self) -> None:
assert bes._process_app_path("/") == ""
def test_arg(self) -> None:
assert bes._process_app_path("/stuff") == "&bokeh-app-path=/stuff"
| Test__process_app_path |
python | kamyu104__LeetCode-Solutions | Python/maximum-number-of-occurrences-of-a-substring.py | {
"start": 88,
"end": 1085
} | class ____(object):
def maxFreq(self, s, maxLetters, minSize, maxSize):
"""
:type s: str
:type maxLetters: int
:type minSize: int
:type maxSize: int
:rtype: int
"""
M, p = 10**9+7, 113
power, rolling_hash = pow(p, minSize-1, M), 0
left = 0
lookup, count = collections.defaultdict(int), collections.defaultdict(int)
for right in xrange(len(s)):
count[s[right]] += 1
if right-left+1 > minSize:
count[s[left]] -= 1
rolling_hash = (rolling_hash - ord(s[left])*power) % M
if count[s[left]] == 0:
count.pop(s[left])
left += 1
rolling_hash = (rolling_hash*p + ord(s[right])) % M
if right-left+1 == minSize and len(count) <= maxLetters:
lookup[rolling_hash] += 1
return max(lookup.values() or [0])
# Time: O(m * n), m = 26
# Space: O(m * n)
| Solution |
python | apache__airflow | task-sdk-integration-tests/tests/task_sdk_tests/jwt_plugin.py | {
"start": 977,
"end": 3665
} | class ____:
"""Generator for JWT tokens used in Task SDK API authentication."""
def __init__(self):
"""Initialize JWT configuration from environment variables."""
self.secret = os.getenv("AIRFLOW__API_AUTH__JWT_SECRET", "test-secret-key-for-testing")
self.issuer = os.getenv("AIRFLOW__API_AUTH__JWT_ISSUER", "airflow-test")
self.audience = os.getenv("AIRFLOW__API_AUTH__JWT_AUDIENCE", "urn:airflow.apache.org:task")
self.algorithm = os.getenv("AIRFLOW__API_AUTH__JWT_ALGORITHM", "HS512")
self.kid = os.getenv("AIRFLOW__API_AUTH__JWT_KID", "test-key-id")
def generate_token(
self,
task_instance_id: str,
expires_in_seconds: int = 3600,
extra_claims: dict[str, Any] | None = None,
extra_headers: dict[str, Any] | None = None,
) -> str:
"""
Generate a JWT token for task instance authentication.
Args:
task_instance_id: The task instance ID to use as the 'sub' claim
expires_in_seconds: Token expiration time in seconds (default: 1 hour)
extra_claims: Additional claims to include in the token
extra_headers: Additional headers to include in the token
Returns:
JWT token as a string
"""
now = int(datetime.now(timezone.utc).timestamp())
claims = {
"jti": uuid.uuid4().hex,
"iss": self.issuer,
"aud": self.audience,
"nbf": now,
"exp": now + expires_in_seconds,
"iat": now,
"sub": task_instance_id,
}
# Remove audience if not set
if not claims.get("aud"):
del claims["aud"]
# Add extra claims if provided
if extra_claims:
claims.update(extra_claims)
# Base JWT headers
headers = {
"alg": self.algorithm,
"kid": self.kid,
}
# Add extra headers if provided
if extra_headers:
headers.update(extra_headers)
# Generate and return the token
token = jwt.encode(claims, self.secret, algorithm=self.algorithm, headers=headers)
return token
def generate_jwt_token(task_instance_id: str, expires_in_seconds: int = 3600) -> str:
"""
Convenience function to generate a JWT token.
Args:
task_instance_id: The task instance ID to use as the 'sub' claim
expires_in_seconds: Token expiration time in seconds (default: 1 hour)
Returns:
JWT token as a string
"""
generator = JWTTokenGenerator()
return generator.generate_token(task_instance_id, expires_in_seconds)
| JWTTokenGenerator |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 190086,
"end": 190597
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("subscribable_id", "state", "client_mutation_id")
subscribable_id = sgqlc.types.Field(
sgqlc.types.non_null(ID), graphql_name="subscribableId"
)
state = sgqlc.types.Field(
sgqlc.types.non_null(SubscriptionState), graphql_name="state"
)
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
| UpdateSubscriptionInput |
python | python-openxml__python-docx | tests/opc/test_package.py | {
"start": 703,
"end": 10615
} | class ____:
"""Unit-test suite for `docx.opc.package.OpcPackage` objects."""
def it_can_open_a_pkg_file(self, PackageReader_, PartFactory_, Unmarshaller_):
# mockery ----------------------
pkg_file = Mock(name="pkg_file")
pkg_reader = PackageReader_.from_file.return_value
# exercise ---------------------
pkg = OpcPackage.open(pkg_file)
# verify -----------------------
PackageReader_.from_file.assert_called_once_with(pkg_file)
Unmarshaller_.unmarshal.assert_called_once_with(pkg_reader, pkg, PartFactory_)
assert isinstance(pkg, OpcPackage)
def it_initializes_its_rels_collection_on_first_reference(self, Relationships_):
pkg = OpcPackage()
rels = pkg.rels
Relationships_.assert_called_once_with(PACKAGE_URI.baseURI)
assert rels == Relationships_.return_value
def it_can_add_a_relationship_to_a_part(self, rels_prop_: Mock, rels_: Mock, part_: Mock):
rels_prop_.return_value = rels_
pkg = OpcPackage()
pkg.load_rel("http://rel/type", part_, "rId99")
rels_.add_relationship.assert_called_once_with("http://rel/type", part_, "rId99", False)
def it_can_establish_a_relationship_to_another_part(
self, rels_prop_: Mock, rels_: Mock, rel_: Mock, part_: Mock
):
rel_.rId = "rId99"
rels_.get_or_add.return_value = rel_
rels_prop_.return_value = rels_
pkg = OpcPackage()
rId = pkg.relate_to(part_, "http://rel/type")
rels_.get_or_add.assert_called_once_with("http://rel/type", part_)
assert rId == "rId99"
def it_can_provide_a_list_of_the_parts_it_contains(self):
# mockery ----------------------
parts = [Mock(name="part1"), Mock(name="part2")]
pkg = OpcPackage()
# verify -----------------------
with patch.object(OpcPackage, "iter_parts", return_value=parts):
assert pkg.parts == [parts[0], parts[1]]
def it_can_iterate_over_parts_by_walking_rels_graph(self, rels_prop_: Mock):
# +----------+ +--------+
# | pkg_rels |-----> | part_1 |
# +----------+ +--------+
# | | ^
# v v |
# external +--------+
# | part_2 |
# +--------+
part1, part2 = (Mock(name="part1"), Mock(name="part2"))
part1.rels = {1: Mock(name="rel1", is_external=False, target_part=part2)}
part2.rels = {1: Mock(name="rel2", is_external=False, target_part=part1)}
pkg = OpcPackage()
rels_prop_.return_value = {
1: Mock(name="rel3", is_external=False, target_part=part1),
2: Mock(name="rel4", is_external=True),
}
# verify -----------------------
assert part1 in pkg.iter_parts()
assert part2 in pkg.iter_parts()
assert len(list(pkg.iter_parts())) == 2
def it_can_find_the_next_available_vector_partname(
self, next_partname_fixture, iter_parts_, PackURI_, packuri_
):
"""A vector partname is one with a numeric suffix, like header42.xml."""
parts_, expected_value = next_partname_fixture
iter_parts_.return_value = iter(parts_)
PackURI_.return_value = packuri_
package = OpcPackage()
partname = package.next_partname(template="/foo/bar/baz%d.xml")
PackURI_.assert_called_once_with(expected_value)
assert partname is packuri_
def it_can_find_a_part_related_by_reltype(self, related_part_fixture_):
pkg, reltype, related_part_ = related_part_fixture_
related_part = pkg.part_related_by(reltype)
pkg.rels.part_with_reltype.assert_called_once_with(reltype)
assert related_part is related_part_
def it_can_save_to_a_pkg_file(
self, pkg_file_: Mock, PackageWriter_: Mock, parts_prop_: Mock, parts_: list[Mock]
):
parts_prop_.return_value = parts_
pkg = OpcPackage()
pkg.save(pkg_file_)
for part in parts_:
part.before_marshal.assert_called_once_with()
PackageWriter_.write.assert_called_once_with(pkg_file_, pkg.rels, parts_)
def it_provides_access_to_the_core_properties(self, core_props_fixture):
opc_package, core_properties_ = core_props_fixture
core_properties = opc_package.core_properties
assert core_properties is core_properties_
def it_provides_access_to_the_core_properties_part_to_help(self, core_props_part_fixture):
opc_package, core_properties_part_ = core_props_part_fixture
core_properties_part = opc_package._core_properties_part
assert core_properties_part is core_properties_part_
def it_creates_a_default_core_props_part_if_none_present(
self, part_related_by_, CorePropertiesPart_, relate_to_, core_properties_part_
):
part_related_by_.side_effect = KeyError
CorePropertiesPart_.default.return_value = core_properties_part_
opc_package = OpcPackage()
core_properties_part = opc_package._core_properties_part
CorePropertiesPart_.default.assert_called_once_with(opc_package)
relate_to_.assert_called_once_with(opc_package, core_properties_part_, RT.CORE_PROPERTIES)
assert core_properties_part is core_properties_part_
# fixtures ---------------------------------------------
@pytest.fixture
def core_props_fixture(
self, _core_properties_part_prop_, core_properties_part_, core_properties_
):
opc_package = OpcPackage()
_core_properties_part_prop_.return_value = core_properties_part_
core_properties_part_.core_properties = core_properties_
return opc_package, core_properties_
@pytest.fixture
def core_props_part_fixture(self, part_related_by_, core_properties_part_):
opc_package = OpcPackage()
part_related_by_.return_value = core_properties_part_
return opc_package, core_properties_part_
@pytest.fixture(params=[((), 1), ((1,), 2), ((1, 2), 3), ((2, 3), 1), ((1, 3), 2)])
def next_partname_fixture(self, request, iter_parts_):
existing_partname_ns, next_partname_n = request.param
parts_ = [
instance_mock(request, Part, name="part[%d]" % idx, partname="/foo/bar/baz%d.xml" % n)
for idx, n in enumerate(existing_partname_ns)
]
expected_value = "/foo/bar/baz%d.xml" % next_partname_n
return parts_, expected_value
@pytest.fixture
def related_part_fixture_(self, request: FixtureRequest, rels_prop_: Mock, rels_: Mock):
related_part_ = instance_mock(request, Part, name="related_part_")
rels_.part_with_reltype.return_value = related_part_
pkg = OpcPackage()
rels_prop_.return_value = rels_
return pkg, "http://rel/type", related_part_
# fixture components -----------------------------------
@pytest.fixture
def CorePropertiesPart_(self, request: FixtureRequest):
return class_mock(request, "docx.opc.package.CorePropertiesPart")
@pytest.fixture
def core_properties_(self, request: FixtureRequest):
return instance_mock(request, CoreProperties)
@pytest.fixture
def core_properties_part_(self, request: FixtureRequest):
return instance_mock(request, CorePropertiesPart)
@pytest.fixture
def _core_properties_part_prop_(self, request: FixtureRequest):
return property_mock(request, OpcPackage, "_core_properties_part")
@pytest.fixture
def iter_parts_(self, request: FixtureRequest):
return method_mock(request, OpcPackage, "iter_parts")
@pytest.fixture
def PackageReader_(self, request: FixtureRequest):
return class_mock(request, "docx.opc.package.PackageReader")
@pytest.fixture
def PackURI_(self, request: FixtureRequest):
return class_mock(request, "docx.opc.package.PackURI")
@pytest.fixture
def packuri_(self, request: FixtureRequest):
return instance_mock(request, PackURI)
@pytest.fixture
def PackageWriter_(self, request: FixtureRequest):
return class_mock(request, "docx.opc.package.PackageWriter")
@pytest.fixture
def PartFactory_(self, request: FixtureRequest):
return class_mock(request, "docx.opc.package.PartFactory")
@pytest.fixture
def part_(self, request: FixtureRequest):
return instance_mock(request, Part)
@pytest.fixture
def part_related_by_(self, request: FixtureRequest):
return method_mock(request, OpcPackage, "part_related_by")
@pytest.fixture
def parts_(self, request: FixtureRequest):
part_ = instance_mock(request, Part, name="part_")
part_2_ = instance_mock(request, Part, name="part_2_")
return [part_, part_2_]
@pytest.fixture
def parts_prop_(self, request: FixtureRequest):
return property_mock(request, OpcPackage, "parts")
@pytest.fixture
def pkg_file_(self, request: FixtureRequest):
return loose_mock(request)
@pytest.fixture
def Relationships_(self, request: FixtureRequest):
return class_mock(request, "docx.opc.package.Relationships")
@pytest.fixture
def rel_(self, request: FixtureRequest):
return instance_mock(request, _Relationship)
@pytest.fixture
def relate_to_(self, request: FixtureRequest):
return method_mock(request, OpcPackage, "relate_to")
@pytest.fixture
def rels_(self, request: FixtureRequest):
return instance_mock(request, Relationships)
@pytest.fixture
def rels_prop_(self, request: FixtureRequest):
return property_mock(request, OpcPackage, "rels")
@pytest.fixture
def Unmarshaller_(self, request: FixtureRequest):
return class_mock(request, "docx.opc.package.Unmarshaller")
| DescribeOpcPackage |
python | getsentry__sentry | tests/sentry/issues/endpoints/test_organization_group_search_view_details.py | {
"start": 14993,
"end": 21329
} | class ____(BaseGSVTestCase):
endpoint = "sentry-api-0-organization-group-search-view-details"
method = "put"
def setUp(self) -> None:
self.base_data = self.create_base_data()
self.login_as(user=self.user_2)
# Get the second user's views for testing
self.view_id = str(self.base_data["user_two_views"][0].id)
self.url = reverse(
"sentry-api-0-organization-group-search-view-details",
kwargs={"organization_id_or_slug": self.organization.slug, "view_id": self.view_id},
)
@with_feature({"organizations:issue-views": True})
def test_put_view_success(self) -> None:
data = {
"name": "Updated View Name",
"query": "is:unresolved",
"querySort": "date",
"projects": [self.project.id],
"isAllProjects": False,
"environments": ["production"],
"timeFilters": {"period": "14d"},
}
response = self.client.put(self.url, data=data)
assert response.status_code == 200
# Verify the view was updated
updated_view = GroupSearchView.objects.get(id=self.view_id)
assert updated_view.name == "Updated View Name"
assert updated_view.query == "is:unresolved"
assert updated_view.query_sort == "date"
assert updated_view.is_all_projects is False
assert list(updated_view.projects.values_list("id", flat=True)) == [self.project.id]
assert updated_view.environments == ["production"]
assert updated_view.time_filters == {"period": "14d"}
@with_feature({"organizations:issue-views": True})
def test_put_update_projects(self) -> None:
second_project = self.create_project(organization=self.organization)
data = {
"name": "Updated Projects View",
"query": "is:unresolved",
"querySort": "date",
"projects": [self.project.id, second_project.id],
"environments": [],
"timeFilters": {"period": "14d"},
}
response = self.client.put(self.url, data=data)
assert response.status_code == 200
# Verify the projects were updated
updated_view = GroupSearchView.objects.get(id=self.view_id)
assert set(updated_view.projects.values_list("id", flat=True)) == {
self.project.id,
second_project.id,
}
@with_feature({"organizations:issue-views": True})
def test_put_all_projects(self) -> None:
data = {
"name": "All Projects View",
"query": "is:unresolved",
"querySort": "date",
"projects": [-1],
"environments": [],
"timeFilters": {"period": "14d"},
}
response = self.client.put(self.url, data=data)
assert response.status_code == 200
# Verify isAllProjects was set
updated_view = GroupSearchView.objects.get(id=self.view_id)
assert updated_view.is_all_projects is True
assert updated_view.projects.count() == 0
@with_feature({"organizations:issue-views": True})
def test_put_nonexistent_view(self) -> None:
nonexistent_id = "99999"
url = reverse(
"sentry-api-0-organization-group-search-view-details",
kwargs={"organization_id_or_slug": self.organization.slug, "view_id": nonexistent_id},
)
data = {
"name": "Updated View",
"query": "is:unresolved",
"projects": [self.project.id],
"environments": [],
"timeFilters": {"period": "14d"},
}
response = self.client.put(url, data=data)
assert response.status_code == 404
@with_feature({"organizations:issue-views": True})
def test_put_view_from_another_user(self) -> None:
# Log in as user 3 (no access to user_two's views)
self.login_as(user=self.user_3)
# Get a view ID from user_two
view_id = str(self.base_data["user_two_views"][0].id)
url = reverse(
"sentry-api-0-organization-group-search-view-details",
kwargs={"organization_id_or_slug": self.organization.slug, "view_id": view_id},
)
data = {
"name": "Updated View",
"query": "is:unresolved",
"projects": [self.project.id],
"environments": [],
"timeFilters": {"period": "14d"},
}
response = self.client.put(url, data=data)
assert response.status_code == 403
@with_feature({"organizations:issue-views": True})
def test_put_view_from_another_user_superuser(self) -> None:
# User 1 is a superuser
self.login_as(user=self.user)
# Get a view ID from user_two
view_id = str(self.base_data["user_two_views"][0].id)
url = reverse(
"sentry-api-0-organization-group-search-view-details",
kwargs={"organization_id_or_slug": self.organization.slug, "view_id": view_id},
)
data = {
"name": "Updated View",
"query": "is:unresolved",
"projects": [self.project.id],
"environments": [],
"timeFilters": {"period": "14d"},
}
response = self.client.put(url, data=data)
assert response.status_code == 200
# Verify the view was updated
updated_view = GroupSearchView.objects.get(id=self.view_id)
assert updated_view.name == "Updated View"
@with_feature({"organizations:issue-views": True})
def test_put_invalid_data(self) -> None:
# Missing required timeFilters
data = {
"name": "Invalid View",
"query": "is:unresolved",
"projects": [self.project.id],
"environments": [],
}
response = self.client.put(self.url, data=data)
assert response.status_code == 400
def test_put_without_feature_flag(self) -> None:
data = {
"name": "Updated View",
"query": "is:unresolved",
"projects": [self.project.id],
"environments": [],
"timeFilters": {"period": "14d"},
}
response = self.client.put(self.url, data=data)
assert response.status_code == 404
| OrganizationGroupSearchViewsPutTest |
python | mwaskom__seaborn | seaborn/_marks/bar.py | {
"start": 518,
"end": 3307
} | class ____(Mark):
def _make_patches(self, data, scales, orient):
transform = scales[orient]._matplotlib_scale.get_transform()
forward = transform.transform
reverse = transform.inverted().transform
other = {"x": "y", "y": "x"}[orient]
pos = reverse(forward(data[orient]) - data["width"] / 2)
width = reverse(forward(data[orient]) + data["width"] / 2) - pos
val = (data[other] - data["baseline"]).to_numpy()
base = data["baseline"].to_numpy()
kws = self._resolve_properties(data, scales)
if orient == "x":
kws.update(x=pos, y=base, w=width, h=val)
else:
kws.update(x=base, y=pos, w=val, h=width)
kws.pop("width", None)
kws.pop("baseline", None)
val_dim = {"x": "h", "y": "w"}[orient]
bars, vals = [], []
for i in range(len(data)):
row = {k: v[i] for k, v in kws.items()}
# Skip bars with no value. It's possible we'll want to make this
# an option (i.e so you have an artist for animating or annotating),
# but let's keep things simple for now.
if not np.nan_to_num(row[val_dim]):
continue
bar = mpl.patches.Rectangle(
xy=(row["x"], row["y"]),
width=row["w"],
height=row["h"],
facecolor=row["facecolor"],
edgecolor=row["edgecolor"],
linestyle=row["edgestyle"],
linewidth=row["edgewidth"],
**self.artist_kws,
)
bars.append(bar)
vals.append(row[val_dim])
return bars, vals
def _resolve_properties(self, data, scales):
resolved = resolve_properties(self, data, scales)
resolved["facecolor"] = resolve_color(self, data, "", scales)
resolved["edgecolor"] = resolve_color(self, data, "edge", scales)
fc = resolved["facecolor"]
if isinstance(fc, tuple):
resolved["facecolor"] = fc[0], fc[1], fc[2], fc[3] * resolved["fill"]
else:
fc[:, 3] = fc[:, 3] * resolved["fill"] # TODO Is inplace mod a problem?
resolved["facecolor"] = fc
return resolved
def _legend_artist(
self, variables: list[str], value: Any, scales: dict[str, Scale],
) -> Artist:
# TODO return some sensible default?
key = {v: value for v in variables}
key = self._resolve_properties(key, scales)
artist = mpl.patches.Patch(
facecolor=key["facecolor"],
edgecolor=key["edgecolor"],
linewidth=key["edgewidth"],
linestyle=key["edgestyle"],
)
return artist
@document_properties
@dataclass
| BarBase |
python | PrefectHQ__prefect | src/integrations/prefect-dask/tests/test_utils.py | {
"start": 1807,
"end": 4483
} | class ____:
async def test_from_task(self):
@task
async def test_task():
delayed_num = dask.delayed(42)
async with get_async_dask_client() as client:
assert isinstance(client, Client)
result = await client.compute(delayed_num).result()
return result
@flow(task_runner=DaskTaskRunner)
async def test_flow():
future = test_task.submit()
return future.result()
assert (await test_flow()) == 42
def test_from_sync_task_error(self):
@task
def test_task():
with get_async_dask_client():
pass
@flow(task_runner=DaskTaskRunner)
def test_flow():
return test_task.submit()
if sys.version_info < (3, 11):
with pytest.raises(AttributeError, match="__enter__"):
test_flow()
else:
with pytest.raises(
TypeError, match="not support the context manager protocol"
):
test_flow()
async def test_from_flow(self):
@flow(task_runner=DaskTaskRunner)
async def test_flow():
delayed_num = dask.delayed(42)
async with get_async_dask_client() as client:
assert isinstance(client, Client)
result = await client.compute(delayed_num).result()
return result
assert (await test_flow()) == 42
def test_from_sync_flow_error(self):
@flow(task_runner=DaskTaskRunner)
def test_flow():
with get_async_dask_client():
pass
if sys.version_info < (3, 11):
with pytest.raises(AttributeError, match="__enter__"):
test_flow()
else:
with pytest.raises(
TypeError, match="not support the context manager protocol"
):
test_flow()
async def test_outside_run_context(self):
delayed_num = dask.delayed(42)
async with get_async_dask_client() as client:
assert isinstance(client, Client)
result = await client.compute(delayed_num).result()
assert result == 42
@pytest.mark.parametrize("timeout", [None, 8])
async def test_include_timeout(self, timeout):
delayed_num = dask.delayed(42)
async with get_async_dask_client(timeout=timeout) as client:
assert isinstance(client, Client)
if timeout is not None:
assert client._timeout == timeout
result = await client.compute(delayed_num).result()
assert result == 42
| TestDaskAsyncClient |
python | huggingface__transformers | src/transformers/models/janus/modeling_janus.py | {
"start": 38771,
"end": 41263
} | class ____(JanusPreTrainedModel):
config: JanusVQVAEConfig
_no_split_modules = [
"JanusVQVAEAttnBlock",
"JanusVQVAEResnetBlock",
"JanusVQVAEVectorQuantizer",
]
main_input_name = "pixel_values"
def __init__(self, config: JanusVQVAEConfig):
super().__init__(config)
self.encoder = JanusVQVAEEncoder(config)
self.quantize = JanusVQVAEVectorQuantizer(config)
self.quant_conv = torch.nn.Conv2d(config.latent_channels, config.embed_dim, 1)
self.post_quant_conv = torch.nn.Conv2d(config.embed_dim, config.latent_channels, 1)
self.eval() # Janus's VQ model is frozen
self.decoder = JanusVQVAEDecoder(config)
self.gradient_checkpointing = False
# Initialize the VQVAE model.
self.post_init()
def encode(self, pixel_values: torch.LongTensor):
hidden_states = self.encoder(pixel_values)
hidden_states = self.quant_conv(hidden_states)
quant, emb_loss, indices = self.quantize(hidden_states)
return quant, emb_loss, indices
def decode(self, image_tokens: torch.LongTensor) -> torch.FloatTensor:
"""
Decodes quantized token IDs into pixel values.
Args:
image_tokens (torch.LongTensor): Batch of token IDs.
Returns:
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
Pixel values decoded from the token IDs.
"""
if image_tokens.shape[1] != self.quantize.quant_state_dims[0] * self.quantize.quant_state_dims[1]:
raise ValueError(
f"Expected `image_tokens` to have shape `(batch_size, {self.quantize.quant_state_dims[0] * self.quantize.quant_state_dims[1]})`, "
f"but got shape `{image_tokens.shape}`."
)
codebook_entry = self.quantize.get_codebook_entry(image_tokens)
hidden_states = self.post_quant_conv(codebook_entry)
pixel_values = self.decoder(hidden_states)
return pixel_values
@can_return_tuple
@auto_docstring
def forward(
self,
pixel_values: torch.FloatTensor,
) -> tuple[torch.FloatTensor, torch.FloatTensor]:
batch_size = pixel_values.shape[0]
quant, embedding_loss, indices = self.encode(pixel_values)
decoded_pixel_values = self.decode(indices.view(batch_size, -1))
return JanusVQVAEOutput(decoded_pixel_values, embedding_loss)
| JanusVQVAE |
python | tiangolo__fastapi | fastapi/openapi/models.py | {
"start": 13324,
"end": 13415
} | class ____(OAuthFlow):
authorizationUrl: str
tokenUrl: str
| OAuthFlowAuthorizationCode |
python | encode__starlette | starlette/middleware/base.py | {
"start": 4077,
"end": 8877
} | class ____:
def __init__(self, app: ASGIApp, dispatch: DispatchFunction | None = None) -> None:
self.app = app
self.dispatch_func = self.dispatch if dispatch is None else dispatch
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
await self.app(scope, receive, send)
return
request = _CachedRequest(scope, receive)
wrapped_receive = request.wrapped_receive
response_sent = anyio.Event()
app_exc: Exception | None = None
exception_already_raised = False
async def call_next(request: Request) -> Response:
async def receive_or_disconnect() -> Message:
if response_sent.is_set():
return {"type": "http.disconnect"}
async with anyio.create_task_group() as task_group:
async def wrap(func: Callable[[], Awaitable[T]]) -> T:
result = await func()
task_group.cancel_scope.cancel()
return result
task_group.start_soon(wrap, response_sent.wait)
message = await wrap(wrapped_receive)
if response_sent.is_set():
return {"type": "http.disconnect"}
return message
async def send_no_error(message: Message) -> None:
try:
await send_stream.send(message)
except anyio.BrokenResourceError:
# recv_stream has been closed, i.e. response_sent has been set.
return
async def coro() -> None:
nonlocal app_exc
with send_stream:
try:
await self.app(scope, receive_or_disconnect, send_no_error)
except Exception as exc:
app_exc = exc
task_group.start_soon(coro)
try:
message = await recv_stream.receive()
info = message.get("info", None)
if message["type"] == "http.response.debug" and info is not None:
message = await recv_stream.receive()
except anyio.EndOfStream:
if app_exc is not None:
nonlocal exception_already_raised
exception_already_raised = True
# Prevent `anyio.EndOfStream` from polluting app exception context.
# If both cause and context are None then the context is suppressed
# and `anyio.EndOfStream` is not present in the exception traceback.
# If exception cause is not None then it is propagated with
# reraising here.
# If exception has no cause but has context set then the context is
# propagated as a cause with the reraise. This is necessary in order
# to prevent `anyio.EndOfStream` from polluting the exception
# context.
raise app_exc from app_exc.__cause__ or app_exc.__context__
raise RuntimeError("No response returned.")
assert message["type"] == "http.response.start"
async def body_stream() -> BodyStreamGenerator:
async for message in recv_stream:
if message["type"] == "http.response.pathsend":
yield message
break
assert message["type"] == "http.response.body", f"Unexpected message: {message}"
body = message.get("body", b"")
if body:
yield body
if not message.get("more_body", False):
break
response = _StreamingResponse(status_code=message["status"], content=body_stream(), info=info)
response.raw_headers = message["headers"]
return response
streams: anyio.create_memory_object_stream[Message] = anyio.create_memory_object_stream()
send_stream, recv_stream = streams
with recv_stream, send_stream, collapse_excgroups():
async with anyio.create_task_group() as task_group:
response = await self.dispatch_func(request, call_next)
await response(scope, wrapped_receive, send)
response_sent.set()
recv_stream.close()
if app_exc is not None and not exception_already_raised:
raise app_exc
async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
raise NotImplementedError() # pragma: no cover
| BaseHTTPMiddleware |
python | PrefectHQ__prefect | src/prefect/client/schemas/objects.py | {
"start": 36880,
"end": 36992
} | class ____(str, Enum):
KEEP = "keep"
REMOVE = "remove"
INACTIVE = "inactive"
| BranchingScheduleHandling |
python | streamlit__streamlit | lib/tests/streamlit/runtime/caching/storage/dummy_cache_storage_test.py | {
"start": 2971,
"end": 4487
} | class ____(unittest.TestCase):
def setUp(self):
super().setUp()
self.storage = DummyCacheStorage()
def test_dummy_storage_get_always_not_found(self):
"""Test that storage.get() always returns CacheStorageKeyNotFoundError."""
with pytest.raises(CacheStorageKeyNotFoundError):
self.storage.get("some-key")
self.storage.set("some-key", b"some-value")
with pytest.raises(CacheStorageKeyNotFoundError):
self.storage.get("some-key")
def test_storage_set(self):
"""
Test that storage.set() works correctly, at always do nothing without
raising exception."""
self.storage.set("new-key", b"new-value")
with pytest.raises(CacheStorageKeyNotFoundError):
self.storage.get("new-key")
def test_storage_delete(self):
"""
Test that storage.delete() works correctly, at always do nothing without
raising exception.
"""
self.storage.delete("another-key")
self.storage.delete("another-key")
self.storage.delete("another-key")
def test_storage_clear(self):
"""
Test that storage.clear() works correctly, at always do nothing without
raising exception.
"""
self.storage.clear()
def test_storage_close(self):
"""
Test that storage.close() works correctly, at always do nothing without
raising exception.
"""
self.storage.close()
| DummyCacheStorageTest |
python | pytorch__pytorch | test/inductor/test_perf.py | {
"start": 2622,
"end": 2678
} | class ____(InductorTestCase):
device = DEVICE
| TestCase |
python | pydantic__pydantic | tests/mypy/outputs/mypy-plugin_ini/plugin_optional_inheritance.py | {
"start": 155,
"end": 453
} | class ____(Bar):
name: str
b = Bar(foo={'id': 1})
assert b.foo.id == 1
# MYPY: error: Item "None" of "Optional[Foo]" has no attribute "id" [union-attr]
z = Baz(foo={'id': 1}, name='test')
assert z.foo.id == 1
# MYPY: error: Item "None" of "Optional[Foo]" has no attribute "id" [union-attr]
| Baz |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/paramSpec14.py | {
"start": 723,
"end": 1112
} | class ____(Generic[P, T]):
@overload
@classmethod
def method1(
cls, run: Callable[P, T], /, *args: P.args, **kwargs: P.kwargs
) -> Self: ...
@overload
@classmethod
def method1(cls) -> "ClassB[[], None]": ...
@classmethod
def method1(cls, *args: Any, **kwargs: Any) -> Any: ...
def func1() -> None:
pass
m1 = ClassB.method1
m1(func1)
| ClassB |
python | pytorch__pytorch | test/dynamo/test_structured_trace.py | {
"start": 5319,
"end": 102359
} | class ____(TestCase):
def setUp(self):
super().setUp()
torch._dynamo.reset()
torch._logging.structured.INTERN_TABLE.clear()
self.buffer = io.StringIO()
self.old_level = trace_log.level
trace_log.setLevel(logging.DEBUG)
self.handler = logging.StreamHandler(self.buffer)
self.handler.setFormatter(StructuredTraceTestingFormatter())
self.handler.addFilter(StructuredTraceTestingFilter())
self.handler.addFilter(chrome_event_filter)
trace_log.addHandler(self.handler)
self.raw_file = tempfile.NamedTemporaryFile(
mode="w", delete=True
) # set this to False to keep temporary files
self.raw_handler = logging.StreamHandler(self.raw_file)
self.raw_handler.setFormatter(TorchLogsFormatter(trace=True))
trace_log.addHandler(self.raw_handler)
def tearDown(self):
trace_log.removeHandler(self.handler)
trace_log.removeHandler(self.raw_handler)
self.raw_file.close()
trace_log.setLevel(self.old_level)
def assertParses(self):
out = tempfile.mkdtemp()
try:
subprocess.check_call(
[
"tlparse",
"-o",
out,
"--overwrite",
"--no-browser",
"--strict",
self.raw_file.name,
]
)
finally:
shutil.rmtree(out, ignore_errors=True)
def test_compile_id_serialization_deserialization(self):
cid = torch._guards.CompileId(
frame_id=1,
frame_compile_id=2,
)
assert cid == torch._guards.CompileId.from_string(str(cid))
cid = torch._guards.CompileId(
compiled_autograd_id=1,
frame_id=2,
frame_compile_id=3,
)
assert cid == torch._guards.CompileId.from_string(str(cid))
cid = torch._guards.CompileId(
compiled_autograd_id=1,
frame_id=None,
frame_compile_id=None,
)
assert cid == torch._guards.CompileId.from_string(str(cid))
for bad_cid in ["-/-", "-/1", "1/-", "!1/2", "!1/-/-"]:
with self.assertRaises(ValueError):
torch._guards.CompileId.from_string(bad_cid)
@requires_cuda_and_triton
def test_schedule(self):
fn_opt = torch.compile(inductor_schedule_fn, backend="inductor")
fn_opt(torch.ones(1000, 1000, device="cuda"))
self.assertExpectedInline(
self.buffer.getvalue(),
"""\
{"dynamo_start": {"stack": "STACK"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"describe_storage": {"id": 0, "describer_id": "ID", "size": 4000000}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"describe_tensor": {"id": 0, "ndim": 2, "dtype": "torch.float32", "device": "device(type='cuda', index=0)", "size": [1000, 1000], "dynamo_hint_overrides": {}, "is_leaf": true, "stride": [1000, 1], "storage": 0, "view_func": "VIEW_FUNC", "describer_id": "ID"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"describe_source": {"describer_id": "ID", "id": 0, "source": "L['a']"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"dynamo_output_graph": {"sizes": {"l_a_": [1000, 1000], "ones": [1000, 1000], "output": [1000, 1000]}}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "before_pre_grad_graph", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "after_pre_grad_graph", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "aotautograd_cache_miss", "encoding": "json"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "aot_forward_graph_fw_metadata", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"aot_inference_graph": {}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "torch._functorch.config", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "before_joint_graph", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "after_joint_graph", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "fx_graph_runnable", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "before_post_grad_graph", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "inductor_post_grad_graph", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"inductor_output_code": {"filename": "FILENAME", "file_path": "FILENAME"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "triton_kernel_info", "encoding": "json"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "fx_graph_cache_miss", "encoding": "json"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"dynamo_cpp_guards_str": {}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"compilation_metrics": "METRICS", "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"compilation_metrics_runtime": "METRICS", "frame_id": 0, "frame_compile_id": 0}
""", # noqa: B950
)
self.assertParses()
@requires_cuda_and_triton
def test_cudagraphs(self):
fn_opt = torch.compile(mode="reduce-overhead")(inductor_schedule_fn)
fn_opt(torch.ones(1000, 1000, device="cuda"))
self.assertExpectedInline(
self.buffer.getvalue(),
"""\
{"dynamo_start": {"stack": "STACK"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"describe_storage": {"id": 0, "describer_id": "ID", "size": 4000000}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"describe_tensor": {"id": 0, "ndim": 2, "dtype": "torch.float32", "device": "device(type='cuda', index=0)", "size": [1000, 1000], "dynamo_hint_overrides": {}, "is_leaf": true, "stride": [1000, 1], "storage": 0, "view_func": "VIEW_FUNC", "describer_id": "ID"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"describe_source": {"describer_id": "ID", "id": 0, "source": "L['a']"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"dynamo_output_graph": {"sizes": {"l_a_": [1000, 1000], "ones": [1000, 1000], "output": [1000, 1000]}}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "before_pre_grad_graph", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "after_pre_grad_graph", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "aotautograd_cache_miss", "encoding": "json"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "aot_forward_graph_fw_metadata", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"aot_inference_graph": {}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "torch._functorch.config", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "before_joint_graph", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "after_joint_graph", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "fx_graph_runnable", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "before_post_grad_graph", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "inductor_post_grad_graph", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"inductor_output_code": {"filename": "FILENAME", "file_path": "FILENAME"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "triton_kernel_info", "encoding": "json"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "fx_graph_cache_miss", "encoding": "json"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"dynamo_cpp_guards_str": {}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"compilation_metrics": "METRICS", "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"compilation_metrics_runtime": "METRICS", "frame_id": 0, "frame_compile_id": 0}
""", # noqa: B950
)
self.assertParses()
@requires_tlparse
def test_recompiles(self):
def fn(x, y):
return torch.add(x, y)
fn_opt = torch.compile(fn, backend="inductor")
fn_opt(torch.ones(1000, 1000), torch.ones(1000, 1000))
fn_opt(torch.ones(1000, 1000), 1)
self.assertExpectedInline(
self.buffer.getvalue(),
"""\
{"dynamo_start": {"stack": "STACK"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"describe_storage": {"id": 0, "describer_id": "ID", "size": 4000000}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"describe_tensor": {"id": 0, "ndim": 2, "dtype": "torch.float32", "device": "device(type='cpu')", "size": [1000, 1000], "dynamo_hint_overrides": {}, "is_leaf": true, "stride": [1000, 1], "storage": 0, "view_func": "VIEW_FUNC", "describer_id": "ID"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"describe_source": {"describer_id": "ID", "id": 0, "source": "L['x']"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"describe_storage": {"id": 1, "describer_id": "ID", "size": 4000000}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"describe_tensor": {"id": 1, "ndim": 2, "dtype": "torch.float32", "device": "device(type='cpu')", "size": [1000, 1000], "dynamo_hint_overrides": {}, "is_leaf": true, "stride": [1000, 1], "storage": 1, "view_func": "VIEW_FUNC", "describer_id": "ID"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"describe_source": {"describer_id": "ID", "id": 1, "source": "L['y']"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"dynamo_output_graph": {"sizes": {"l_x_": [1000, 1000], "l_y_": [1000, 1000], "add": [1000, 1000]}}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "before_pre_grad_graph", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "after_pre_grad_graph", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "aotautograd_cache_miss", "encoding": "json"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "aot_forward_graph_fw_metadata", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"aot_inference_graph": {}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "torch._functorch.config", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "before_joint_graph", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "after_joint_graph", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "fx_graph_runnable", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "before_post_grad_graph", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "inductor_post_grad_graph", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"inductor_output_code": {"filename": "FILENAME", "file_path": "FILENAME"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "fx_graph_cache_miss", "encoding": "json"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"dynamo_cpp_guards_str": {}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"compilation_metrics": "METRICS", "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"artifact": {"name": "recompile_reasons", "encoding": "json"}, "frame_id": 0, "frame_compile_id": 1, "attempt": 0, "has_payload": "HASH"}
{"dynamo_start": {"stack": "STACK"}, "frame_id": 0, "frame_compile_id": 1, "attempt": 0}
{"describe_storage": {"id": 0, "describer_id": "ID", "size": 4000000}, "frame_id": 0, "frame_compile_id": 1, "attempt": 0}
{"describe_tensor": {"id": 0, "ndim": 2, "dtype": "torch.float32", "device": "device(type='cpu')", "size": [1000, 1000], "dynamo_hint_overrides": {}, "is_leaf": true, "stride": [1000, 1], "storage": 0, "view_func": "VIEW_FUNC", "describer_id": "ID"}, "frame_id": 0, "frame_compile_id": 1, "attempt": 0}
{"describe_source": {"describer_id": "ID", "id": 0, "source": "L['x']"}, "frame_id": 0, "frame_compile_id": 1, "attempt": 0}
{"create_symbol": {"symbol": "s48", "val": "1", "vr": "[-int_oo, int_oo]", "source": "L['y']", "user_stack": "STACK", "stack": "STACK"}, "frame_id": 0, "frame_compile_id": 1, "attempt": 0}
{"dynamo_output_graph": {"sizes": {"l_x_": [1000, 1000], "add": [1000, 1000]}}, "frame_id": 0, "frame_compile_id": 1, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "before_pre_grad_graph", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 1, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "after_pre_grad_graph", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 1, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "aotautograd_cache_miss", "encoding": "json"}, "frame_id": 0, "frame_compile_id": 1, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "aot_forward_graph_fw_metadata", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 1, "attempt": 0, "has_payload": "HASH"}
{"aot_inference_graph": {}, "frame_id": 0, "frame_compile_id": 1, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "torch._functorch.config", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 1, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "before_joint_graph", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 1, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "after_joint_graph", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 1, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "fx_graph_runnable", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 1, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "before_post_grad_graph", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 1, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "inductor_post_grad_graph", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 1, "attempt": 0, "has_payload": "HASH"}
{"inductor_output_code": {"filename": "FILENAME", "file_path": "FILENAME"}, "frame_id": 0, "frame_compile_id": 1, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "fx_graph_cache_miss", "encoding": "json"}, "frame_id": 0, "frame_compile_id": 1, "attempt": 0, "has_payload": "HASH"}
{"dynamo_cpp_guards_str": {}, "frame_id": 0, "frame_compile_id": 1, "attempt": 0, "has_payload": "HASH"}
{"compilation_metrics": "METRICS", "frame_id": 0, "frame_compile_id": 1, "attempt": 0}
""", # noqa: B950
)
self.assertParses()
@requires_tlparse
def test_example_fn(self):
fn_opt = torch.compile(example_fn, backend="inductor")
fn_opt(torch.ones(1000, 1000))
self.assertExpectedInline(
self.buffer.getvalue(),
"""\
{"dynamo_start": {"stack": "STACK"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"describe_storage": {"id": 0, "describer_id": "ID", "size": 4000000}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"describe_tensor": {"id": 0, "ndim": 2, "dtype": "torch.float32", "device": "device(type='cpu')", "size": [1000, 1000], "dynamo_hint_overrides": {}, "is_leaf": true, "stride": [1000, 1], "storage": 0, "view_func": "VIEW_FUNC", "describer_id": "ID"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"describe_source": {"describer_id": "ID", "id": 0, "source": "L['a']"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"dynamo_output_graph": {"sizes": {"l_a_": [1000, 1000], "ones": [1000, 1000], "output": [1000, 1000], "ones_1": [1000, 1000], "output_1": [1000, 1000]}}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "before_pre_grad_graph", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "after_pre_grad_graph", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "aotautograd_cache_miss", "encoding": "json"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "aot_forward_graph_fw_metadata", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"aot_inference_graph": {}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "torch._functorch.config", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "before_joint_graph", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "after_joint_graph", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "fx_graph_runnable", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "before_post_grad_graph", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "inductor_post_grad_graph", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"inductor_output_code": {"filename": "FILENAME", "file_path": "FILENAME"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "fx_graph_cache_miss", "encoding": "json"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"dynamo_cpp_guards_str": {}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"compilation_metrics": "METRICS", "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
""", # noqa: B950
)
self.assertParses()
@requires_tlparse
def test_example_training_fn(self):
fn_opt = torch.compile(example_training_fn, backend="inductor")
fn_opt(torch.ones(1000, 1000, requires_grad=True))
buffer = self.buffer.getvalue()
buffer = replace_dynamic(buffer, "inductor_compile_time_s")
buffer = replace_dynamic(buffer, "code_gen_time_s")
buffer = replace_dynamic(buffer, "structured_logging_overhead_s")
self.assertExpectedInline(
buffer,
"""\
{"dynamo_start": {"stack": "STACK"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"describe_storage": {"id": 0, "describer_id": "ID", "size": 4000000}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"describe_tensor": {"id": 0, "ndim": 2, "dtype": "torch.float32", "device": "device(type='cpu')", "size": [1000, 1000], "dynamo_hint_overrides": {}, "is_leaf": true, "requires_grad": true, "stride": [1000, 1], "storage": 0, "view_func": "VIEW_FUNC", "describer_id": "ID"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"describe_source": {"describer_id": "ID", "id": 0, "source": "L['a']"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"artifact": {"name": "dynamo_graph_break_reason", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"describe_storage": {"id": 0, "describer_id": "ID", "size": 4000000}, "frame_id": 0, "frame_compile_id": 0, "attempt": 1}
{"describe_tensor": {"id": 0, "ndim": 2, "dtype": "torch.float32", "device": "device(type='cpu')", "size": [1000, 1000], "dynamo_hint_overrides": {}, "is_leaf": true, "requires_grad": true, "stride": [1000, 1], "storage": 0, "view_func": "VIEW_FUNC", "describer_id": "ID"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 1}
{"describe_source": {"describer_id": "ID", "id": 0, "source": "L['a']"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 1}
{"dynamo_cpp_guards_str": {}, "frame_id": 0, "frame_compile_id": 0, "attempt": 1, "has_payload": "HASH"}
{"compilation_metrics": "METRICS", "frame_id": 0, "frame_compile_id": 0, "attempt": 1}
{"dynamo_start": {"stack": "STACK"}, "frame_id": 1, "frame_compile_id": 0, "attempt": 0}
{"artifact": {"name": "dynamo_graph_break_reason", "encoding": "string"}, "frame_id": 1, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"describe_storage": {"id": 0, "describer_id": "ID", "size": 4000000}, "frame_id": 1, "frame_compile_id": 0, "attempt": 1}
{"describe_tensor": {"id": 0, "ndim": 2, "dtype": "torch.float32", "device": "device(type='cpu')", "size": [1000, 1000], "dynamo_hint_overrides": {}, "is_leaf": true, "requires_grad": true, "stride": [1000, 1], "storage": 0, "view_func": "VIEW_FUNC", "describer_id": "ID"}, "frame_id": 1, "frame_compile_id": 0, "attempt": 1}
{"describe_source": {"describer_id": "ID", "id": 0, "source": "L['___stack1']"}, "frame_id": 1, "frame_compile_id": 0, "attempt": 1}
{"dynamo_cpp_guards_str": {}, "frame_id": 1, "frame_compile_id": 0, "attempt": 1, "has_payload": "HASH"}
{"compilation_metrics": "METRICS", "frame_id": 1, "frame_compile_id": 0, "attempt": 1}
{"dynamo_start": {"stack": "STACK"}, "frame_id": 2, "frame_compile_id": 0, "attempt": 0}
{"describe_storage": {"id": 0, "describer_id": "ID", "size": 4000000}, "frame_id": 2, "frame_compile_id": 0, "attempt": 0}
{"describe_tensor": {"id": 0, "ndim": 2, "dtype": "torch.float32", "device": "device(type='cpu')", "size": [1000, 1000], "dynamo_hint_overrides": {}, "requires_grad": true, "stride": [1000, 1], "storage": 0, "view_func": "VIEW_FUNC", "describer_id": "ID"}, "frame_id": 2, "frame_compile_id": 0, "attempt": 0}
{"describe_source": {"describer_id": "ID", "id": 0, "source": "L['___stack0']"}, "frame_id": 2, "frame_compile_id": 0, "attempt": 0}
{"artifact": {"name": "dynamo_graph_break_reason", "encoding": "string"}, "frame_id": 2, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"describe_storage": {"id": 0, "describer_id": "ID", "size": 4000000}, "frame_id": 2, "frame_compile_id": 0, "attempt": 1}
{"describe_tensor": {"id": 0, "ndim": 2, "dtype": "torch.float32", "device": "device(type='cpu')", "size": [1000, 1000], "dynamo_hint_overrides": {}, "requires_grad": true, "stride": [1000, 1], "storage": 0, "view_func": "VIEW_FUNC", "describer_id": "ID"}, "frame_id": 2, "frame_compile_id": 0, "attempt": 1}
{"describe_source": {"describer_id": "ID", "id": 0, "source": "L['___stack0']"}, "frame_id": 2, "frame_compile_id": 0, "attempt": 1}
{"dynamo_output_graph": {"sizes": {"l_stack0_": [1000, 1000], "ones": [1000, 1000], "output": [1000, 1000], "sum_1": []}}, "frame_id": 2, "frame_compile_id": 0, "attempt": 1, "has_payload": "HASH"}
{"artifact": {"name": "before_pre_grad_graph", "encoding": "string"}, "frame_id": 2, "frame_compile_id": 0, "attempt": 1, "has_payload": "HASH"}
{"artifact": {"name": "after_pre_grad_graph", "encoding": "string"}, "frame_id": 2, "frame_compile_id": 0, "attempt": 1, "has_payload": "HASH"}
{"artifact": {"name": "aotautograd_cache_miss", "encoding": "json"}, "frame_id": 2, "frame_compile_id": 0, "attempt": 1, "has_payload": "HASH"}
{"aot_joint_graph": {}, "frame_id": 2, "frame_compile_id": 0, "attempt": 1, "has_payload": "HASH"}
{"artifact": {"name": "torch._functorch.config", "encoding": "string"}, "frame_id": 2, "frame_compile_id": 0, "attempt": 1, "has_payload": "HASH"}
{"artifact": {"name": "aot_forward_graph_fw_metadata", "encoding": "string"}, "frame_id": 2, "frame_compile_id": 0, "attempt": 1, "has_payload": "HASH"}
{"aot_forward_graph": {}, "frame_id": 2, "frame_compile_id": 0, "attempt": 1, "has_payload": "HASH"}
{"aot_backward_graph": {}, "frame_id": 2, "frame_compile_id": 0, "attempt": 1, "has_payload": "HASH"}
{"artifact": {"name": "fx_graph_runnable", "encoding": "string"}, "frame_id": 2, "frame_compile_id": 0, "attempt": 1, "has_payload": "HASH"}
{"artifact": {"name": "before_post_grad_graph", "encoding": "string"}, "frame_id": 2, "frame_compile_id": 0, "attempt": 1, "has_payload": "HASH"}
{"artifact": {"name": "inductor_post_grad_graph", "encoding": "string"}, "frame_id": 2, "frame_compile_id": 0, "attempt": 1, "has_payload": "HASH"}
{"inductor_output_code": {"filename": "FILENAME", "file_path": "FILENAME"}, "frame_id": 2, "frame_compile_id": 0, "attempt": 1, "has_payload": "HASH"}
{"artifact": {"name": "fx_graph_cache_miss", "encoding": "json"}, "frame_id": 2, "frame_compile_id": 0, "attempt": 1, "has_payload": "HASH"}
{"dynamo_cpp_guards_str": {}, "frame_id": 2, "frame_compile_id": 0, "attempt": 1, "has_payload": "HASH"}
{"compilation_metrics": "METRICS", "frame_id": 2, "frame_compile_id": 0, "attempt": 1}
{"dynamo_start": {"stack": "STACK"}, "frame_id": 3, "frame_compile_id": 0, "attempt": 0}
{"compilation_metrics": "METRICS", "frame_id": 3, "frame_compile_id": 0, "attempt": 0}
{"artifact": {"name": "fx_graph_runnable", "encoding": "string"}, "frame_id": 2, "frame_compile_id": 0, "attempt": 1, "has_payload": "HASH"}
{"artifact": {"name": "before_post_grad_graph", "encoding": "string"}, "frame_id": 2, "frame_compile_id": 0, "attempt": 1, "has_payload": "HASH"}
{"artifact": {"name": "inductor_post_grad_graph", "encoding": "string"}, "frame_id": 2, "frame_compile_id": 0, "attempt": 1, "has_payload": "HASH"}
{"inductor_output_code": {"filename": "FILENAME", "file_path": "FILENAME"}, "frame_id": 2, "frame_compile_id": 0, "attempt": 1, "has_payload": "HASH"}
{"artifact": {"name": "fx_graph_cache_miss", "encoding": "json"}, "frame_id": 2, "frame_compile_id": 0, "attempt": 1, "has_payload": "HASH"}
{"bwd_compilation_metrics": "METRICS", "frame_id": 2, "frame_compile_id": 0, "attempt": 1}
{"dynamo_start": {"stack": "STACK"}, "frame_id": 4, "frame_compile_id": 0, "attempt": 0}
{"describe_storage": {"id": 0, "describer_id": "ID", "size": 4000000}, "frame_id": 4, "frame_compile_id": 0, "attempt": 0}
{"describe_tensor": {"id": 0, "ndim": 2, "dtype": "torch.float32", "device": "device(type='cpu')", "size": [1000, 1000], "dynamo_hint_overrides": {}, "requires_grad": true, "stride": [1000, 1], "storage": 0, "view_func": "VIEW_FUNC", "describer_id": "ID"}, "frame_id": 4, "frame_compile_id": 0, "attempt": 0}
{"describe_source": {"describer_id": "ID", "id": 0, "source": "L['output']"}, "frame_id": 4, "frame_compile_id": 0, "attempt": 0}
{"compilation_metrics": "METRICS", "frame_id": 4, "frame_compile_id": 0, "attempt": 0}
""", # noqa: B950
)
self.assertParses()
@requires_tlparse
def test_dynamo_error(self):
try:
fn_opt = torch.compile(dynamo_error_fn, backend="inductor")
fn_opt(*ARGS)
except Exception:
pass
self.assertExpectedInline(
self.buffer.getvalue(),
"""\
{"dynamo_start": {"stack": "STACK"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"describe_storage": {"id": 0, "describer_id": "ID", "size": 4000000}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"describe_tensor": {"id": 0, "ndim": 2, "dtype": "torch.float32", "device": "device(type='cpu')", "size": [1000, 1000], "dynamo_hint_overrides": {}, "is_leaf": true, "requires_grad": true, "stride": [1000, 1], "storage": 0, "view_func": "VIEW_FUNC", "describer_id": "ID"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"describe_source": {"describer_id": "ID", "id": 0, "source": "L['a']"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"artifact": {"name": "dynamo_error", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"compilation_metrics": "METRICS", "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
""", # noqa: B950
)
self.assertParses()
@requires_tlparse
def test_inductor_error(self):
import torch._inductor.lowering
def throw(x):
raise AssertionError
# inject an error in the lowerings
dict_entries = {}
for x in list(torch._inductor.lowering.lowerings.keys()):
if "round" in x.__name__:
dict_entries[x] = throw
with unittest.mock.patch.dict(torch._inductor.lowering.lowerings, dict_entries):
try:
fn_opt = torch.compile(inductor_error_fn, backend="inductor")
fn_opt(*ARGS)
except Exception:
pass
self.assertExpectedInline(
self.buffer.getvalue(),
"""\
{"dynamo_start": {"stack": "STACK"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"describe_storage": {"id": 0, "describer_id": "ID", "size": 4000000}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"describe_tensor": {"id": 0, "ndim": 2, "dtype": "torch.float32", "device": "device(type='cpu')", "size": [1000, 1000], "dynamo_hint_overrides": {}, "is_leaf": true, "requires_grad": true, "stride": [1000, 1], "storage": 0, "view_func": "VIEW_FUNC", "describer_id": "ID"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"describe_source": {"describer_id": "ID", "id": 0, "source": "L['a']"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"dynamo_output_graph": {"sizes": {"l_a_": [1000, 1000], "output": [1000, 1000]}}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "before_pre_grad_graph", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "after_pre_grad_graph", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "aotautograd_cache_miss", "encoding": "json"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"aot_joint_graph": {}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "torch._functorch.config", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "aot_forward_graph_fw_metadata", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"aot_forward_graph": {}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"aot_backward_graph": {}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "fx_graph_runnable", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "before_post_grad_graph", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "inductor_post_grad_graph", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "dynamo_error", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"compilation_metrics": "METRICS", "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
""", # noqa: B950
)
self.assertParses()
@requires_distributed()
@requires_cuda_and_triton
def test_ddp_graphs(self):
class ToyModel(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.layers = torch.nn.Sequential(
torch.nn.Linear(1024, 1024),
torch.nn.Linear(1024, 1024),
)
def forward(self, x):
return self.layers(x)
# TODO: this isn't safely bracketed, will leak
os.environ["MASTER_ADDR"] = "localhost"
os.environ["MASTER_PORT"] = str(find_free_port())
dist.init_process_group("gloo", rank=0, world_size=1)
model = DDP(ToyModel().to("cuda:0"), device_ids=[0], bucket_cap_mb=4)
ddp_model = torch.compile(model, backend="inductor")
ddp_model(torch.randn(1024, 1024, device="cuda:0"))
dist.destroy_process_group()
if not torch._dynamo.config.inline_inbuilt_nn_modules:
self.assertExpectedInline(
self.buffer.getvalue(),
"""\
{"dynamo_start": {"stack": "STACK"}, "rank": 0, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"artifact": {"name": "dynamo_graph_break_reason", "encoding": "string"}, "rank": 0, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"dynamo_cpp_guards_str": {}, "rank": 0, "frame_id": 0, "frame_compile_id": 0, "attempt": 1, "has_payload": "HASH"}
{"compilation_metrics": "METRICS", "rank": 0, "frame_id": 0, "frame_compile_id": 0, "attempt": 1}
{"dynamo_start": {"stack": "STACK"}, "rank": 0, "frame_id": 1, "frame_compile_id": 0, "attempt": 0}
{"artifact": {"name": "dynamo_graph_break_reason", "encoding": "string"}, "rank": 0, "frame_id": 1, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"dynamo_cpp_guards_str": {}, "rank": 0, "frame_id": 1, "frame_compile_id": 0, "attempt": 1, "has_payload": "HASH"}
{"compilation_metrics": "METRICS", "rank": 0, "frame_id": 1, "frame_compile_id": 0, "attempt": 1}
{"dynamo_start": {"stack": "STACK"}, "rank": 0, "frame_id": 2, "frame_compile_id": 0, "attempt": 0}
{"artifact": {"name": "dynamo_graph_break_reason", "encoding": "string"}, "rank": 0, "frame_id": 2, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"dynamo_cpp_guards_str": {}, "rank": 0, "frame_id": 2, "frame_compile_id": 0, "attempt": 1, "has_payload": "HASH"}
{"compilation_metrics": "METRICS", "rank": 0, "frame_id": 2, "frame_compile_id": 0, "attempt": 1}
{"dynamo_start": {"stack": "STACK"}, "rank": 0, "frame_id": 3, "frame_compile_id": 0, "attempt": 0}
{"describe_storage": {"id": 0, "describer_id": "ID", "size": 4194304}, "rank": 0, "frame_id": 3, "frame_compile_id": 0, "attempt": 0}
{"describe_tensor": {"id": 0, "ndim": 2, "dtype": "torch.float32", "device": "device(type='cuda', index=0)", "size": [1024, 1024], "is_leaf": true, "stride": [1024, 1], "storage": 0, "view_func": "VIEW_FUNC", "describer_id": "ID"}, "rank": 0, "frame_id": 3, "frame_compile_id": 0, "attempt": 0}
{"describe_source": {"describer_id": "ID", "id": 0, "source": "L['x']"}, "rank": 0, "frame_id": 3, "frame_compile_id": 0, "attempt": 0}
{"dynamo_output_graph": {"sizes": {"l_x_": [1024, 1024], "l__self___layers_0": [1024, 1024], "l__self___layers_1": [1024, 1024]}}, "rank": 0, "frame_id": 3, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"optimize_ddp_split_graph": {}, "rank": 0, "frame_id": 3, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"optimize_ddp_split_child": {"name": "submod_0"}, "rank": 0, "frame_id": 3, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"optimize_ddp_split_child": {"name": "submod_1"}, "rank": 0, "frame_id": 3, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"describe_storage": {"id": 0, "describer_id": "ID", "size": 4194304}, "rank": 0, "frame_id": 3, "frame_compile_id": 0, "attempt": 0}
{"describe_tensor": {"id": 0, "ndim": 2, "dtype": "torch.float32", "device": "device(type='cuda', index=0)", "size": [1024, 1024], "is_leaf": true, "stride": [1024, 1], "storage": 0, "view_func": "VIEW_FUNC", "describer_id": "ID"}, "rank": 0, "frame_id": 3, "frame_compile_id": 0, "attempt": 0}
{"describe_source": {"describer_id": "ID", "id": 0, "source": "L['x']"}, "rank": 0, "frame_id": 3, "frame_compile_id": 0, "attempt": 0}
{"artifact": {"name": "before_pre_grad_graph", "encoding": "string"}, "rank": 0, "frame_id": 3, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "after_pre_grad_graph", "encoding": "string"}, "rank": 0, "frame_id": 3, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"aot_joint_graph": {}, "rank": 0, "frame_id": 3, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "torch._functorch.config", "encoding": "string"}, "rank": 0, "frame_id": 3, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "aot_forward_graph_fw_metadata", "encoding": "string"}, "rank": 0, "frame_id": 3, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"aot_forward_graph": {}, "rank": 0, "frame_id": 3, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"aot_backward_graph": {}, "rank": 0, "frame_id": 3, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "fx_graph_runnable", "encoding": "string"}, "rank": 0, "frame_id": 3, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "before_post_grad_graph", "encoding": "string"}, "rank": 0, "frame_id": 3, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "inductor_post_grad_graph", "encoding": "string"}, "rank": 0, "frame_id": 3, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"inductor_output_code": {"filename": "FILENAME", "file_path": "FILENAME"}, "rank": 0, "frame_id": 3, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "fx_graph_cache_miss", "encoding": "json"}, "rank": 0, "frame_id": 3, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "aotautograd_cache_bypass", "encoding": "json"}, "rank": 0, "frame_id": 3, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "before_pre_grad_graph", "encoding": "string"}, "rank": 0, "frame_id": 3, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "after_pre_grad_graph", "encoding": "string"}, "rank": 0, "frame_id": 3, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"aot_joint_graph": {}, "rank": 0, "frame_id": 3, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "torch._functorch.config", "encoding": "string"}, "rank": 0, "frame_id": 3, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "aot_forward_graph_fw_metadata", "encoding": "string"}, "rank": 0, "frame_id": 3, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"aot_forward_graph": {}, "rank": 0, "frame_id": 3, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"aot_backward_graph": {}, "rank": 0, "frame_id": 3, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "fx_graph_runnable", "encoding": "string"}, "rank": 0, "frame_id": 3, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "before_post_grad_graph", "encoding": "string"}, "rank": 0, "frame_id": 3, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "inductor_post_grad_graph", "encoding": "string"}, "rank": 0, "frame_id": 3, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"inductor_output_code": {"filename": "FILENAME", "file_path": "FILENAME"}, "rank": 0, "frame_id": 3, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "fx_graph_cache_miss", "encoding": "json"}, "rank": 0, "frame_id": 3, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "aotautograd_cache_bypass", "encoding": "json"}, "rank": 0, "frame_id": 3, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"dynamo_cpp_guards_str": {}, "rank": 0, "frame_id": 3, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"compilation_metrics": "METRICS", "rank": 0, "frame_id": 3, "frame_compile_id": 0, "attempt": 0}
""", # noqa: B950
)
else:
self.assertExpectedInline(
self.buffer.getvalue(),
"""\
{"dynamo_start": {"stack": "STACK"}, "rank": 0, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"artifact": {"name": "dynamo_graph_break_reason", "encoding": "string"}, "rank": 0, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"describe_storage": {"id": 0, "describer_id": "ID", "size": 4194304}, "rank": 0, "frame_id": 0, "frame_compile_id": 0, "attempt": 1}
{"describe_tensor": {"id": 0, "ndim": 2, "dtype": "torch.float32", "device": "device(type='cuda', index=0)", "size": [1024, 1024], "dynamo_hint_overrides": {}, "is_leaf": true, "stride": [1024, 1], "storage": 0, "view_func": "VIEW_FUNC", "describer_id": "ID"}, "rank": 0, "frame_id": 0, "frame_compile_id": 0, "attempt": 1}
{"describe_source": {"describer_id": "ID", "id": 0, "source": "L['args'][0]"}, "rank": 0, "frame_id": 0, "frame_compile_id": 0, "attempt": 1}
{"dynamo_cpp_guards_str": {}, "rank": 0, "frame_id": 0, "frame_compile_id": 0, "attempt": 1, "has_payload": "HASH"}
{"compilation_metrics": "METRICS", "rank": 0, "frame_id": 0, "frame_compile_id": 0, "attempt": 1}
{"dynamo_start": {"stack": "STACK"}, "rank": 0, "frame_id": 1, "frame_compile_id": 0, "attempt": 0}
{"artifact": {"name": "dynamo_graph_break_reason", "encoding": "string"}, "rank": 0, "frame_id": 1, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"dynamo_cpp_guards_str": {}, "rank": 0, "frame_id": 1, "frame_compile_id": 0, "attempt": 1, "has_payload": "HASH"}
{"compilation_metrics": "METRICS", "rank": 0, "frame_id": 1, "frame_compile_id": 0, "attempt": 1}
{"dynamo_start": {"stack": "STACK"}, "rank": 0, "frame_id": 2, "frame_compile_id": 0, "attempt": 0}
{"artifact": {"name": "dynamo_graph_break_reason", "encoding": "string"}, "rank": 0, "frame_id": 2, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"dynamo_cpp_guards_str": {}, "rank": 0, "frame_id": 2, "frame_compile_id": 0, "attempt": 1, "has_payload": "HASH"}
{"compilation_metrics": "METRICS", "rank": 0, "frame_id": 2, "frame_compile_id": 0, "attempt": 1}
{"dynamo_start": {"stack": "STACK"}, "rank": 0, "frame_id": 3, "frame_compile_id": 0, "attempt": 0}
{"compilation_metrics": "METRICS", "rank": 0, "frame_id": 3, "frame_compile_id": 0, "attempt": 0}
{"dynamo_start": {"stack": "STACK"}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0}
{"describe_storage": {"id": 0, "describer_id": "ID", "size": 4194304}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0}
{"describe_tensor": {"id": 0, "ndim": 2, "dtype": "torch.float32", "device": "device(type='cuda', index=0)", "size": [1024, 1024], "dynamo_hint_overrides": {}, "is_leaf": true, "requires_grad": true, "is_parameter": true, "stride": [1024, 1], "storage": 0, "view_func": "VIEW_FUNC", "describer_id": "ID"}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0}
{"describe_source": {"describer_id": "ID", "id": 0, "source": "L['self']._modules['layers']._modules['0']._parameters['weight']"}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0}
{"describe_storage": {"id": 1, "describer_id": "ID", "size": 4096}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0}
{"describe_tensor": {"id": 1, "ndim": 1, "dtype": "torch.float32", "device": "device(type='cuda', index=0)", "size": [1024], "dynamo_hint_overrides": {}, "is_leaf": true, "requires_grad": true, "is_parameter": true, "stride": [1], "storage": 1, "view_func": "VIEW_FUNC", "describer_id": "ID"}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0}
{"describe_source": {"describer_id": "ID", "id": 1, "source": "L['self']._modules['layers']._modules['0']._parameters['bias']"}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0}
{"describe_storage": {"id": 2, "describer_id": "ID", "size": 4194304}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0}
{"describe_tensor": {"id": 2, "ndim": 2, "dtype": "torch.float32", "device": "device(type='cuda', index=0)", "size": [1024, 1024], "dynamo_hint_overrides": {}, "is_leaf": true, "stride": [1024, 1], "storage": 2, "view_func": "VIEW_FUNC", "describer_id": "ID"}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0}
{"describe_source": {"describer_id": "ID", "id": 2, "source": "L['x']"}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0}
{"describe_storage": {"id": 3, "describer_id": "ID", "size": 4194304}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0}
{"describe_tensor": {"id": 8, "ndim": 2, "dtype": "torch.float32", "device": "device(type='cuda', index=0)", "size": [1024, 1024], "dynamo_hint_overrides": {}, "is_leaf": true, "requires_grad": true, "is_parameter": true, "stride": [1024, 1], "storage": 3, "view_func": "VIEW_FUNC", "describer_id": "ID"}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0}
{"describe_source": {"describer_id": "ID", "id": 8, "source": "L['self']._modules['layers']._modules['1']._parameters['weight']"}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0}
{"describe_storage": {"id": 4, "describer_id": "ID", "size": 4096}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0}
{"describe_tensor": {"id": 9, "ndim": 1, "dtype": "torch.float32", "device": "device(type='cuda', index=0)", "size": [1024], "dynamo_hint_overrides": {}, "is_leaf": true, "requires_grad": true, "is_parameter": true, "stride": [1], "storage": 4, "view_func": "VIEW_FUNC", "describer_id": "ID"}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0}
{"describe_source": {"describer_id": "ID", "id": 9, "source": "L['self']._modules['layers']._modules['1']._parameters['bias']"}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0}
{"dynamo_output_graph": {"sizes": {"l_self_modules_layers_modules_0_parameters_weight_": [1024, 1024], "l_self_modules_layers_modules_0_parameters_bias_": [1024], "l_x_": [1024, 1024], "l_self_modules_layers_modules_1_parameters_weight_": [1024, 1024], "l_self_modules_layers_modules_1_parameters_bias_": [1024], "input_1": [1024, 1024], "input_2": [1024, 1024]}}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"optimize_ddp_split_graph": {}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"optimize_ddp_split_child": {"name": "submod_0"}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"optimize_ddp_split_child": {"name": "submod_1"}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"describe_storage": {"id": 0, "describer_id": "ID", "size": 4194304}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0}
{"describe_tensor": {"id": 0, "ndim": 2, "dtype": "torch.float32", "device": "device(type='cuda', index=0)", "size": [1024, 1024], "dynamo_hint_overrides": {}, "is_leaf": true, "stride": [1024, 1], "storage": 0, "view_func": "VIEW_FUNC", "describer_id": "ID"}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0}
{"describe_source": {"describer_id": "ID", "id": 0, "source": "L['x']"}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0}
{"describe_storage": {"id": 1, "describer_id": "ID", "size": 4194304}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0}
{"describe_tensor": {"id": 1, "ndim": 2, "dtype": "torch.float32", "device": "device(type='cuda', index=0)", "size": [1024, 1024], "dynamo_hint_overrides": {}, "is_leaf": true, "requires_grad": true, "is_parameter": true, "stride": [1024, 1], "storage": 1, "view_func": "VIEW_FUNC", "describer_id": "ID"}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0}
{"describe_source": {"describer_id": "ID", "id": 1, "source": "L['self']._modules['layers']._modules['0']._parameters['weight']"}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0}
{"describe_storage": {"id": 2, "describer_id": "ID", "size": 4096}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0}
{"describe_tensor": {"id": 2, "ndim": 1, "dtype": "torch.float32", "device": "device(type='cuda', index=0)", "size": [1024], "dynamo_hint_overrides": {}, "is_leaf": true, "requires_grad": true, "is_parameter": true, "stride": [1], "storage": 2, "view_func": "VIEW_FUNC", "describer_id": "ID"}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0}
{"describe_source": {"describer_id": "ID", "id": 2, "source": "L['self']._modules['layers']._modules['0']._parameters['bias']"}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0}
{"artifact": {"name": "before_pre_grad_graph", "encoding": "string"}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "after_pre_grad_graph", "encoding": "string"}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "aotautograd_cache_bypass", "encoding": "json"}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"aot_joint_graph": {}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "torch._functorch.config", "encoding": "string"}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "aot_forward_graph_fw_metadata", "encoding": "string"}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"aot_forward_graph": {}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"aot_backward_graph": {}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "fx_graph_runnable", "encoding": "string"}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "before_post_grad_graph", "encoding": "string"}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "inductor_post_grad_graph", "encoding": "string"}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"inductor_output_code": {"filename": "FILENAME", "file_path": "FILENAME"}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "fx_graph_cache_miss", "encoding": "json"}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"describe_storage": {"id": 16, "describer_id": "ID", "size": 4194304}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0}
{"describe_tensor": {"id": 28, "ndim": 2, "dtype": "torch.float32", "device": "device(type='cuda', index=0)", "size": [1024, 1024], "dynamo_hint_overrides": {}, "is_leaf": true, "requires_grad": true, "is_parameter": true, "stride": [1024, 1], "storage": 16, "view_func": "VIEW_FUNC", "describer_id": "ID"}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0}
{"describe_source": {"describer_id": "ID", "id": 28, "source": "L['self']._modules['layers']._modules['1']._parameters['weight']"}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0}
{"describe_storage": {"id": 17, "describer_id": "ID", "size": 4096}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0}
{"describe_tensor": {"id": 29, "ndim": 1, "dtype": "torch.float32", "device": "device(type='cuda', index=0)", "size": [1024], "dynamo_hint_overrides": {}, "is_leaf": true, "requires_grad": true, "is_parameter": true, "stride": [1], "storage": 17, "view_func": "VIEW_FUNC", "describer_id": "ID"}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0}
{"describe_source": {"describer_id": "ID", "id": 29, "source": "L['self']._modules['layers']._modules['1']._parameters['bias']"}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0}
{"artifact": {"name": "before_pre_grad_graph", "encoding": "string"}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "after_pre_grad_graph", "encoding": "string"}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "aotautograd_cache_bypass", "encoding": "json"}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"aot_joint_graph": {}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "torch._functorch.config", "encoding": "string"}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "aot_forward_graph_fw_metadata", "encoding": "string"}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"aot_forward_graph": {}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"aot_backward_graph": {}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "fx_graph_runnable", "encoding": "string"}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "before_post_grad_graph", "encoding": "string"}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "inductor_post_grad_graph", "encoding": "string"}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"inductor_output_code": {"filename": "FILENAME", "file_path": "FILENAME"}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "fx_graph_cache_miss", "encoding": "json"}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"dynamo_cpp_guards_str": {}, "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"compilation_metrics": "METRICS", "rank": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0}
""", # noqa: B950
)
self.assertParses()
@requires_tlparse
def test_graph_breaks(self):
@torch.compile(backend="inductor")
def fn(x):
torch._dynamo.graph_break()
return x + 1
fn(torch.ones(1))
self.assertExpectedInline(
self.buffer.getvalue(),
"""\
{"dynamo_start": {"stack": "STACK"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"artifact": {"name": "dynamo_graph_break_reason", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"dynamo_cpp_guards_str": {}, "frame_id": 0, "frame_compile_id": 0, "attempt": 1, "has_payload": "HASH"}
{"compilation_metrics": "METRICS", "frame_id": 0, "frame_compile_id": 0, "attempt": 1}
{"dynamo_start": {"stack": "STACK"}, "frame_id": 1, "frame_compile_id": 0, "attempt": 0}
{"describe_storage": {"id": 0, "describer_id": "ID", "size": 4}, "frame_id": 1, "frame_compile_id": 0, "attempt": 0}
{"describe_tensor": {"id": 0, "ndim": 1, "dtype": "torch.float32", "device": "device(type='cpu')", "size": [1], "dynamo_hint_overrides": {}, "is_leaf": true, "stride": [1], "storage": 0, "view_func": "VIEW_FUNC", "describer_id": "ID"}, "frame_id": 1, "frame_compile_id": 0, "attempt": 0}
{"describe_source": {"describer_id": "ID", "id": 0, "source": "L['x']"}, "frame_id": 1, "frame_compile_id": 0, "attempt": 0}
{"dynamo_output_graph": {"sizes": {"l_x_": [1], "add": [1]}}, "frame_id": 1, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "before_pre_grad_graph", "encoding": "string"}, "frame_id": 1, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "after_pre_grad_graph", "encoding": "string"}, "frame_id": 1, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "aotautograd_cache_miss", "encoding": "json"}, "frame_id": 1, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "aot_forward_graph_fw_metadata", "encoding": "string"}, "frame_id": 1, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"aot_inference_graph": {}, "frame_id": 1, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "torch._functorch.config", "encoding": "string"}, "frame_id": 1, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "before_joint_graph", "encoding": "string"}, "frame_id": 1, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "after_joint_graph", "encoding": "string"}, "frame_id": 1, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "fx_graph_runnable", "encoding": "string"}, "frame_id": 1, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "before_post_grad_graph", "encoding": "string"}, "frame_id": 1, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "inductor_post_grad_graph", "encoding": "string"}, "frame_id": 1, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"inductor_output_code": {"filename": "FILENAME", "file_path": "FILENAME"}, "frame_id": 1, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "fx_graph_cache_miss", "encoding": "json"}, "frame_id": 1, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"dynamo_cpp_guards_str": {}, "frame_id": 1, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"compilation_metrics": "METRICS", "frame_id": 1, "frame_compile_id": 0, "attempt": 0}
""", # noqa: B950
)
self.assertParses()
# TODO: bring in the trace_source tests once we start emitting bytecode
@requires_tlparse
def test_graph_sizes_dynamic(self):
def fn(a, b):
return a @ b
fn_opt = torch.compile(fn, backend="eager", dynamic=False)
fn_opt(torch.randn(10, 20), torch.randn(20, 30))
fn_opt2 = torch.compile(fn, backend="eager", dynamic=True)
fn_opt2(torch.randn(5, 10), torch.randn(10, 15))
self.assertExpectedInline(
self.buffer.getvalue(),
"""\
{"dynamo_start": {"stack": "STACK"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"describe_storage": {"id": 0, "describer_id": "ID", "size": 800}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"describe_tensor": {"id": 0, "ndim": 2, "dtype": "torch.float32", "device": "device(type='cpu')", "size": [10, 20], "dynamo_hint_overrides": {}, "is_leaf": true, "stride": [20, 1], "storage": 0, "view_func": "VIEW_FUNC", "describer_id": "ID"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"describe_source": {"describer_id": "ID", "id": 0, "source": "L['a']"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"describe_storage": {"id": 1, "describer_id": "ID", "size": 2400}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"describe_tensor": {"id": 1, "ndim": 2, "dtype": "torch.float32", "device": "device(type='cpu')", "size": [20, 30], "dynamo_hint_overrides": {}, "is_leaf": true, "stride": [30, 1], "storage": 1, "view_func": "VIEW_FUNC", "describer_id": "ID"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"describe_source": {"describer_id": "ID", "id": 1, "source": "L['b']"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"dynamo_output_graph": {"sizes": {"l_a_": [10, 20], "l_b_": [20, 30], "matmul": [10, 30]}}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"dynamo_cpp_guards_str": {}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"compilation_metrics": "METRICS", "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"artifact": {"name": "recompile_reasons", "encoding": "json"}, "frame_id": 0, "frame_compile_id": 1, "attempt": 0, "has_payload": "HASH"}
{"dynamo_start": {"stack": "STACK"}, "frame_id": 0, "frame_compile_id": 1, "attempt": 0}
{"describe_storage": {"id": 0, "describer_id": "ID", "size": 200}, "frame_id": 0, "frame_compile_id": 1, "attempt": 0}
{"describe_tensor": {"id": 0, "ndim": 2, "dtype": "torch.float32", "device": "device(type='cpu')", "size": [5, 10], "dynamo_hint_overrides": {}, "is_leaf": true, "stride": [10, 1], "storage": 0, "view_func": "VIEW_FUNC", "describer_id": "ID"}, "frame_id": 0, "frame_compile_id": 1, "attempt": 0}
{"describe_source": {"describer_id": "ID", "id": 0, "source": "L['a']"}, "frame_id": 0, "frame_compile_id": 1, "attempt": 0}
{"create_symbol": {"symbol": "s97", "val": "5", "vr": "[2, int_oo]", "source": "L['a'].size()[0]", "user_stack": "STACK", "stack": "STACK"}, "frame_id": 0, "frame_compile_id": 1, "attempt": 0}
{"create_symbol": {"symbol": "s98", "val": "10", "vr": "[2, int_oo]", "source": "L['a'].size()[1]", "user_stack": "STACK", "stack": "STACK"}, "frame_id": 0, "frame_compile_id": 1, "attempt": 0}
{"describe_storage": {"id": 1, "describer_id": "ID", "size": 600}, "frame_id": 0, "frame_compile_id": 1, "attempt": 0}
{"describe_tensor": {"id": 1, "ndim": 2, "dtype": "torch.float32", "device": "device(type='cpu')", "size": [10, 15], "dynamo_hint_overrides": {}, "is_leaf": true, "stride": [15, 1], "storage": 1, "view_func": "VIEW_FUNC", "describer_id": "ID"}, "frame_id": 0, "frame_compile_id": 1, "attempt": 0}
{"describe_source": {"describer_id": "ID", "id": 1, "source": "L['b']"}, "frame_id": 0, "frame_compile_id": 1, "attempt": 0}
{"create_symbol": {"symbol": "s52", "val": "10", "vr": "[2, int_oo]", "source": "L['b'].size()[0]", "user_stack": "STACK", "stack": "STACK"}, "frame_id": 0, "frame_compile_id": 1, "attempt": 0}
{"create_symbol": {"symbol": "s20", "val": "15", "vr": "[2, int_oo]", "source": "L['b'].size()[1]", "user_stack": "STACK", "stack": "STACK"}, "frame_id": 0, "frame_compile_id": 1, "attempt": 0}
{"guard_added_fast": {"expr": "Eq(s98, s52)", "user_stack": "STACK", "stack": "STACK"}, "frame_id": 0, "frame_compile_id": 1, "attempt": 0}
{"dynamo_output_graph": {"sizes": {"l_a_": ["s97", "s52"], "l_b_": ["s52", "s20"], "matmul": ["s97", "s20"]}}, "frame_id": 0, "frame_compile_id": 1, "attempt": 0, "has_payload": "HASH"}
{"dynamo_cpp_guards_str": {}, "frame_id": 0, "frame_compile_id": 1, "attempt": 0, "has_payload": "HASH"}
{"compilation_metrics": "METRICS", "frame_id": 0, "frame_compile_id": 1, "attempt": 0}
""", # noqa: B950
)
self.assertParses()
@requires_tlparse
def test_guards_recompiles(self):
def fn(x, ys, zs):
return inner(x, ys, zs)
def inner(x, ys, zs):
for y, z in zip(ys, zs):
x += y * z
return x
ys = [1.0, 2.0]
zs = [3.0]
x = torch.tensor([1.0])
fn_opt = torch.compile(fn, backend="eager")
fn_opt(x, ys, zs)
fn_opt(x, ys[:1], zs)
self.assertExpectedInline(
self.buffer.getvalue(),
"""\
{"dynamo_start": {"stack": "STACK"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"describe_storage": {"id": 0, "describer_id": "ID", "size": 4}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"describe_tensor": {"id": 0, "ndim": 1, "dtype": "torch.float32", "device": "device(type='cpu')", "size": [1], "dynamo_hint_overrides": {}, "is_leaf": true, "stride": [1], "storage": 0, "view_func": "VIEW_FUNC", "describer_id": "ID"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"describe_source": {"describer_id": "ID", "id": 0, "source": "L['x']"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"dynamo_output_graph": {"sizes": {"l_x_": [1], "x": [1]}}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"dynamo_cpp_guards_str": {}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"compilation_metrics": "METRICS", "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"artifact": {"name": "recompile_reasons", "encoding": "json"}, "frame_id": 0, "frame_compile_id": 1, "attempt": 0, "has_payload": "HASH"}
{"dynamo_start": {"stack": "STACK"}, "frame_id": 0, "frame_compile_id": 1, "attempt": 0}
{"describe_storage": {"id": 0, "describer_id": "ID", "size": 4}, "frame_id": 0, "frame_compile_id": 1, "attempt": 0}
{"describe_tensor": {"id": 0, "ndim": 1, "dtype": "torch.float32", "device": "device(type='cpu')", "size": [1], "dynamo_hint_overrides": {}, "is_leaf": true, "stride": [1], "storage": 0, "view_func": "VIEW_FUNC", "describer_id": "ID"}, "frame_id": 0, "frame_compile_id": 1, "attempt": 0}
{"describe_source": {"describer_id": "ID", "id": 0, "source": "L['x']"}, "frame_id": 0, "frame_compile_id": 1, "attempt": 0}
{"dynamo_output_graph": {"sizes": {"l_x_": [1], "x": [1]}}, "frame_id": 0, "frame_compile_id": 1, "attempt": 0, "has_payload": "HASH"}
{"dynamo_cpp_guards_str": {}, "frame_id": 0, "frame_compile_id": 1, "attempt": 0, "has_payload": "HASH"}
{"compilation_metrics": "METRICS", "frame_id": 0, "frame_compile_id": 1, "attempt": 0}
""", # noqa: B950
)
self.assertParses()
def test_dump_file(self):
def f(x, y):
return x.add(y)
gm = fx.symbolic_trace(f)
torch.compile(gm, backend="eager")(torch.randn(3), torch.randn(3))
self.assertExpectedInline(
self.buffer.getvalue(),
"""\
{"dynamo_start": {"stack": "STACK"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"dump_file": {"name": "<eval_with_key>"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
def forward(self, x, y):
add = x.add(y); x = y = None
return add
{"describe_storage": {"id": 0, "describer_id": "ID", "size": 12}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"describe_tensor": {"id": 0, "ndim": 1, "dtype": "torch.float32", "device": "device(type='cpu')", "size": [3], "dynamo_hint_overrides": {}, "is_leaf": true, "stride": [1], "storage": 0, "view_func": "VIEW_FUNC", "describer_id": "ID"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"describe_source": {"describer_id": "ID", "id": 0, "source": "L['x']"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"describe_storage": {"id": 1, "describer_id": "ID", "size": 12}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"describe_tensor": {"id": 1, "ndim": 1, "dtype": "torch.float32", "device": "device(type='cpu')", "size": [3], "dynamo_hint_overrides": {}, "is_leaf": true, "stride": [1], "storage": 1, "view_func": "VIEW_FUNC", "describer_id": "ID"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"describe_source": {"describer_id": "ID", "id": 1, "source": "L['y']"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"dynamo_output_graph": {"sizes": {"l_x_": [3], "l_y_": [3], "add": [3]}}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"dynamo_cpp_guards_str": {}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"compilation_metrics": "METRICS", "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
""", # noqa: B950
)
@requires_tlparse
@torch._inductor.config.patch("fx_graph_cache", True)
def test_codecache(self):
def fn(a):
return a.sin()
x = torch.tensor([1.0])
fn_opt = torch.compile(fn, backend="inductor")
fn_opt(x)
torch._dynamo.reset()
# Trigger a cache hit
fn_opt(x)
# Should print twice, including inductor_output_code
self.assertExpectedInline(
self.buffer.getvalue(),
"""\
{"dynamo_start": {"stack": "STACK"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"describe_storage": {"id": 0, "describer_id": "ID", "size": 4}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"describe_tensor": {"id": 0, "ndim": 1, "dtype": "torch.float32", "device": "device(type='cpu')", "size": [1], "dynamo_hint_overrides": {}, "is_leaf": true, "stride": [1], "storage": 0, "view_func": "VIEW_FUNC", "describer_id": "ID"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"describe_source": {"describer_id": "ID", "id": 0, "source": "L['a']"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"dynamo_output_graph": {"sizes": {"l_a_": [1], "sin": [1]}}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "before_pre_grad_graph", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "after_pre_grad_graph", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "aotautograd_cache_miss", "encoding": "json"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "aot_forward_graph_fw_metadata", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"aot_inference_graph": {}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "torch._functorch.config", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "before_joint_graph", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "after_joint_graph", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "fx_graph_runnable", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "before_post_grad_graph", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "inductor_post_grad_graph", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"inductor_output_code": {"filename": "FILENAME", "file_path": "FILENAME"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "fx_graph_cache_miss", "encoding": "json"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"dynamo_cpp_guards_str": {}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"compilation_metrics": "METRICS", "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"dynamo_start": {"stack": "STACK"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"describe_storage": {"id": 0, "describer_id": "ID", "size": 4}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"describe_tensor": {"id": 0, "ndim": 1, "dtype": "torch.float32", "device": "device(type='cpu')", "size": [1], "dynamo_hint_overrides": {}, "is_leaf": true, "stride": [1], "storage": 0, "view_func": "VIEW_FUNC", "describer_id": "ID"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"describe_source": {"describer_id": "ID", "id": 0, "source": "L['a']"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"dynamo_output_graph": {"sizes": {"l_a_": [1], "sin": [1]}}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "before_pre_grad_graph", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "after_pre_grad_graph", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "aot_forward_graph_fw_metadata", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"aot_inference_graph": {}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "fx_graph_runnable", "encoding": "string"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"inductor_post_grad_graph": {}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"inductor_output_code": {"filename": "FILENAME", "file_path": "FILENAME"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "inductor_provenance_tracking_node_mappings", "encoding": "json"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"artifact": {"name": "inductor_provenance_tracking_kernel_stack_traces", "encoding": "json"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
{"artifact": {"name": "fx_graph_cache_hit", "encoding": "json"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"artifact": {"name": "aotautograd_cache_hit", "encoding": "json"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"dynamo_cpp_guards_str": {}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, "has_payload": "HASH"}
{"compilation_metrics": "METRICS", "frame_id": 0, "frame_compile_id": 0, "attempt": 0}
""", # noqa: B950
)
self.assertParses()
@requires_tlparse
def test_make_fx_fail_partial(self):
from torch.fx.experimental.proxy_tensor import make_fx
payload_buffer = io.StringIO()
payload_handler = logging.StreamHandler(payload_buffer)
payload_handler.setFormatter(StructuredTracePayloadFormatter())
payload_handler.addFilter(StructuredTraceTestingFilter("make_fx_fail_partial"))
trace_log.addHandler(payload_handler)
def f(x):
y = x + 1 # noqa: F841
raise RuntimeError("boo")
try:
make_fx(f)(torch.randn(2))
except RuntimeError:
pass
self.assertExpectedInline(
self.buffer.getvalue(),
"""\
{"artifact": {"name": "make_fx_fail_partial", "encoding": "string"}, "stack": "STACK", "has_payload": "HASH"}
""",
)
self.assertExpectedInline(
payload_buffer.getvalue(),
"""\
def forward(self, x_1: "f32[2][1]cpu"):
# No stacktrace found for following nodes
add: "f32[2][1]cpu" = torch.ops.aten.add.Tensor(x_1, 1); x_1 = add = None
""",
)
@requires_tlparse
@torch._inductor.config.patch("fx_graph_cache", True)
@show_chrome_events
def test_chromium_event(self):
def fn(a):
return a.sin()
x = torch.tensor([1.0])
fn_opt = torch.compile(fn, backend="inductor")
fn_opt(x)
torch._dynamo.reset()
# Trigger a cache hit
fn_opt(x)
# Should print twice, including inductor_output_code
self.assertParses()
chromium_event = (
'{"chromium_event": {}, "frame_id": 0, "frame_compile_id": 0, '
'"attempt": 0, "has_payload": "HASH"}'
)
self.assertTrue(chromium_event in self.buffer.getvalue())
@requires_tlparse
@torch._dynamo.config.patch("compiled_autograd", True)
@torch._inductor.config.patch("fx_graph_cache", True)
@show_chrome_events
def test_compiled_autograd_id(self):
def fn(a):
return a.sin().sum().backward()
x = torch.tensor([1.0], requires_grad=True)
fn_opt = torch._dynamo.optimize("inductor")(fn)
fn_opt(x)
torch._dynamo.reset()
# Trigger a cache hit
fn_opt(x)
# Should print twice, including inductor_output_code
self.assertParses()
chromium_events = [
(
'{"chromium_event": {}, "frame_id": 0, "frame_compile_id": 0, '
'"attempt": 0, "has_payload": "HASH"}'
),
(
'{"compiled_autograd_graph": {}, "compiled_autograd_id": 0, '
'"attempt": 0, "has_payload": "HASH"}'
),
(
'{"chromium_event": {}, "compiled_autograd_id": 0, "frame_id": 2, "frame_compile_id": 0, '
'"attempt": 0, "has_payload": "HASH"}'
),
]
logs = self.buffer.getvalue()
self.assertTrue(all(event in logs for event in chromium_events))
@requires_tlparse
@torch._dynamo.config.patch("compiled_autograd", True)
def test_compiled_autograd_attribution(self):
# multiple dynamo recompiles should still be attributed to the parent compiled autograd id
def fn():
class MySin(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
ctx.save_for_backward(x)
return torch.sin(x)
@staticmethod
def backward(ctx, gO):
print("graph break")
(x,) = ctx.saved_tensors
print("graph break")
return gO * torch.cos(x)
grads = []
for i in [10, 100, 10, 15, 20, 25]:
x = torch.arange(0.0, i, requires_grad=True)
out = MySin.apply(x)
loss = out.sum()
loss.backward()
grads.append(x.grad)
return grads
fn_opt = torch.compile(fn)
fn_opt()
self.assertParses()
expected = [
'{"dynamo_start": {"stack": "STACK"}, "frame_id": 0, "frame_compile_id": 0, "attempt": 0}',
'{"dynamo_start": {"stack": "STACK"}, "frame_id": 1, "frame_compile_id": 0, "attempt": 0}',
'{"dynamo_start": {"stack": "STACK"}, "frame_id": 2, "frame_compile_id": 0, "attempt": 0}',
'{"dynamo_start": {"stack": "STACK"}, "compiled_autograd_id": 0, "frame_id": 4, "frame_compile_id": 0, "attempt": 0}',
'{"dynamo_start": {"stack": "STACK"}, "compiled_autograd_id": 0, "frame_id": 5, "frame_compile_id": 0, "attempt": 0}',
'{"dynamo_start": {"stack": "STACK"}, "compiled_autograd_id": 0, "frame_id": 6, "frame_compile_id": 0, "attempt": 0}',
'{"dynamo_start": {"stack": "STACK"}, "compiled_autograd_id": 0, "frame_id": 7, "frame_compile_id": 0, "attempt": 0}',
'{"dynamo_start": {"stack": "STACK"}, "compiled_autograd_id": 0, "frame_id": 8, "frame_compile_id": 0, "attempt": 0}',
'{"dynamo_start": {"stack": "STACK"}, "compiled_autograd_id": 0, "frame_id": 9, "frame_compile_id": 0, "attempt": 0}',
'{"dynamo_start": {"stack": "STACK"}, "compiled_autograd_id": 1, "frame_id": 12, "frame_compile_id": 1, "attempt": 0}',
]
logs = self.buffer.getvalue()
self.assertTrue(all(event in logs for event in expected))
@requires_tlparse
@show_chrome_events
def test_compiled_autograd_chromium(self):
with torch._dynamo.compiled_autograd._enable(torch.compile):
for i in [10, 100, 10, 15, 20, 25]:
x = torch.arange(0.0, i, requires_grad=True)
loss = x.sum()
loss.backward()
self.assertParses()
expected = [
'{"chromium_event": {}, "compiled_autograd_id": 0, "attempt": 0, "has_payload": "HASH"}',
'{"chromium_event": {}, "compiled_autograd_id": 0, "frame_id": 0, "frame_compile_id": 0, "attempt": 0, '
'"has_payload": "HASH"}',
'{"chromium_event": {}, "compiled_autograd_id": 0, "frame_id": 0, "frame_compile_id": 1, "attempt": 0, '
'"has_payload": "HASH"}',
]
logs = self.buffer.getvalue()
self.assertTrue(all(event in logs for event in expected))
def test_recompile_user_contexts(self):
# test that user_context is called only once per recompile
num_calls = 0
def f(x):
return x + 1
f = torch.compile(f)
def user_context() -> str:
nonlocal num_calls
num_calls += 1
return "user_context: " + str(num_calls)
torch._dynamo.register_hook_for_recompile_user_context(user_context)
for _ in range(10):
f(torch.randn(1, 5))
# first compile
self.assertEqual(num_calls, 1)
for i in range(2, 10):
f(torch.randn(i, 5))
# first compile + recompile once
self.assertEqual(num_calls, 2)
def test_recompile_user_contexts_iteration(self):
class Step:
def __init__(self):
self.step = 0
def next_step(self):
self.step += 1
step = Step()
def f(x):
return x + 1
f = torch.compile(f)
def user_context() -> str:
return "user_context: " + str(step.step)
torch._dynamo.register_hook_for_recompile_user_context(user_context)
for i in range(10):
f(torch.randn(i + 2 // 3, 5))
step.next_step()
@contextmanager
def _setup_collective_schedule_capture(self):
"""Helper to turn on and capture the 'inductor_collective_schedule' structured trace."""
payload_buffer = io.StringIO()
payload_handler = logging.StreamHandler(payload_buffer)
payload_handler.setLevel(logging.DEBUG)
payload_handler.setFormatter(StructuredTracePayloadFormatter())
payload_handler.addFilter(
StructuredTraceTestingFilter("inductor_collective_schedule")
)
trace_log.addHandler(payload_handler)
try:
yield payload_buffer
finally:
trace_log.removeHandler(payload_handler)
@requires_tlparse
def test_collective_schedule_empty(self):
"""Verify logging when no collective kernels are present (empty schedule)."""
with self._setup_collective_schedule_capture() as payload_buffer:
from torch._inductor.debug import log_collective_schedule
log_collective_schedule([])
# With no collectives, artifact should not be logged and payload should be empty
self.assertNotIn('"inductor_collective_schedule"', self.buffer.getvalue())
self.assertEqual(payload_buffer.getvalue().strip(), "")
@requires_tlparse
@requires_distributed()
@torch._inductor.config.patch("fx_graph_cache", False)
def test_collective_schedule_real(self):
"""Test collective schedule with _c10d_functional ops that work with FakeStore."""
import torch.distributed as dist
store = FakeStore()
dist.init_process_group(backend="fake", rank=0, world_size=2, store=store)
class CollectiveModule(torch.nn.Module):
def forward(self, x):
# Use _c10d_functional ops that actually trigger collective kernels
y = torch.ops._c10d_functional.all_reduce.default(x, "sum", "0")
y = torch.ops._c10d_functional.wait_tensor.default(y)
return y * 2
try:
with self._setup_collective_schedule_capture() as payload_buffer:
torch._dynamo.reset()
mod = CollectiveModule()
compiled = torch.compile(mod, backend="inductor")
compiled(torch.randn(4, 4))
# Verify collective schedule artifact was logged
self.assertIn('"inductor_collective_schedule"', self.buffer.getvalue())
payload_content = payload_buffer.getvalue().strip()
schedule = json.loads(payload_content)
self.assertIsInstance(schedule, list)
# Verify expected collective operations are present
self.assertExpectedInline(
str(schedule),
"""\
['torch.ops._c10d_functional.all_reduce_.default', 'torch.ops._c10d_functional.wait_tensor.default']\
""",
)
self.assertParses()
finally:
dist.destroy_process_group()
@contextmanager
def _setup_runtime_estimates_capture(self):
"""Helper to turn on and capture the combined 'inductor_runtime_and_tensor_meta' structured trace."""
payload_buffer = io.StringIO()
payload_handler = logging.StreamHandler(payload_buffer)
payload_handler.setLevel(logging.DEBUG)
payload_handler.setFormatter(StructuredTracePayloadFormatter())
payload_handler.addFilter(
StructuredTraceTestingFilter("inductor_runtime_and_tensor_meta")
)
trace_log.addHandler(payload_handler)
try:
yield payload_buffer
finally:
trace_log.removeHandler(payload_handler)
@requires_tlparse
@requires_distributed()
@requires_cuda_and_triton
@torch._inductor.config.patch("fx_graph_cache", False)
@torch._inductor.config.patch("log_tlparse", True)
def test_runtime_estimates_simple(self):
"""Test runtime estimates logging with simple compute and collective ops."""
import torch.distributed as dist
store = FakeStore()
dist.init_process_group(backend="fake", rank=0, world_size=2, store=store)
class SimpleModule(torch.nn.Module):
def __init__(self):
super().__init__()
self.linear = torch.nn.Linear(4, 4)
def forward(self, x):
h = self.linear(x)
h = torch.relu(h)
h = torch.ops._c10d_functional.all_reduce.default(h, "sum", "0")
h = torch.ops._c10d_functional.wait_tensor.default(h)
return h
try:
with self._setup_runtime_estimates_capture() as payload_buffer:
torch._dynamo.reset()
mod = SimpleModule().cuda()
compiled = torch.compile(mod, backend="inductor")
compiled(torch.randn(4, 4, device="cuda"))
# Verify runtime + tensor meta artifact was logged
self.assertIn(
'"inductor_runtime_and_tensor_meta"', self.buffer.getvalue()
)
payload_content = payload_buffer.getvalue().strip()
if payload_content:
data = json.loads(payload_content)
self.assertIn("ops", data)
ops = data["ops"]
# Verify runtime estimates
compute_ops = [op for op in ops if op["type"] == "compute"]
collective_ops = [op for op in ops if op["type"] == "collective"]
self.assertTrue(len(compute_ops) > 0 or len(collective_ops) > 0)
# Just check each op has an estimated runtime value (any value, including 0)
for op in ops:
self.assertIn("estimated_runtime_ns", op)
self.assertIsNotNone(op["estimated_runtime_ns"])
self.assertParses()
finally:
dist.destroy_process_group()
@requires_tlparse
@requires_distributed()
@requires_cuda_and_triton
@torch._inductor.config.patch("fx_graph_cache", False)
@torch._inductor.config.patch("log_tlparse", True)
def test_runtime_estimates_mixed(self):
"""Test runtime estimates logging with mixed compute and collective sequence."""
import torch.distributed as dist
store = FakeStore()
dist.init_process_group(backend="fake", rank=0, world_size=2, store=store)
class MixedModule(torch.nn.Module):
def __init__(self):
super().__init__()
self.norm = torch.nn.LayerNorm(4)
def forward(self, x):
h = self.norm(x)
h = torch.nn.functional.gelu(h)
h = torch.ops._c10d_functional.all_reduce.default(h, "sum", "0")
h = torch.ops._c10d_functional.wait_tensor.default(h)
h = h * 0.5
gathered = torch.ops._c10d_functional.all_gather_into_tensor.default(
h, 2, "0"
)
gathered = torch.ops._c10d_functional.wait_tensor.default(gathered)
return gathered.sum(dim=0)
try:
with self._setup_runtime_estimates_capture() as payload_buffer:
torch._dynamo.reset()
mod = MixedModule().cuda()
compiled = torch.compile(mod, backend="inductor")
compiled(torch.randn(4, 4, device="cuda"))
# Verify artifact was logged
self.assertIn(
'"inductor_runtime_and_tensor_meta"', self.buffer.getvalue()
)
payload_content = payload_buffer.getvalue().strip()
if payload_content:
data = json.loads(payload_content)
self.assertIn("ops", data)
ops = data["ops"]
# Should have both compute and collective ops
op_types = {op["type"] for op in ops}
self.assertIn("compute", op_types)
self.assertIn("collective", op_types)
# Just check each op has an estimated runtime value (any value, including 0)
for op in ops:
self.assertIn("estimated_runtime_ns", op)
self.assertIsNotNone(op["estimated_runtime_ns"])
self.assertParses()
finally:
dist.destroy_process_group()
@requires_tlparse
@requires_distributed()
@requires_cuda_and_triton
@torch._inductor.config.patch("fx_graph_cache", False)
@torch._inductor.config.patch("log_tlparse", True)
def test_tensor_metadata_logging_multiple_ops(self):
import torch.distributed as dist
store = FakeStore()
dist.init_process_group(backend="fake", rank=0, world_size=2, store=store)
class Mixed(torch.nn.Module):
def __init__(self):
super().__init__()
self.linear = torch.nn.Linear(4, 4)
def forward(self, x):
y = torch.relu(self.linear(x))
y = torch.ops._c10d_functional.all_reduce.default(y, "sum", "0")
y = torch.ops._c10d_functional.wait_tensor.default(y)
return y + 1
try:
with self._setup_runtime_estimates_capture() as payload_buffer:
torch._dynamo.reset()
mod = Mixed().cuda()
compiled = torch.compile(mod, backend="inductor")
compiled(torch.randn(4, 4, device="cuda"))
payload = payload_buffer.getvalue().strip()
if payload:
data = json.loads(payload)
types = sorted({op.get("type") for op in data.get("ops", [])})
self.assertExpectedInline(
str(types), """['collective', 'compute']"""
)
self.assertParses()
finally:
dist.destroy_process_group()
@requires_tlparse
@torch._inductor.config.patch("log_tlparse", True)
def test_tensor_metadata_logging(self):
"""Emit unified runtime+tensor-metadata artifact and assert a stable simplified JSON inline."""
with self._setup_runtime_estimates_capture() as payload_buffer:
def f(x):
y = x.transpose(0, 1)
z = y.mean(dim=0)
w = z.to(torch.float16)
return w
compiled = torch.compile(f, backend="inductor", fullgraph=True)
compiled(torch.ones(2, 3))
# Verify artifact was logged
self.assertIn('"inductor_runtime_and_tensor_meta"', self.buffer.getvalue())
payload = payload_buffer.getvalue().strip()
if payload:
data = json.loads(payload)
ops = data.get("ops", [])
simplified_ops = []
for op in ops:
outs = [
{
"shape": out.get("shape", []),
"stride": out.get("stride", []),
"dtype": out.get("dtype", None),
}
for out in op.get("outputs", [])
]
if outs:
simplified_ops.append(
{
"type": op.get("type", ""),
"outputs": outs,
}
)
self.assertExpectedInline(
{"ops": simplified_ops[-1:]} if simplified_ops else {"ops": []},
"""{'ops': [{'type': 'compute', 'outputs': [{'shape': [2], 'stride': [1], 'dtype': 'float16'}]}]}""",
)
self.assertParses()
@requires_tlparse
@torch._inductor.config.patch("log_tlparse", True)
def test_tensor_metadata_logging_dynamic_shapes(self):
"""Same as test_tensor_metadata_logging, but with dynamic shapes enabled to cover to_size_hints."""
with self._setup_runtime_estimates_capture() as payload_buffer:
def f(x):
y = x.transpose(0, 1)
z = y.mean(dim=0)
w = z.to(torch.float16)
return w
compiled = torch.compile(f, backend="inductor", dynamic=True)
compiled(torch.ones(2, 3))
# Verify artifact was logged
self.assertIn('"inductor_runtime_and_tensor_meta"', self.buffer.getvalue())
payload = payload_buffer.getvalue().strip()
if payload:
data = json.loads(payload)
ops = data.get("ops", [])
simplified_ops = []
for op in ops:
outs = [
{
"shape": out.get("shape", []),
"stride": out.get("stride", []),
"dtype": out.get("dtype", None),
}
for out in op.get("outputs", [])
]
if outs:
simplified_ops.append(
{
"type": op.get("type", ""),
"outputs": outs,
}
)
self.assertExpectedInline(
{"ops": simplified_ops[-1:]} if simplified_ops else {"ops": []},
(
"{'ops': [{'type': 'compute', 'outputs': ["
"{'shape': [2], 'stride': [1], 'dtype': 'float32'}, "
"{'shape': [2], 'stride': [1], 'dtype': 'float16'}]}]}"
),
)
self.assertParses()
@contextmanager
def _setup_graph_execution_capture(self):
"""Helper to capture the 'graph_execution' structured trace."""
payload_buffer = io.StringIO()
payload_handler = logging.StreamHandler(payload_buffer)
payload_handler.setLevel(logging.DEBUG)
payload_handler.setFormatter(StructuredTracePayloadFormatter())
payload_handler.addFilter(StructuredTraceTestingFilter("graph_execution"))
trace_log.addHandler(payload_handler)
try:
yield payload_buffer
finally:
trace_log.removeHandler(payload_handler)
@requires_tlparse
@torch._inductor.config.patch(force_disable_caches=True)
def test_graph_execution_order(self):
"""Verify graph execution order is aggregated into a single artifact."""
torch._dynamo.reset()
with self._setup_graph_execution_capture() as payload_buffer:
def fn(x):
y = x + 1
torch._dynamo.graph_break()
return y + 2
compiled = torch.compile(fn, backend="inductor")
from torch._inductor.debug import record_and_log_graph_execution_order
with record_and_log_graph_execution_order():
compiled(torch.randn(1))
payload_content = payload_buffer.getvalue().strip()
payload = json.loads(payload_content)
executions = payload["graph_execution_order"]
self.assertTrue(all(isinstance(e["compile_id"], str) for e in executions))
self.assertExpectedInline(
json.dumps(payload),
"""{"graph_execution_order": [{"compile_id": "0/0"}, {"compile_id": "1/0"}]}""",
)
self.assertParses()
if __name__ == "__main__":
from torch._dynamo.test_case import run_tests
run_tests()
| StructuredTraceTest |
python | Lightning-AI__lightning | tests/tests_pytorch/test_cli.py | {
"start": 18413,
"end": 20076
} | class ____(BoringModel):
def __init__(self, out_dim: int = 2, hidden_dim: int = 2) -> None:
super().__init__()
self.save_hyperparameters()
self.hidden_dim = hidden_dim
self.layer = torch.nn.Linear(32, out_dim)
def test_lightning_cli_ckpt_path_argument_hparams(cleandir):
class CkptPathCLI(LightningCLI):
def add_arguments_to_parser(self, parser):
parser.link_arguments("model.out_dim", "model.hidden_dim", compute_fn=lambda x: x * 2)
cli_args = ["fit", "--model.out_dim=3", "--trainer.max_epochs=1"]
with mock.patch("sys.argv", ["any.py"] + cli_args):
cli = CkptPathCLI(BoringCkptPathModel)
assert cli.config.fit.model.out_dim == 3
assert cli.config.fit.model.hidden_dim == 6
hparams_path = Path(cli.trainer.log_dir) / "hparams.yaml"
assert hparams_path.is_file()
hparams = yaml.safe_load(hparams_path.read_text())
assert hparams["out_dim"] == 3
assert hparams["hidden_dim"] == 6
checkpoint_path = next(Path(cli.trainer.log_dir, "checkpoints").glob("*.ckpt"))
cli_args = ["predict", f"--ckpt_path={checkpoint_path}"]
with mock.patch("sys.argv", ["any.py"] + cli_args):
cli = CkptPathCLI(BoringCkptPathModel)
assert cli.config.predict.model.out_dim == 3
assert cli.config.predict.model.hidden_dim == 6
assert cli.config_init.predict.model.layer.out_features == 3
err = StringIO()
with mock.patch("sys.argv", ["any.py"] + cli_args), redirect_stderr(err), pytest.raises(SystemExit):
cli = LightningCLI(BoringModel)
assert "Parsing of ckpt_path hyperparameters failed" in err.getvalue()
| BoringCkptPathModel |
python | scipy__scipy | scipy/stats/tests/test_stats.py | {
"start": 179111,
"end": 187634
} | class ____:
def check_power_divergence(self, f_obs, f_exp, ddof, axis, lambda_,
expected_stat, xp):
dtype = xp.asarray(1.).dtype
f_obs = xp.asarray(f_obs, dtype=dtype)
f_exp = xp.asarray(f_exp, dtype=dtype) if f_exp is not None else f_exp
if axis is None:
num_obs = xp_size(f_obs)
else:
arrays = (xp.broadcast_arrays(f_obs, f_exp) if f_exp is not None
else (f_obs,))
num_obs = arrays[0].shape[axis]
with warnings.catch_warnings():
warnings.filterwarnings("ignore", "Mean of empty slice", RuntimeWarning)
stat, p = stats.power_divergence(
f_obs, f_exp=f_exp, ddof=ddof,
axis=axis, lambda_=lambda_)
xp_assert_close(stat, xp.asarray(expected_stat, dtype=dtype))
if lambda_ == 1 or lambda_ == "pearson":
# Also test stats.chisquare.
stat, p = stats.chisquare(f_obs, f_exp=f_exp, ddof=ddof,
axis=axis)
xp_assert_close(stat, xp.asarray(expected_stat, dtype=dtype))
ddof = np.asarray(ddof)
expected_p = stats.distributions.chi2.sf(expected_stat,
num_obs - 1 - ddof)
xp_assert_close(p, xp.asarray(expected_p, dtype=dtype))
@pytest.mark.parametrize('case', power_div_1d_cases)
@pytest.mark.parametrize('lambda_stat',
[(None, 'chi2'), ('pearson', 'chi2'), (1, 'chi2'),
('log-likelihood', 'log'), ('mod-log-likelihood', 'mod_log'),
('cressie-read', 'cr'), (2/3, 'cr')])
def test_basic(self, case, lambda_stat, xp):
lambda_, attr = lambda_stat
expected_stat = getattr(case, attr)
self.check_power_divergence(case.f_obs, case.f_exp, case.ddof, case.axis,
lambda_, expected_stat, xp)
def test_axis(self, xp):
case0 = power_div_1d_cases[0]
case1 = power_div_1d_cases[1]
f_obs = np.vstack((case0.f_obs, case1.f_obs))
f_exp = np.vstack((np.ones_like(case0.f_obs)*np.mean(case0.f_obs),
case1.f_exp))
# Check the four computational code paths in power_divergence
# using a 2D array with axis=1.
f_obs = xp.asarray(f_obs)
f_exp = xp.asarray(f_exp) if f_exp is not None else f_exp
self.check_power_divergence(
f_obs, f_exp, 0, 1,
"pearson", [case0.chi2, case1.chi2], xp=xp)
self.check_power_divergence(
f_obs, f_exp, 0, 1,
"log-likelihood", [case0.log, case1.log], xp=xp)
self.check_power_divergence(
f_obs, f_exp, 0, 1,
"mod-log-likelihood", [case0.mod_log, case1.mod_log], xp=xp)
self.check_power_divergence(
f_obs, f_exp, 0, 1,
"cressie-read", [case0.cr, case1.cr], xp=xp)
# Reshape case0.f_obs to shape (2,2), and use axis=None.
# The result should be the same.
f_obs_reshape = xp.reshape(xp.asarray(case0.f_obs), (2, 2))
self.check_power_divergence(
f_obs_reshape, None, 0, None,
"pearson", case0.chi2, xp=xp)
def test_ddof_broadcasting(self, xp):
# Test that ddof broadcasts correctly.
# ddof does not affect the test statistic. It is broadcast
# with the computed test statistic for the computation of
# the p value.
case0 = power_div_1d_cases[0]
case1 = power_div_1d_cases[1]
# Create 4x2 arrays of observed and expected frequencies.
f_obs = np.vstack((case0.f_obs, case1.f_obs)).T
f_exp = np.vstack((np.ones_like(case0.f_obs)*np.mean(case0.f_obs),
case1.f_exp)).T
expected_chi2 = [case0.chi2, case1.chi2]
dtype = xp.asarray(1.).dtype
f_obs = xp.asarray(f_obs, dtype=dtype)
f_exp = xp.asarray(f_exp, dtype=dtype)
expected_chi2 = xp.asarray(expected_chi2, dtype=dtype)
# ddof has shape (2, 1). This is broadcast with the computed
# statistic, so p will have shape (2,2).
ddof = xp.asarray([[0], [1]])
stat, p = stats.power_divergence(f_obs, f_exp, ddof=ddof)
xp_assert_close(stat, expected_chi2)
# Compute the p values separately, passing in scalars for ddof.
_, p0 = stats.power_divergence(f_obs, f_exp, ddof=ddof[0, 0])
_, p1 = stats.power_divergence(f_obs, f_exp, ddof=ddof[1, 0])
expected_p = xp.concat((p0[xp.newaxis, :], p1[xp.newaxis, :]), axis=0)
xp_assert_close(p, expected_p)
@pytest.mark.parametrize('case', power_div_empty_cases)
@pytest.mark.parametrize('lambda_stat',
[('pearson', 'chi2'), ('log-likelihood', 'log'),
('mod-log-likelihood', 'mod_log'),
('cressie-read', 'cr'), (2/3, 'cr')])
def test_empty_cases(self, case, lambda_stat, xp):
lambda_, attr = lambda_stat
expected_stat = getattr(case, attr)
with warnings.catch_warnings():
self.check_power_divergence(
case.f_obs, case.f_exp, case.ddof, case.axis,
lambda_, expected_stat, xp)
def test_power_divergence_result_attributes(self, xp):
f_obs = power_div_1d_cases[0].f_obs
f_exp = power_div_1d_cases[0].f_exp
ddof = power_div_1d_cases[0].ddof
axis = power_div_1d_cases[0].axis
dtype = xp.asarray(1.).dtype
f_obs = xp.asarray(f_obs, dtype=dtype)
# f_exp is None
res = stats.power_divergence(f_obs, f_exp=f_exp, ddof=ddof,
axis=axis, lambda_="pearson")
attributes = ('statistic', 'pvalue')
check_named_results(res, attributes, xp=xp)
def test_power_divergence_gh_12282(self, xp):
# The sums of observed and expected frequencies must match
f_obs = xp.asarray([[10., 20.], [30., 20.]])
f_exp = xp.asarray([[5., 15.], [35., 25.]])
message = 'For each axis slice...'
with pytest.raises(ValueError, match=message):
stats.power_divergence(f_obs, f_exp=xp.asarray([30., 60.]))
with pytest.raises(ValueError, match=message):
stats.power_divergence(f_obs, f_exp=f_exp, axis=1)
stat, pval = stats.power_divergence(f_obs, f_exp=f_exp)
xp_assert_close(stat, xp.asarray([5.71428571, 2.66666667]))
xp_assert_close(pval, xp.asarray([0.01682741, 0.10247043]))
def test_power_divergence_against_cressie_read_data(self, xp):
# Test stats.power_divergence against tables 4 and 5 from
# Cressie and Read, "Multimonial Goodness-of-Fit Tests",
# J. R. Statist. Soc. B (1984), Vol 46, No. 3, pp. 440-464.
# This tests the calculation for several values of lambda.
# Table 4 data recalculated for greater precision according to:
# Shelby J. Haberman, Analysis of Qualitative Data: Volume 1
# Introductory Topics, Academic Press, New York, USA (1978).
obs = xp.asarray([15., 11., 14., 17., 5., 11., 10., 4., 8.,
10., 7., 9., 11., 3., 6., 1., 1., 4.])
beta = -0.083769 # Haberman (1978), p. 15
i = xp.arange(1., obs.shape[0] + 1.)
alpha = xp.log(xp.sum(obs) / xp.sum(xp.exp(beta*i)))
expected_counts = xp.exp(alpha + beta*i)
# `table4` holds just the second and third columns from Table 4.
table4 = xp.concat((obs[xp.newaxis, :],
expected_counts[xp.newaxis, :])).T
table5 = xp.asarray([
# lambda, statistic
-10.0, 72.2e3,
-5.0, 28.9e1,
-3.0, 65.6,
-2.0, 40.6,
-1.5, 34.0,
-1.0, 29.5,
-0.5, 26.5,
0.0, 24.6,
0.5, 23.4,
0.67, 23.1,
1.0, 22.7,
1.5, 22.6,
2.0, 22.9,
3.0, 24.8,
5.0, 35.5,
10.0, 21.4e1,
])
table5 = xp.reshape(table5, (-1, 2))
for i in range(table5.shape[0]):
lambda_, expected_stat = table5[i, 0], table5[i, 1]
stat, p = stats.power_divergence(table4[:,0], table4[:,1],
lambda_=lambda_)
xp_assert_close(stat, expected_stat, rtol=5e-3)
@make_xp_test_case(stats.chisquare)
| TestPowerDivergence |
python | getsentry__sentry | src/sentry/incidents/models/alert_rule.py | {
"start": 4993,
"end": 5471
} | class ____(Model):
"""
Specify a project for the AlertRule
"""
__relocation_scope__ = RelocationScope.Organization
alert_rule = FlexibleForeignKey("sentry.AlertRule", db_index=False)
project = FlexibleForeignKey("sentry.Project")
date_added = models.DateTimeField(default=timezone.now)
class Meta:
app_label = "sentry"
db_table = "sentry_alertruleprojects"
unique_together = (("alert_rule", "project"),)
| AlertRuleProjects |
python | pypa__pipenv | pipenv/vendor/tomlkit/source.py | {
"start": 258,
"end": 1211
} | class ____:
def __init__(
self,
source: Source,
save_marker: bool | None = False,
restore: bool | None = False,
) -> None:
self._source = source
self._save_marker = save_marker
self.restore = restore
def __enter__(self) -> _State:
# Entering this context manager - save the state
self._chars = copy(self._source._chars)
self._idx = self._source._idx
self._current = self._source._current
self._marker = self._source._marker
return self
def __exit__(self, exception_type, exception_val, trace):
# Exiting this context manager - restore the prior state
if self.restore or exception_type:
self._source._chars = self._chars
self._source._idx = self._idx
self._source._current = self._current
if self._save_marker:
self._source._marker = self._marker
| _State |
python | keras-team__keras | keras/src/layers/layer.py | {
"start": 2266,
"end": 71405
} | class ____(BackendLayer, Operation):
"""This is the class from which all layers inherit.
A layer is a callable object that takes as input one or more tensors and
that outputs one or more tensors. It involves *computation*, defined
in the `call()` method, and a *state* (weight variables). State can be
created:
* in `__init__()`, for instance via `self.add_weight()`;
* in the optional `build()` method, which is invoked by the first
`__call__()` to the layer, and supplies the shape(s) of the input(s),
which may not have been known at initialization time.
Layers are recursively composable: If you assign a Layer instance as an
attribute of another Layer, the outer layer will start tracking the weights
created by the inner layer. Nested layers should be instantiated in the
`__init__()` method or `build()` method.
Users will just instantiate a layer and then treat it as a callable.
Args:
trainable: Boolean, whether the layer's variables should be trainable.
name: String name of the layer.
dtype: The dtype of the layer's computations and weights. Can also be a
`keras.DTypePolicy`, which allows the computation and weight dtype
to differ. Defaults to `None`. `None` means to use
`keras.config.dtype_policy()`, which is a `float32` policy unless
set to different value (via `keras.config.set_dtype_policy()`).
Attributes:
name: The name of the layer (string).
dtype: Dtype of the layer's weights. Alias of `layer.variable_dtype`.
variable_dtype: Dtype of the layer's weights.
compute_dtype: The dtype of the layer's computations.
Layers automatically cast inputs to this dtype, which causes
the computations and output to also be in this dtype.
When mixed precision is used with a
`keras.DTypePolicy`, this will be different
than `variable_dtype`.
trainable_weights: List of variables to be included in backprop.
non_trainable_weights: List of variables that should not be
included in backprop.
weights: The concatenation of the lists trainable_weights and
non_trainable_weights (in this order).
trainable: Whether the layer should be trained (boolean), i.e.
whether its potentially-trainable weights should be returned
as part of `layer.trainable_weights`.
input_spec: Optional (list of) `InputSpec` object(s) specifying the
constraints on inputs that can be accepted by the layer.
We recommend that descendants of `Layer` implement the following methods:
* `__init__()`: Defines custom layer attributes, and creates layer weights
that do not depend on input shapes, using `add_weight()`,
or other state.
* `build(self, input_shape)`: This method can be used to create weights that
depend on the shape(s) of the input(s), using `add_weight()`, or other
state. `__call__()` will automatically build the layer
(if it has not been built yet) by calling `build()`.
* `call(self, *args, **kwargs)`: Called in `__call__` after making
sure `build()` has been called. `call()` performs the logic of applying
the layer to the input arguments.
Two reserved keyword arguments you can optionally use in `call()` are:
1. `training` (boolean, whether the call is in inference mode or
training mode).
2. `mask` (boolean tensor encoding masked timesteps in the input,
used e.g. in RNN layers).
A typical signature for this method is `call(self, inputs)`, and user
could optionally add `training` and `mask` if the layer need them.
* `get_config(self)`: Returns a dictionary containing the configuration
used to initialize this layer. If the keys differ from the arguments
in `__init__()`, then override `from_config(self)` as well.
This method is used when saving
the layer or a model that contains this layer.
Examples:
Here's a basic example: a layer with two variables, `w` and `b`,
that returns `y = w . x + b`.
It shows how to implement `build()` and `call()`.
Variables set as attributes of a layer are tracked as weights
of the layers (in `layer.weights`).
```python
class SimpleDense(Layer):
def __init__(self, units=32):
super().__init__()
self.units = units
# Create the state of the layer (weights)
def build(self, input_shape):
self.kernel = self.add_weight(
shape=(input_shape[-1], self.units),
initializer="glorot_uniform",
trainable=True,
name="kernel",
)
self.bias = self.add_weight(
shape=(self.units,),
initializer="zeros",
trainable=True,
name="bias",
)
# Defines the computation
def call(self, inputs):
return ops.matmul(inputs, self.kernel) + self.bias
# Instantiates the layer.
linear_layer = SimpleDense(4)
# This will also call `build(input_shape)` and create the weights.
y = linear_layer(ops.ones((2, 2)))
assert len(linear_layer.weights) == 2
# These weights are trainable, so they're listed in `trainable_weights`:
assert len(linear_layer.trainable_weights) == 2
```
Besides trainable weights, updated via backpropagation during training,
layers can also have non-trainable weights. These weights are meant to
be updated manually during `call()`. Here's a example layer that computes
the running sum of its inputs:
```python
class ComputeSum(Layer):
def __init__(self, input_dim):
super(ComputeSum, self).__init__()
# Create a non-trainable weight.
self.total = self.add_weight(
shape=(),
initializer="zeros",
trainable=False,
name="total",
)
def call(self, inputs):
self.total.assign(self.total + ops.sum(inputs))
return self.total
my_sum = ComputeSum(2)
x = ops.ones((2, 2))
y = my_sum(x)
assert my_sum.weights == [my_sum.total]
assert my_sum.non_trainable_weights == [my_sum.total]
assert my_sum.trainable_weights == []
```
"""
def __new__(cls, *args, **kwargs):
obj = super().__new__(cls, *args, **kwargs)
# Wrap the user-provided `build` method in the `build_wrapper`
# to add name scope support and serialization support.
original_build_method = obj.build
@wraps(original_build_method)
def build_wrapper(*args, **kwargs):
with obj._open_name_scope():
obj._path = current_path()
original_build_method(*args, **kwargs)
# Record build config.
signature = inspect.signature(original_build_method)
obj._build_shapes_dict = signature.bind(*args, **kwargs).arguments
# Set built, post build actions, and lock state.
obj.built = True
obj._post_build()
obj._lock_state()
obj.build = build_wrapper
# Wrap the user-provided `quantize` method in the `quantize_wrapper`
# to add tracker support.
original_quantize_method = obj.quantize
@wraps(original_quantize_method)
def quantize_wrapper(mode, **kwargs):
obj._check_quantize_args(mode, obj.compute_dtype)
obj._tracker.unlock()
try:
original_quantize_method(mode, **kwargs)
except Exception:
raise
finally:
obj._tracker.lock()
obj.quantize = quantize_wrapper
return obj
def __init__(
self,
*,
activity_regularizer=None,
trainable=True,
dtype=None,
autocast=True,
name=None,
**kwargs,
):
BackendLayer.__init__(self)
self._lock = False
Operation.__init__(self, name=name)
self._dtype_policy = dtype_policies.get(dtype)
self.activity_regularizer = regularizers.get(activity_regularizer)
input_dim_arg = kwargs.pop("input_dim", None)
if input_dim_arg is not None:
input_shape_arg = (input_dim_arg,)
else:
input_shape_arg = kwargs.pop("input_shape", None)
if input_shape_arg is not None:
warnings.warn(
"Do not pass an `input_shape`/`input_dim` argument to "
"a layer. When using Sequential models, "
"prefer using an `Input(shape)` object as the "
"first layer in the model instead.",
stacklevel=2,
)
self._input_shape_arg = input_shape_arg
if kwargs:
raise ValueError(
"Unrecognized keyword arguments "
f"passed to {self.__class__.__name__}: {kwargs}"
)
self._path = None # Will be determined in `build_wrapper`
self.built = False
self.autocast = autocast
self._input_spec = None
self._called = False
self.supports_jit = True
self._trainable = trainable
self._losses = []
self._loss_ids = set()
self._losses_override = []
self._call_signature = inspect.signature(self.call)
self.call_signature_parameters = [
p.name for p in self._call_signature.parameters.values()
]
self._call_has_training_arg = (
"training" in self.call_signature_parameters
)
self._call_has_mask_arg = "mask" in self.call_signature_parameters
# 1. collect names that should be auto‑propagated
self._call_context_args = {"training"}
# 2. remember which of them exist in *this* call signature
self._call_has_context_arg = {
arg: (arg in self.call_signature_parameters)
for arg in self._call_context_args
}
self._supports_masking = not utils.is_default(self.compute_mask)
# Whether to automatically convert (+ auto-cast) inputs to `call()`.
self._convert_input_args = True
# Whether to allow non-tensors as positional arguments in `call()`.
self._allow_non_tensor_positional_args = False
# Dict of shapes that were used to call `build()`.
self._build_shapes_dict = None
# Parent path
self._parent_path = None
self._remat_mode = get_current_remat_mode()
self._initialize_tracker()
@tracking.no_automatic_dependency_tracking
def _initialize_tracker(self):
if hasattr(self, "_tracker"):
return
trainable_variables = []
non_trainable_variables = []
layers = []
metrics = []
seed_generators = []
self._tracker = tracking.Tracker(
{
"trainable_variables": (
lambda x: isinstance(x, backend.Variable) and x.trainable,
trainable_variables,
),
"non_trainable_variables": (
lambda x: isinstance(x, backend.Variable)
and not x.trainable,
non_trainable_variables,
),
"metrics": (lambda x: isinstance(x, Metric), metrics),
"layers": (
lambda x: isinstance(x, Layer)
and not isinstance(x, Metric),
layers,
),
"seed_generators": (
lambda x: isinstance(x, backend.random.SeedGenerator),
seed_generators,
),
},
exclusions={"non_trainable_variables": ["trainable_variables"]},
)
if backend.backend() == "tensorflow":
# Remove attribute tracking for lists (TF-specific attribute)
_self_setattr_tracking = getattr(
self, "_self_setattr_tracking", True
)
self._self_setattr_tracking = False
self._trainable_variables = trainable_variables
self._non_trainable_variables = non_trainable_variables
self._layers = layers
self._metrics = metrics
self._seed_generators = seed_generators
if backend.backend() == "tensorflow":
# Reset attribute tracking (TF-specific)
self._self_setattr_tracking = _self_setattr_tracking
def _build_at_init(self):
"""Build the layer at `Layer.__init__`.
We can only safely mark the layer as `built=True` in `Layer.__init__` if
`build` is not overridden. Otherwise, it might cause the subclasses to
ignore the user's `build`.
"""
if utils.is_default(self.build):
self.built = True
self._post_build()
self._lock_state()
@property
def path(self):
"""The path of the layer.
If the layer has not been built yet, it will be `None`.
"""
return self._path
@property
def input_spec(self):
return self._input_spec
@input_spec.setter
def input_spec(self, value):
self._input_spec = value
@utils.default
def build(self, input_shape):
self._check_super_called()
if utils.is_default(self.build) and might_have_unbuilt_state(self):
warnings.warn(
f"`build()` was called on layer '{self.name}', however "
"the layer does not have a `build()` method implemented "
"and it looks like it has unbuilt state. This will cause "
"the layer to be marked as built, despite not being "
"actually built, which may cause failures down the line. "
"Make sure to implement a proper `build()` method."
)
self.built = True
def _lock_state(self):
"""Prevent further state updates, called automatically in `build()`."""
if not self._tracker.locked:
self._tracker.lock(
msg=(
"You cannot add new elements of state "
"(variables or sub-layers) "
"to a layer that is already built. All state "
"must be created in the `__init__()` method or "
"in the `build()` method."
)
)
def get_build_config(self):
"""Returns a dictionary with the layer's input shape.
This method returns a config dict that can be used by
`build_from_config(config)` to create all states (e.g. Variables and
Lookup tables) needed by the layer.
By default, the config only contains the input shape that the layer
was built with. If you're writing a custom layer that creates state in
an unusual way, you should override this method to make sure this state
is already created when Keras attempts to load its value upon model
loading.
Returns:
A dict containing the input shape associated with the layer.
"""
if self._build_shapes_dict is not None:
if len(self._build_shapes_dict) == 1:
return {
"input_shape": tuple(self._build_shapes_dict.values())[0],
}
else:
return {"shapes_dict": self._build_shapes_dict}
def build_from_config(self, config):
"""Builds the layer's states with the supplied config dict.
By default, this method calls the `build(config["input_shape"])` method,
which creates weights based on the layer's input shape in the supplied
config. If your config contains other information needed to load the
layer's state, you should override this method.
Args:
config: Dict containing the input shape associated with this layer.
"""
if config:
if "input_shape" in config:
self.build(config["input_shape"])
elif "shapes_dict" in config:
self.build(**config["shapes_dict"])
def _obj_type(self):
return "Layer"
def add_variable(
self,
shape,
initializer,
dtype=None,
trainable=True,
autocast=True,
regularizer=None,
constraint=None,
name=None,
):
"""Add a weight variable to the layer.
Alias of `add_weight()`.
"""
return self.add_weight(
shape=shape,
initializer=initializer,
dtype=dtype,
trainable=trainable,
autocast=autocast,
regularizer=regularizer,
constraint=constraint,
name=name,
)
def add_weight(
self,
shape=None,
initializer=None,
dtype=None,
trainable=True,
autocast=True,
regularizer=None,
constraint=None,
aggregation="none",
overwrite_with_gradient=False,
name=None,
):
"""Add a weight variable to the layer.
Args:
shape: Shape tuple for the variable. Must be fully-defined
(no `None` entries). Defaults to `()` (scalar) if unspecified.
initializer: Initializer object to use to populate the initial
variable value, or string name of a built-in initializer
(e.g. `"random_normal"`). If unspecified, defaults to
`"glorot_uniform"` for floating-point variables and to `"zeros"`
for all other types (e.g. int, bool).
dtype: Dtype of the variable to create, e.g. `"float32"`. If
unspecified, defaults to the layer's variable dtype
(which itself defaults to `"float32"` if unspecified).
trainable: Boolean, whether the variable should be trainable via
backprop or whether its updates are managed manually. Defaults
to `True`.
autocast: Boolean, whether to autocast layers variables when
accessing them. Defaults to `True`.
regularizer: Regularizer object to call to apply penalty on the
weight. These penalties are summed into the loss function
during optimization. Defaults to `None`.
constraint: Contrainst object to call on the variable after any
optimizer update, or string name of a built-in constraint.
Defaults to `None`.
aggregation: Optional string, one of `None`, `"none"`, `"mean"`,
`"sum"` or `"only_first_replica"`. Annotates the variable with
the type of multi-replica aggregation to be used for this
variable when writing custom data parallel training loops.
Defaults to `"none"`.
overwrite_with_gradient: Boolean, whether to overwrite the variable
with the computed gradient. This is useful for float8 training.
Defaults to `False`.
name: String name of the variable. Useful for debugging purposes.
"""
self._check_super_called()
if shape is None:
shape = ()
if dtype is not None:
dtype = backend.standardize_dtype(dtype)
else:
dtype = self.variable_dtype
if initializer is None:
if "float" in dtype:
initializer = "glorot_uniform"
else:
initializer = "zeros"
initializer = initializers.get(initializer)
with backend.name_scope(self.name, caller=self):
variable = backend.Variable(
initializer=initializer,
shape=shape,
dtype=dtype,
trainable=trainable,
autocast=autocast,
aggregation=aggregation,
name=name,
)
# Will be added to layer.losses
variable.regularizer = regularizers.get(regularizer)
variable.constraint = constraints.get(constraint)
variable.overwrite_with_gradient = overwrite_with_gradient
self._track_variable(variable)
return variable
@property
def trainable(self):
"""Settable boolean, whether this layer should be trainable or not."""
return self._trainable
@trainable.setter
def trainable(self, value):
"""Sets trainable attribute for the layer and its sublayers.
When this value is changed during training (e.g. with a
`Callback`) you need to call the parent
`Model.make_train_function` with `force=True` in order to
recompile the training graph.
Args:
value: Boolean with the desired state for the layer's trainable
attribute.
"""
value = bool(value)
self._trainable = value
for v in self._trainable_variables:
v.trainable = value
for layer in self._layers:
layer.trainable = value
@property
def variables(self):
"""List of all layer state, including random seeds.
This extends `layer.weights` to include all state used by the layer
including `SeedGenerator`s.
Note that metrics variables are not included here, use
`metrics_variables` to visit all the metric variables.
"""
# Return all `Variables` associate with the layer including metrics
# and random seeds. Also deduplicate them.
variables = []
seen_ids = set()
for v in self._trainable_variables + self._non_trainable_variables:
if id(v) not in seen_ids:
variables.append(v)
seen_ids.add(id(v))
for sg in self._seed_generators:
variables.append(sg.state)
for layer in self._layers:
for v in layer.variables:
if id(v) not in seen_ids:
variables.append(v)
seen_ids.add(id(v))
return variables
@property
def trainable_variables(self):
"""List of all trainable layer state.
This is equivalent to `layer.trainable_weights`.
"""
if not self.trainable:
return []
return [v for v in self.variables if v.trainable]
@property
def non_trainable_variables(self):
"""List of all non-trainable layer state.
This extends `layer.non_trainable_weights` to include all state used by
the layer including state for metrics and `SeedGenerator`s.
"""
if not self.trainable:
return self.variables
return [v for v in self.variables if not v.trainable]
@property
def weights(self):
"""List of all weight variables of the layer.
Unlike, `layer.variables` this excludes metric state and random seeds.
"""
# Return only `Variables` directly owned by layers and sub-layers.
# Also deduplicate them.
weights = []
seen_ids = set()
for w in self._trainable_variables + self._non_trainable_variables:
if id(w) not in seen_ids:
weights.append(w)
seen_ids.add(id(w))
for layer in self._layers:
for w in layer.weights:
if id(w) not in seen_ids:
weights.append(w)
seen_ids.add(id(w))
return weights
@property
def trainable_weights(self):
"""List of all trainable weight variables of the layer.
These are the weights that get updated by the optimizer during training.
"""
if not self.trainable:
return []
return [v for v in self.weights if v.trainable]
@property
def non_trainable_weights(self):
"""List of all non-trainable weight variables of the layer.
These are the weights that should not be updated by the optimizer during
training. Unlike, `layer.non_trainable_variables` this excludes metric
state and random seeds.
"""
if not self.trainable:
return self.weights
return [v for v in self.weights if not v.trainable]
@property
def metrics(self):
"""List of all metrics."""
metrics = list(self._metrics)
for layer in self._layers:
metrics.extend(layer.metrics)
return metrics
@property
def metrics_variables(self):
"""List of all metric variables."""
vars = []
for metric in self.metrics:
vars.extend(metric.variables)
return vars
def get_weights(self):
"""Return the values of `layer.weights` as a list of NumPy arrays."""
return [v.numpy() for v in self.weights]
def set_weights(self, weights):
"""Sets the values of `layer.weights` from a list of NumPy arrays."""
layer_weights = self.weights
if len(layer_weights) != len(weights):
raise ValueError(
f"You called `set_weights(weights)` on layer '{self.name}' "
f"with a weight list of length {len(weights)}, but the layer "
f"was expecting {len(layer_weights)} weights."
)
for variable, value in zip(layer_weights, weights):
if variable.shape != value.shape:
raise ValueError(
f"Layer {self.name} weight shape {variable.shape} "
"is not compatible with provided weight "
f"shape {value.shape}."
)
variable.assign(value)
@property
def dtype_policy(self):
return self._dtype_policy
@dtype_policy.setter
def dtype_policy(self, value):
policy = dtype_policies.get(value)
if isinstance(self._dtype_policy, DTypePolicyMap) and self.path:
if self.path in self._dtype_policy:
del self._dtype_policy[self.path]
self._dtype_policy[self.path] = policy
else:
self._dtype_policy = policy
if policy.quantization_mode is not None:
if self.built and not getattr(self, "_is_quantized", False):
self.quantize(policy.quantization_mode)
@property
def dtype(self):
"""Alias of `layer.variable_dtype`."""
return self.variable_dtype
@property
def compute_dtype(self):
"""The dtype of the computations performed by the layer."""
if isinstance(self._dtype_policy, DTypePolicyMap) and self.path:
policy = self._dtype_policy[self.path]
else:
policy = self._dtype_policy
return policy.compute_dtype
@property
def variable_dtype(self):
"""The dtype of the state (weights) of the layer."""
if isinstance(self._dtype_policy, DTypePolicyMap) and self.path:
policy = self._dtype_policy[self.path]
else:
policy = self._dtype_policy
return policy.variable_dtype
@property
def quantization_mode(self):
"""The quantization mode of this layer, `None` if not quantized."""
if isinstance(self._dtype_policy, DTypePolicyMap) and self.path:
policy = self._dtype_policy[self.path]
else:
policy = self._dtype_policy
return policy.quantization_mode
@property
def input_dtype(self):
"""The dtype layer inputs should be converted to."""
return self.compute_dtype
@property
def supports_masking(self):
"""Whether this layer supports computing a mask using `compute_mask`."""
return self._supports_masking
@supports_masking.setter
def supports_masking(self, value):
self._supports_masking = value
@utils.default
def compute_mask(self, inputs, previous_mask):
return previous_mask
def symbolic_call(self, *args, **kwargs):
# Node is created at the end of `__call__` instead of `symbolic_call`.
return self.compute_output_spec(*args, **kwargs)
@traceback_utils.filter_traceback
def __call__(self, *args, **kwargs):
self._check_super_called()
self._called = True
original_args = args
original_kwargs = kwargs
#############################################################
# 1. Convert any array arguments to tensors of correct dtype.
def maybe_convert(x):
return self.dtype_policy.convert_input(
x, self.autocast, self.input_dtype
)
# Used to avoid expensive `tree` operations in the most common case.
if (
kwargs
or len(args) != 1
or not is_backend_tensor_or_symbolic(args[0], allow_none=False)
or backend.standardize_dtype(args[0].dtype) != self.input_dtype
) and self._convert_input_args:
args = tree.map_structure(maybe_convert, args)
kwargs = tree.map_structure(maybe_convert, kwargs)
##########################################################
# 2. Enforce that only tensors can be passed positionally.
if not self._allow_non_tensor_positional_args:
for arg in tree.flatten(args):
if not is_backend_tensor_or_symbolic(arg, allow_none=True):
raise ValueError(
"Only input tensors may be passed as "
"positional arguments. The following argument value "
f"should be passed as a keyword argument: {arg} "
f"(of type {type(arg)})"
)
# Caches info about `call()` signature, args, kwargs.
call_spec = CallSpec(
self._call_signature, self._call_context_args, args, kwargs
)
############################################
# 3. Check input spec for 1st positional arg.
# TODO: consider extending this to all args and kwargs.
self._assert_input_compatibility(call_spec.first_arg)
################
# 4. Call build
with self._open_name_scope():
self._maybe_build(call_spec)
##########################
# 5. Infer training value
# Training phase for `Layer.call` is set via (in order of priority):
# (1) The `training` argument passed to this `Layer.call`, if not None
# (2) The training argument of an outer `Layer.call`.
# (4) Any non-None default value for `training` in the call signature
# (5) False (treating the layer as if it's in inference)
# Maintains info about the `Layer.call` stack
# across nested calls.
call_context = self._get_call_context()
for context_arg in self._call_context_args:
self._resolve_and_populate_arg(
context_arg, call_spec, call_context, kwargs
)
##############################
# 6. Populate mask argument(s)
if len(call_spec.tensor_arguments_dict) == 1:
if (
"mask" in call_spec.argument_names
and call_spec.arguments_dict["mask"] is None
):
arg_name = list(call_spec.tensor_arguments_dict.keys())[0]
only_tensor_arg = call_spec.tensor_arguments_dict[arg_name]
mask = tree.map_structure(
backend.get_keras_mask,
only_tensor_arg,
)
kwargs["mask"] = mask
elif len(call_spec.tensor_arguments_dict) > 1:
for k, v in call_spec.tensor_arguments_dict.items():
expected_mask_arg_name = f"{k}_mask"
if expected_mask_arg_name in call_spec.argument_names:
if call_spec.arguments_dict[expected_mask_arg_name] is None:
mask = tree.map_structure(backend.get_keras_mask, v)
kwargs[expected_mask_arg_name] = mask
# We need to cache the `previous_mask` before `__call__` because the
# mask might be removed during the call, such as `MultiHeadAttention`.
if "mask" in kwargs and kwargs["mask"] is not None:
# Case 1: Mask was explicitly passed or auto-populated in step 6.
previous_mask = kwargs["mask"]
else:
# Case 2: Fallback to the mask attached to the first input tensor.
previous_mask = tree.map_structure(
backend.get_keras_mask, call_spec.first_arg
)
####################
# 7. Call the layer.
try:
with self._open_name_scope():
current_scope = backend.get_autocast_scope()
new_scope = None
if current_scope is not None:
# Clear or update the current scope if necessary.
if not self.autocast:
new_scope = backend.AutocastScope(None)
elif not backend.is_float_dtype(self.compute_dtype):
# Some preprocessing layers might have a non-float
# dtype, we should not autocast in this case.
new_scope = backend.AutocastScope(None)
elif current_scope.dtype != self.compute_dtype:
new_scope = backend.AutocastScope(self.compute_dtype)
elif self.compute_dtype != self.variable_dtype:
# Enter a new scope if our dtypes are "mixed".
new_scope = backend.AutocastScope(self.compute_dtype)
if new_scope is not None:
with new_scope:
outputs = super().__call__(*args, **kwargs)
else:
outputs = super().__call__(*args, **kwargs)
# Change the layout for the layer output if needed.
# This is useful for relayout intermediate tensor in the model
# to achieve the optimal performance.
distribution = distribution_lib.distribution()
if distribution is not None:
current_layer_path = current_path()
current_layer_path += "/output"
layout = distribution.get_tensor_layout(current_layer_path)
if layout:
outputs = distribution_lib.distribute_tensor(
outputs, layout
)
self.built = True
# Record activity regularizer loss.
if self.activity_regularizer is not None:
for output in tree.flatten(outputs):
if backend.is_tensor(output):
self.add_loss(self.activity_regularizer(output))
# Set `previous_mask` on outputs if available. It is provided only
# for the first positional input arg and its mask.
# TODO: consider extending this to all args and kwargs.
if self.supports_masking:
self._set_mask_metadata(
call_spec.first_arg, outputs, previous_mask
)
elif any(m is not None for m in tree.flatten(previous_mask)):
warnings.warn(
f"Layer '{self.name}' (of type {self.__class__.__name__}) "
"was passed an input with a mask attached to it. "
"However, this layer does not support masking and will "
"therefore destroy the mask information. Downstream "
"layers will not see the mask."
)
finally:
# Destroy call context if we created it
self._maybe_reset_call_context()
################################################
# 8. Add a node in the graph for symbolic calls.
if any_symbolic_tensors(original_args, original_kwargs):
Node(
operation=self,
call_args=original_args,
call_kwargs=original_kwargs,
outputs=outputs,
)
return outputs
def call(self, *args, **kwargs):
raise self._not_implemented_error(self.call)
def _resolve_and_populate_arg(
self, arg_name, call_spec, call_context, kwargs
):
# 1) user explicitly passed it?
if arg_name in call_spec.user_arguments_dict:
value = call_spec.user_arguments_dict[arg_name]
# 2) else: inherited from outer layer call?
elif call_context.get_value(arg_name) is not None:
value = call_context.get_value(arg_name)
# 3) else: default from the call() signature
else:
value = call_spec.arguments_dict.get(arg_name, None)
# stash it for downstream layers
call_context.set_value(arg_name, value)
# only inject it if this layer actually accepts it and it's not None
if (
self._call_has_context_arg.get(arg_name, False)
and value is not None
):
kwargs[arg_name] = value
@traceback_utils.filter_traceback
def stateless_call(
self,
trainable_variables,
non_trainable_variables,
*args,
return_losses=False,
**kwargs,
):
"""Call the layer without any side effects.
Args:
trainable_variables: List of trainable variables of the model.
non_trainable_variables: List of non-trainable variables of the
model.
*args: Positional arguments to be passed to `call()`.
return_losses: If `True`, `stateless_call()` will return the list of
losses created during `call()` as part of its return values.
**kwargs: Keyword arguments to be passed to `call()`.
Returns:
A tuple. By default, returns `(outputs, non_trainable_variables)`.
If `return_losses = True`, then returns
`(outputs, non_trainable_variables, losses)`.
Note: `non_trainable_variables` include not only non-trainable weights
such as `BatchNormalization` statistics, but also RNG seed state
(if there are any random operations part of the layer, such as dropout),
and `Metric` state (if there are any metrics attached to the layer).
These are all elements of state of the layer.
Example:
```python
model = ...
data = ...
trainable_variables = model.trainable_variables
non_trainable_variables = model.non_trainable_variables
# Call the model with zero side effects
outputs, non_trainable_variables = model.stateless_call(
trainable_variables,
non_trainable_variables,
data,
)
# Attach the updated state to the model
# (until you do this, the model is still in its pre-call state).
for ref_var, value in zip(
model.non_trainable_variables, non_trainable_variables
):
ref_var.assign(value)
```
"""
self._check_super_called()
if not self.built:
raise ValueError(
f"To call stateless_call, {self.__class__.__name__} must be "
"built (i.e. its variables must have been already created). "
"You can build it by calling it on some data."
)
if len(trainable_variables) != len(self.trainable_variables):
raise ValueError(
"Argument `trainable_variables` must be a list of tensors "
"corresponding 1:1 to "
f"{self.__class__.__name__}().trainable_variables. "
f"Received list with length {len(trainable_variables)}, "
f"but expected {len(self.trainable_variables)} variables."
)
if len(non_trainable_variables) != len(self.non_trainable_variables):
raise ValueError(
"Argument `non_trainable_variables` must be a list of tensors "
"corresponding 1:1 to "
f"{self.__class__.__name__}().non_trainable_variables. "
f"Received list with length {len(non_trainable_variables)}, "
f"but expected {len(self.non_trainable_variables)} variables."
)
# Gather variable mapping
trainable_mapping = zip(self.trainable_variables, trainable_variables)
non_trainable_mapping = zip(
self.non_trainable_variables, non_trainable_variables
)
mapping = list(trainable_mapping) + list(non_trainable_mapping)
# Call in stateless scope
losses = None
with backend.StatelessScope(
state_mapping=mapping, collect_losses=return_losses
) as scope:
if self.dtype_policy.quantization_mode is not None:
if self._remat_mode is not None:
outputs = self.rematerialized_call(
self.quantized_call, *args, **kwargs
)(*args, **kwargs)
else:
outputs = self.quantized_call(*args, **kwargs)
elif self._remat_mode is not None:
outputs = self.rematerialized_call(self.call, *args, **kwargs)(
*args, **kwargs
)
else:
outputs = self.call(*args, **kwargs)
if return_losses:
losses = self.losses
# Gather updated non-trainable variables
non_trainable_variables = []
for v in self.non_trainable_variables:
new_v = scope.get_current_value(v)
non_trainable_variables.append(new_v)
if return_losses:
return outputs, non_trainable_variables, losses
return outputs, non_trainable_variables
def compute_output_spec(self, *args, **kwargs):
if utils.is_default(self.compute_output_shape):
return super().compute_output_spec(*args, **kwargs)
else:
# Use compute_output_shape() to return the right output spec
call_spec = CallSpec(
self._call_signature, self._call_context_args, args, kwargs
)
shapes_dict = get_shapes_dict(call_spec)
shapes_dict = update_shapes_dict_for_target_fn(
self.compute_output_shape,
shapes_dict=shapes_dict,
call_spec=call_spec,
class_name=self.__class__.__name__,
)
output_shape = self.compute_output_shape(**shapes_dict)
if (
isinstance(output_shape, list)
and output_shape
and isinstance(output_shape[0], (int, type(None)))
):
output_shape = tuple(output_shape)
if not isinstance(output_shape, (list, tuple, dict)):
try:
output_shape = tuple(output_shape)
except:
raise ValueError(
"Method `compute_output_shape()` of layer "
f"{self.__class__.__name__} is returning "
"a type that cannot be interpreted as a shape. "
"It should return a shape tuple. "
f"Received: {output_shape}"
)
if (
isinstance(output_shape, tuple)
and output_shape
and isinstance(output_shape[0], (int, type(None)))
):
return KerasTensor(output_shape, dtype=self.compute_dtype)
# Case: nested. Could be a tuple/list of shapes, or a dict of
# shapes. Could be deeply nested.
return tree.map_shape_structure(
lambda s: KerasTensor(s, dtype=self.compute_dtype), output_shape
)
@utils.default
def compute_output_shape(self, *args, **kwargs):
raise self._not_implemented_error(
self.compute_output_shape,
"Should implement `def compute_output_shape(self, input_shape)`.",
)
def add_loss(self, loss):
"""Can be called inside of the `call()` method to add a scalar loss.
Example:
```python
class MyLayer(Layer):
...
def call(self, x):
self.add_loss(ops.sum(x))
return x
```
"""
# Eager only.
losses = tree.flatten(loss)
for x in losses:
if not backend.is_tensor(x):
raise ValueError(
"`add_loss()` can only be called from inside `build()` or "
f"`call()`, on a tensor input. Received invalid value: {x}"
)
if backend.in_stateless_scope():
scope = backend.get_stateless_scope()
if scope.collect_losses:
for x in losses:
scope.add_loss(x)
self._loss_ids.add(id(x))
else:
self._losses.extend(losses)
def _get_own_losses(self):
if backend.in_stateless_scope():
losses = []
scope = backend.get_stateless_scope()
for loss in scope.losses:
if id(loss) in self._loss_ids:
losses.append(loss)
return losses
else:
return self._losses[:]
def _get_regularization_losses(self):
weight_regularization_losses = []
for variable in self.trainable_weights:
if variable.regularizer is None:
continue
if backend.in_stateless_scope() and not in_symbolic_scope():
# If in symbolic scope, we might get `None` from
# `get_current_value` in `backend.compute_output_spec`. So we
# assign `variable` instead.
v = backend.get_stateless_scope().get_current_value(variable)
else:
v = variable
weight_regularization_losses.append(variable.regularizer(v))
return weight_regularization_losses
@property
def losses(self):
"""List of scalar losses from `add_loss`, regularizers and sublayers."""
if self._losses_override:
return self._losses_override
losses = self._get_own_losses()
for layer in self._flatten_layers(include_self=False):
losses.extend(layer._get_own_losses())
weight_regularization_losses = self._get_regularization_losses()
losses.extend(weight_regularization_losses)
return losses
def _clear_losses(self):
if backend.in_stateless_scope():
scope = backend.get_stateless_scope()
if scope.collect_losses:
for x in scope.losses:
if id(x) in self._loss_ids:
scope.losses.remove(x)
self._losses.clear()
self._loss_ids.clear()
for layer in self._layers:
layer._clear_losses()
# Quantization-related (int8 and float8) methods
def quantized_build(self, input_shape, mode):
raise self._not_implemented_error(self.quantized_build)
def quantize(self, mode, type_check=True, config=None):
raise self._not_implemented_error(self.quantize)
def _check_quantize_args(self, mode, compute_dtype):
if not self.built:
raise ValueError(
"Cannot quantize a layer that isn't yet built. "
f"Layer '{self.name}' (of type '{self.__class__.__name__}') "
"is not built yet."
)
if getattr(self, "_is_quantized", False):
raise ValueError(
f"Layer '{self.name}' is already quantized with "
f"dtype_policy='{self.dtype_policy.name}'. "
f"Received: mode={mode}"
)
if mode not in dtype_policies.QUANTIZATION_MODES:
raise ValueError(
"Invalid quantization mode. "
f"Expected one of {dtype_policies.QUANTIZATION_MODES}. "
f"Received: mode={mode}"
)
if mode == "int8" and compute_dtype == "float16":
raise ValueError(
f"Quantization mode='{mode}' doesn't work well with "
"compute_dtype='float16'. Consider loading model/layer with "
"another dtype policy such as 'mixed_bfloat16' or "
"'mixed_float16' before calling `quantize()`."
)
def quantized_call(self, *args, **kwargs):
current_remat_mode = get_current_remat_mode()
if (
current_remat_mode != self._remat_mode
and current_remat_mode is not None
):
warnings.warn(
f"The RematScope at call time ({current_remat_mode}) differs "
f"the one set during layer initialization "
f"({self._remat_mode}). "
f"Restoring the correct rematerialization mode "
f"{self._remat_mode} for this layer."
)
if self.quantization_mode == "int8":
return self._int8_call(*args, **kwargs)
elif self.quantization_mode == "float8":
return self._float8_call(*args, **kwargs)
elif self.quantization_mode == "int4":
return self._int4_call(*args, **kwargs)
elif self.quantization_mode == "gptq":
return self._gptq_call(*args, **kwargs)
else:
raise self._quantization_mode_error(self.quantization_mode)
def _int4_call(self, *args, **kwargs):
raise self._not_implemented_error(self._int4_call)
def _int8_call(self, *args, **kwargs):
raise self._not_implemented_error(self._int8_call)
def _float8_call(self, *args, **kwargs):
raise self._not_implemented_error(self._float8_call)
def _gptq_call(self, *args, **kwargs):
raise self._not_implemented_error(self._gptq_call)
def _not_implemented_error(self, attr, msg=None):
if callable(attr):
attr_name = attr.__name__
attr_type = "method"
else:
attr_name = str(attr)
attr_type = "attribute"
msg = f" {msg}" if msg is not None else ""
return NotImplementedError(
f"Layer {self.__class__.__name__} does not have a `{attr_name}` "
f"{attr_type} implemented.{msg}"
)
def _quantization_mode_error(self, mode):
return NotImplementedError(
"Invalid quantization mode. Expected one of "
f"{dtype_policies.QUANTIZATION_MODES}. "
f"Received: quantization_mode={mode}"
)
def save_own_variables(self, store):
"""Saves the state of the layer.
You can override this method to take full control of how the state of
the layer is saved upon calling `model.save()`.
Args:
store: Dict where the state of the model will be saved.
"""
all_vars = self._trainable_variables + self._non_trainable_variables
for i, v in enumerate(all_vars):
store[f"{i}"] = v
def _check_load_own_variables(self, store):
all_vars = self._trainable_variables + self._non_trainable_variables
if len(store.keys()) != len(all_vars):
if len(all_vars) == 0 and not self.built:
raise ValueError(
f"Layer '{self.name}' was never built "
"and thus it doesn't have any variables. "
f"However the weights file lists {len(store.keys())} "
"variables for this layer.\n"
"In most cases, this error indicates that either:\n\n"
"1. The layer is owned by a parent layer that "
"implements a `build()` method, but calling the "
"parent's `build()` method did NOT create the state of "
f"the child layer '{self.name}'. A `build()` method "
"must create ALL state for the layer, including "
"the state of any children layers.\n\n"
"2. You need to implement "
"the `def build_from_config(self, config)` method "
f"on layer '{self.name}', to specify how to rebuild "
"it during loading. "
"In this case, you might also want to implement the "
"method that generates the build config at saving time, "
"`def get_build_config(self)`. "
"The method `build_from_config()` is meant "
"to create the state "
"of the layer (i.e. its variables) upon deserialization.",
)
raise ValueError(
f"Layer '{self.name}' expected {len(all_vars)} variables, "
"but received "
f"{len(store.keys())} variables during loading. "
f"Expected: {[v.name for v in all_vars]}"
)
def load_own_variables(self, store):
"""Loads the state of the layer.
You can override this method to take full control of how the state of
the layer is loaded upon calling `keras.models.load_model()`.
Args:
store: Dict from which the state of the model will be loaded.
"""
self._check_load_own_variables(store)
all_vars = self._trainable_variables + self._non_trainable_variables
for i, v in enumerate(all_vars):
v.assign(store[f"{i}"])
def _track_variable(self, variable):
if variable.trainable:
self._tracker.add_to_store("trainable_variables", variable)
else:
self._tracker.add_to_store("non_trainable_variables", variable)
if not self.trainable:
variable.trainable = False
self._post_track_variable(variable)
def _untrack_variable(self, variable):
previous_lock_state = self._tracker.locked
self._tracker.unlock()
self._tracker.untrack(variable)
if previous_lock_state is True:
self._tracker.lock()
self._post_untrack_variable(variable)
def add_metric(self, *args, **kwargs):
# Permanently disabled
raise NotImplementedError(
"Layer `add_metric()` method is deprecated. "
"Add your metric in `Model.compile(metrics=[...])`, "
"or create metric trackers in init() or build() "
"when subclassing the layer or model, then call "
"`metric.update_state()` whenever necessary."
)
def count_params(self):
"""Count the total number of scalars composing the weights.
Returns:
An integer count.
"""
if not self.built:
raise ValueError(
"You tried to call `count_params` "
f"on layer '{self.name}', "
"but the layer isn't built. "
"You can build it manually via: "
f"`layer.build(input_shape)`."
)
return summary_utils.count_params(self.weights)
def _maybe_build(self, call_spec):
if self.built:
return
shapes_dict = get_shapes_dict(call_spec)
first_shape = next(iter(shapes_dict.values()), None)
# If the layer has a build method, call it with our input shapes.
if not utils.is_default(self.build):
shapes_dict = update_shapes_dict_for_target_fn(
self.build,
shapes_dict=shapes_dict,
call_spec=call_spec,
class_name=self.__class__.__name__,
)
self.build(**shapes_dict)
# Check input spec again (after build, since self.input_spec
# may have been updated
self._assert_input_compatibility(call_spec.first_arg)
return
# Otherwise, attempt to build the layer by calling it on symbolic input.
if might_have_unbuilt_state(self):
try:
backend.compute_output_spec(
self.call, **call_spec.arguments_dict
)
except Exception as e:
if call_spec.eager:
# Will let the actual eager call do state-building
return
warnings.warn(
f"Layer '{self.name}' looks like it has unbuilt state, but "
"Keras is not able to trace the layer `call()` in order to "
"build it automatically. Possible causes:\n"
"1. The `call()` method of your layer may be crashing. Try "
"to `__call__()` the layer eagerly on some test input "
"first to see if it works. "
"E.g. `x = np.random.random((3, 4)); y = layer(x)`\n"
"2. If the `call()` method is correct, then you may need "
"to implement the `def build(self, input_shape)` method on "
"your layer. It should create all variables used by the "
"layer (e.g. by calling `layer.build()` on all its "
"children layers).\n"
f"Exception encountered: ''{e}''"
)
self.build(first_shape)
def _build_by_run_for_single_pos_arg(self, input_shape):
# Case: all inputs are in the first arg (possibly nested).
input_tensors = tree.map_shape_structure(
lambda s: backend.KerasTensor(s), input_shape
)
try:
backend.compute_output_spec(self.call, input_tensors)
return True
except:
return False
def _build_by_run_for_kwargs(self, shapes_dict):
# Case: inputs were recorded as multiple keyword arguments.
if all(is_shape_tuple(s) for s in shapes_dict.values()):
# Case: all input keyword arguments were plain tensors.
input_tensors = {
# We strip the `_shape` suffix to recover kwarg names.
utils.removesuffix(k, "_shape"): backend.KerasTensor(shape)
for k, shape in shapes_dict.items()
}
try:
backend.compute_output_spec(self.call, **input_tensors)
return True
except:
return False
else:
# Not supported: nested input keyword arguments.
return False
def __repr__(self):
return (
f"<{self.__class__.__name__} name={self.name}, built={self.built}>"
)
def __str__(self):
return self.__repr__()
def __setattr__(self, name, value):
# Track Variables, Layers, Metrics, SeedGenerators.
name, value = self._setattr_hook(name, value)
if name != "_tracker":
if not hasattr(self, "_tracker"):
self._initialize_tracker()
value = self._tracker.track(value)
# NNX-specific bypass for `_called` and `built` attributes
# bypass nnx.Module.__setattr__ which cannot be called while tracing
if (
backend.backend() == "jax"
and is_nnx_enabled()
and (name == "_called" or name == "built")
):
object.__setattr__(self, name, value)
return
super().__setattr__(name, value)
def __delattr__(self, name):
obj = getattr(self, name)
if isinstance(obj, backend.Variable):
import gc
# It will take a short amount of time for the corresponding buffer
# to be actually removed from the device.
# https://stackoverflow.com/a/74631949
self._untrack_variable(obj)
super().__delattr__(name)
gc.collect()
else:
super().__delattr__(name)
def _check_super_called(self):
if getattr(self, "_lock", True):
raise RuntimeError(
f"In layer '{self.__class__.__name__}', you forgot to call "
"`super().__init__()` as the first statement "
"in the `__init__()` method. Go add it!"
)
def _assert_input_compatibility(self, arg_0):
if self.input_spec:
try:
input_spec.assert_input_compatibility(
self.input_spec, arg_0, layer_name=self.name
)
except SystemError:
if backend.backend() == "torch":
# TODO: The torch backend failed the ONNX CI with the error:
# SystemError: <method '__int__' of 'torch._C.TensorBase'
# objects> returned a result with an exception set
# As a workaround, we are skipping this for now.
pass
else:
raise
def _get_call_context(self):
"""Returns currently active `CallContext`."""
layer_call_ctx = global_state.get_global_attribute("current_call_ctx")
if layer_call_ctx is None:
# Enter new call context.
layer_call_ctx = CallContext(entry_layer=self)
global_state.set_global_attribute(
"current_call_ctx", layer_call_ctx
)
self._clear_losses()
return layer_call_ctx
def _maybe_reset_call_context(self):
layer_call_ctx = global_state.get_global_attribute("current_call_ctx")
if layer_call_ctx is None or layer_call_ctx.entry_layer == self:
global_state.set_global_attribute("current_call_ctx", None)
def _flatten_layers(self, include_self=True, recursive=True):
layers = []
if include_self:
layers.append(self)
seen_object_ids = set()
deque = collections.deque(self._layers)
while deque:
layer = deque.popleft()
if id(layer) in seen_object_ids:
continue
seen_object_ids.add(id(layer))
layers.append(layer)
# Introspect recursively through sublayers.
if recursive:
deque.extendleft(layer._layers)
return layers
def _set_mask_metadata(self, inputs, outputs, previous_mask):
flat_outputs = tree.flatten(outputs)
mask_already_computed = all(
backend.get_keras_mask(x) is not None for x in flat_outputs
)
if mask_already_computed:
return
output_masks = self.compute_mask(inputs, previous_mask)
if output_masks is None:
return
flat_masks = tree.flatten(output_masks)
for tensor, mask in zip(flat_outputs, flat_masks):
if backend.get_keras_mask(tensor) is None and mask is not None:
if backend.backend() == "numpy":
warnings.warn(
"The NumPy backend does not support masking at this"
"time. Masks will be ignored."
)
else:
backend.set_keras_mask(tensor, mask)
@python_utils.default
def get_config(self):
self._check_super_called()
base_config = super().get_config()
config = {
"trainable": self.trainable,
"dtype": dtype_policies.serialize(self.dtype_policy),
}
if self.activity_regularizer is not None:
config["activity_regularizer"] = regularizers.serialize(
self.activity_regularizer
)
return {**base_config, **config}
def _open_name_scope(self):
from keras.src.utils import jax_utils # avoid circular imports
if self._parent_path is None:
# Avoid mutating _parent_path during a JAX trace if it's part of
# nnx.Object state and the object was created at a different trace
# level. We check if we are in NNX mode and if we are in a JAX
# trace.
if not (is_nnx_enabled() and jax_utils.is_in_jax_tracing_scope()):
self._parent_path = current_path()
return backend.name_scope(self.name, caller=self)
def rematerialized_call(self, layer_call, *args, **kwargs):
"""Enable rematerialization dynamically for layer's call method.
Args:
layer_call: The original `call` method of a layer.
Returns:
Rematerialized layer's `call` method.
"""
def compute_size(x):
return (
math.prod([d or 1 for d in x.shape])
if isinstance(x, KerasTensor)
else 0
)
# Full rematerialization
if self._remat_mode.mode == "full":
return remat.remat(layer_call)
# Apply rematerialization to specific layers
elif self._remat_mode.mode == "list_of_layers" and (
self.name in self._remat_mode.layer_names
):
return remat.remat(layer_call)
# Apply rematerialization based on output size threshold
elif self._remat_mode.mode == "larger_than":
output_spec = self.compute_output_spec(*args, **kwargs)
output_size = sum(
tree.flatten(tree.map_structure(compute_size, output_spec))
)
if (
output_size
and output_size > self._remat_mode.output_size_threshold
):
return remat.remat(layer_call)
elif self._remat_mode.mode == "activations":
has_activation = (
hasattr(self, "activation") and self.activation is not None
)
if has_activation:
@functools.wraps(layer_call)
def rematerialized_activation_call_wrapper(*args, **kwargs):
original_activation = self.activation
self.activation = remat.remat(original_activation)
try:
return layer_call(*args, **kwargs)
finally:
self.activation = original_activation
return rematerialized_activation_call_wrapper
return layer_call
def _register_call_context_args(self, *names):
"""Registers call-context args for this layer.
If this layer declares a `call()` method that accepts
one or more of the given args, those args will be
automatically injected into the call signature of this
layer. This layer will also propagate the args to any
nested sublayers that are called from within this layer.
If this layer doesn't declare a `call()` method that
accepts one or more of the given args, these args will
simply be propagated to any nested sublayers without
being injected into the call signature of this layer.
This is useful for propagating custom arguments
from top-level layers/models to sublayers.
Example:
```
class Inner(layers.Layer):
def __init__(self):
super().__init__()
# Register `foo_mode` as a call-context arg
self._register_call_context_args("foo_mode")
def call(self, x, foo_mode=False):
# If foo_mode=True add 1, otherwise add 0
add_val = ops.where(foo_mode, 1.0, 0.0)
return x + add_val
class Outer(layers.Layer):
def __init__(self):
super().__init__()
self.inner = Inner()
def call(self, x):
# We don't explicitly pass foo_mode here—Base Layer.__call__
# should inject it into `self.inner`
return self.inner(x)
sample_input = np.array([[1.0], [2.0]])
# Sequential model
seq = models.Sequential([Outer()])
# Tell the Sequential model to propagate foo_mode down
# the call-stack
seq.register_call_context_args("foo_mode")
# foo_mode=True -> input + 1
out_true = seq(sample_input, foo_mode=True)
"""
if self._called:
raise RuntimeError(
"Cannot add call-context args after the layer has been called."
)
self._call_context_args = self._call_context_args | set(names)
self._call_has_context_arg.update(
{arg: (arg in self.call_signature_parameters) for arg in names}
)
def is_backend_tensor_or_symbolic(x, allow_none=False):
if allow_none and x is None:
return True
return backend.is_tensor(x) or isinstance(x, backend.KerasTensor)
| Layer |
python | getsentry__sentry | src/sentry/notifications/utils/__init__.py | {
"start": 21039,
"end": 22290
} | class ____(PerformanceProblemContext):
def to_dict(self) -> dict[str, str | float | list[str]]:
return {
"transaction_name": self.transaction,
"slow_span_description": self.slow_span_description,
"slow_span_duration": self.slow_span_duration,
"transaction_duration": self.transaction_duration,
"fcp": self.fcp,
}
@property
def slow_span(self) -> Span | None:
if not self.spans:
return None
offending_spans = [
span for span in self.spans if span.get("span_id") in self.problem.offender_span_ids
]
if len(offending_spans) == 0:
return None
return offending_spans[0]
@property
def slow_span_description(self) -> str:
slow_span = self.slow_span
if not slow_span:
return ""
return str(slow_span.get("description", ""))
@property
def slow_span_duration(self) -> float:
return self.duration(self.slow_span)
@property
def fcp(self) -> float:
if not self.event:
return 0
return float(self.event.data.get("measurements", {}).get("fcp", {}).get("value", 0) or 0)
| RenderBlockingAssetProblemContext |
python | numpy__numpy | numpy/_core/tests/test_defchararray.py | {
"start": 6632,
"end": 11918
} | class ____:
def A(self):
return np.array([[' abc ', ''],
['12345', 'MixedCase'],
['123 \t 345 \0 ', 'UPPER']]) \
.view(np.char.chararray)
def B(self):
return np.array([[' \u03a3 ', ''],
['12345', 'MixedCase'],
['123 \t 345 \0 ', 'UPPER']]) \
.view(np.char.chararray)
def test_len(self):
A, B = self.A(), self.B()
assert_(issubclass(np.char.str_len(A).dtype.type, np.integer))
assert_array_equal(np.char.str_len(A), [[5, 0], [5, 9], [12, 5]])
assert_array_equal(np.char.str_len(B), [[3, 0], [5, 9], [12, 5]])
def test_count(self):
A, B = self.A(), self.B()
assert_(issubclass(A.count('').dtype.type, np.integer))
assert_array_equal(A.count('a'), [[1, 0], [0, 1], [0, 0]])
assert_array_equal(A.count('123'), [[0, 0], [1, 0], [1, 0]])
# Python doesn't seem to like counting NULL characters
assert_array_equal(A.count('a', 0, 2), [[1, 0], [0, 0], [0, 0]])
assert_array_equal(B.count('a'), [[0, 0], [0, 1], [0, 0]])
assert_array_equal(B.count('123'), [[0, 0], [1, 0], [1, 0]])
def test_endswith(self):
A = self.A()
assert_(issubclass(A.endswith('').dtype.type, np.bool))
assert_array_equal(A.endswith(' '), [[1, 0], [0, 0], [1, 0]])
assert_array_equal(A.endswith('3', 0, 3), [[0, 0], [1, 0], [1, 0]])
def fail():
A.endswith('3', 'fdjk')
assert_raises(TypeError, fail)
@pytest.mark.parametrize(
"dtype, encode",
[("U", str),
("S", lambda x: x.encode('ascii')),
])
def test_find(self, dtype, encode):
A = self.A().astype(dtype)
assert_(issubclass(A.find(encode('a')).dtype.type, np.integer))
assert_array_equal(A.find(encode('a')),
[[1, -1], [-1, 6], [-1, -1]])
assert_array_equal(A.find(encode('3')),
[[-1, -1], [2, -1], [2, -1]])
assert_array_equal(A.find(encode('a'), 0, 2),
[[1, -1], [-1, -1], [-1, -1]])
assert_array_equal(A.find([encode('1'), encode('P')]),
[[-1, -1], [0, -1], [0, 1]])
C = (np.array(['ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'01234567890123456789012345'])
.view(np.char.chararray)).astype(dtype)
assert_array_equal(C.find(encode('M')), [12, -1])
def test_index(self):
A = self.A()
def fail():
A.index('a')
assert_raises(ValueError, fail)
assert_(np.char.index('abcba', 'b') == 1)
assert_(issubclass(np.char.index('abcba', 'b').dtype.type, np.integer))
def test_isalnum(self):
A = self.A()
assert_(issubclass(A.isalnum().dtype.type, np.bool))
assert_array_equal(A.isalnum(), [[False, False], [True, True], [False, True]])
def test_isalpha(self):
A = self.A()
assert_(issubclass(A.isalpha().dtype.type, np.bool))
assert_array_equal(A.isalpha(), [[False, False], [False, True], [False, True]])
def test_isdigit(self):
A = self.A()
assert_(issubclass(A.isdigit().dtype.type, np.bool))
assert_array_equal(A.isdigit(), [[False, False], [True, False], [False, False]])
def test_islower(self):
A = self.A()
assert_(issubclass(A.islower().dtype.type, np.bool))
assert_array_equal(A.islower(), [[True, False], [False, False], [False, False]])
def test_isspace(self):
A = self.A()
assert_(issubclass(A.isspace().dtype.type, np.bool))
assert_array_equal(A.isspace(), [[False, False], [False, False], [False, False]])
def test_istitle(self):
A = self.A()
assert_(issubclass(A.istitle().dtype.type, np.bool))
assert_array_equal(A.istitle(), [[False, False], [False, False], [False, False]])
def test_isupper(self):
A = self.A()
assert_(issubclass(A.isupper().dtype.type, np.bool))
assert_array_equal(A.isupper(), [[False, False], [False, False], [False, True]])
def test_rfind(self):
A = self.A()
assert_(issubclass(A.rfind('a').dtype.type, np.integer))
assert_array_equal(A.rfind('a'), [[1, -1], [-1, 6], [-1, -1]])
assert_array_equal(A.rfind('3'), [[-1, -1], [2, -1], [6, -1]])
assert_array_equal(A.rfind('a', 0, 2), [[1, -1], [-1, -1], [-1, -1]])
assert_array_equal(A.rfind(['1', 'P']), [[-1, -1], [0, -1], [0, 2]])
def test_rindex(self):
A = self.A()
def fail():
A.rindex('a')
assert_raises(ValueError, fail)
assert_(np.char.rindex('abcba', 'b') == 3)
assert_(issubclass(np.char.rindex('abcba', 'b').dtype.type, np.integer))
def test_startswith(self):
A = self.A()
assert_(issubclass(A.startswith('').dtype.type, np.bool))
assert_array_equal(A.startswith(' '), [[1, 0], [0, 0], [0, 0]])
assert_array_equal(A.startswith('1', 0, 3), [[0, 0], [1, 0], [1, 0]])
def fail():
A.startswith('3', 'fdjk')
assert_raises(TypeError, fail)
| TestInformation |
python | getsentry__sentry | src/sentry/integrations/messaging/metrics.py | {
"start": 3151,
"end": 3327
} | class ____(StrEnum):
"""Common reasons why a messaging command may fail."""
MISSING_DATA = "missing_data"
INVALID_STATE = "invalid_state"
| MessageCommandFailureReason |
python | numba__numba | numba/testing/main.py | {
"start": 24550,
"end": 27289
} | class ____(object):
"""
A minimal picklable object able to instantiate a runner in a
child process and run a test case with it.
"""
def __init__(self, runner_cls, runner_args):
self.runner_cls = runner_cls
self.runner_args = runner_args
# Python 2 doesn't know how to pickle instance methods, so we use __call__
# instead.
def __call__(self, test):
# Executed in child process
kwargs = self.runner_args
# Force recording of output in a buffer (it will be printed out
# by the parent).
kwargs['stream'] = StringIO()
runner = self.runner_cls(**kwargs)
result = runner._makeResult()
# Avoid child tracebacks when Ctrl-C is pressed.
signals.installHandler()
signals.registerResult(result)
result.failfast = runner.failfast
result.buffer = runner.buffer
# Create a per-process memory tracker to avoid global state issues
memtrack = memoryutils.MemoryTracker(test.id())
with memtrack.monitor():
with self.cleanup_object(test):
test(result)
# HACK as cStringIO.StringIO isn't picklable in 2.x
result.stream = _FakeStringIO(result.stream.getvalue())
return _MinimalResult(result, test.id(),
resource_info=memtrack.get_summary())
@contextlib.contextmanager
def cleanup_object(self, test):
"""
A context manager which cleans up unwanted attributes on a test case
(or any other object).
"""
vanilla_attrs = set(test.__dict__)
try:
yield test
finally:
spurious_attrs = set(test.__dict__) - vanilla_attrs
for name in spurious_attrs:
del test.__dict__[name]
def _split_nonparallel_tests(test, sliced):
"""
Split test suite into parallel and serial tests.
"""
ptests = []
stests = []
flat = [*filter(sliced, _flatten_suite(test))]
def is_parallelizable_test_case(test):
# Guard for the fake test case created by unittest when test
# discovery fails, as it isn't picklable (e.g. "LoadTestsFailure")
method_name = test._testMethodName
method = getattr(test, method_name)
if method.__name__ != method_name and method.__name__ == "testFailure":
return False
# Was parallel execution explicitly disabled?
return getattr(test, "_numba_parallel_test_", True)
for t in flat:
if is_parallelizable_test_case(t):
ptests.append(t)
else:
stests.append(t)
return ptests, stests
# A test can't run longer than 10 minutes
_TIMEOUT = 1200
| _MinimalRunner |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.