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 | tensorflow__tensorflow | tensorflow/python/kernel_tests/data_structures/padding_fifo_queue_test.py | {
"start": 1356,
"end": 60468
} | class ____(test.TestCase):
def testConstructor(self):
with ops.Graph().as_default():
q = data_flow_ops.PaddingFIFOQueue(
10, dtypes_lib.float32, ((None,),), name="Q")
self.assertTrue(isinstance(q.queue_ref, tensor.Tensor))
self.assertProtoEquals("""
name:'Q' op:'PaddingFIFOQueueV2'
attr { key: 'component_types' value { list { type: DT_FLOAT } } }
attr { key: 'shapes' value { list { shape { dim { size: -1 } } } } }
attr { key: 'capacity' value { i: 10 } }
attr { key: 'container' value { s: '' } }
attr { key: 'shared_name' value { s: '' } }
""", q.queue_ref.op.node_def)
def testMultiQueueConstructor(self):
with ops.Graph().as_default():
q = data_flow_ops.PaddingFIFOQueue(
5, (dtypes_lib.int32, dtypes_lib.float32), ((), ()),
shared_name="foo",
name="Q")
self.assertTrue(isinstance(q.queue_ref, tensor.Tensor))
self.assertProtoEquals("""
name:'Q' op:'PaddingFIFOQueueV2'
attr { key: 'component_types' value { list {
type: DT_INT32 type : DT_FLOAT
} } }
attr { key: 'shapes' value { list { shape { } shape { } } } }
attr { key: 'capacity' value { i: 5 } }
attr { key: 'container' value { s: '' } }
attr { key: 'shared_name' value { s: 'foo' } }
""", q.queue_ref.op.node_def)
def testConstructorWithShapes(self):
with ops.Graph().as_default():
q = data_flow_ops.PaddingFIFOQueue(
5, (dtypes_lib.int32, dtypes_lib.float32),
shapes=(tensor_shape.TensorShape([1, 1, 2, 3]),
tensor_shape.TensorShape([5, 8])),
name="Q")
self.assertTrue(isinstance(q.queue_ref, tensor.Tensor))
self.assertProtoEquals("""
name:'Q' op:'PaddingFIFOQueueV2'
attr { key: 'component_types' value { list {
type: DT_INT32 type : DT_FLOAT
} } }
attr { key: 'shapes' value { list {
shape { dim { size: 1 }
dim { size: 1 }
dim { size: 2 }
dim { size: 3 } }
shape { dim { size: 5 }
dim { size: 8 } }
} } }
attr { key: 'capacity' value { i: 5 } }
attr { key: 'container' value { s: '' } }
attr { key: 'shared_name' value { s: '' } }
""", q.queue_ref.op.node_def)
def testEnqueue(self):
with self.cached_session():
q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),))
enqueue_op = q.enqueue((10.0,))
enqueue_op.run()
def testEnqueueWithShape(self):
with self.cached_session():
q = data_flow_ops.PaddingFIFOQueue(
10, dtypes_lib.float32, shapes=((3, 2),))
enqueue_correct_op = q.enqueue(([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]],))
enqueue_correct_op.run()
with self.assertRaises(ValueError):
q.enqueue(([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]],))
self.assertEqual(1, q.size().eval())
def testEnqueueManyWithShape(self):
with self.cached_session():
q = data_flow_ops.PaddingFIFOQueue(
10, [dtypes_lib.int32, dtypes_lib.int32], shapes=[(), (2,)])
q.enqueue_many([[1, 2, 3, 4], [[1, 1], [2, 2], [3, 3], [4, 4]]]).run()
self.assertEqual(4, q.size().eval())
def testParallelEnqueue(self):
# We need each thread to keep its own device stack or the device scopes
# won't be properly nested.
ops.get_default_graph().switch_to_thread_local()
with self.cached_session() as sess:
q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),))
elems = [10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0]
enqueue_ops = [q.enqueue((x,)) for x in elems]
dequeued_t = q.dequeue()
# Run one producer thread for each element in elems.
def enqueue(enqueue_op):
self.evaluate(enqueue_op)
threads = [
self.checkedThread(
target=enqueue, args=(e,)) for e in enqueue_ops
]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
# Dequeue every element using a single thread.
results = []
for _ in range(len(elems)):
results.append(self.evaluate(dequeued_t))
self.assertItemsEqual(elems, results)
def testParallelDequeue(self):
# We need each thread to keep its own device stack or the device scopes
# won't be properly nested.
ops.get_default_graph().switch_to_thread_local()
with self.cached_session() as sess:
q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),))
elems = [10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0]
enqueue_ops = [q.enqueue((x,)) for x in elems]
dequeued_t = q.dequeue()
# Enqueue every element using a single thread.
for enqueue_op in enqueue_ops:
enqueue_op.run()
# Run one consumer thread for each element in elems.
results = []
def dequeue():
results.append(self.evaluate(dequeued_t))
threads = [self.checkedThread(target=dequeue) for _ in enqueue_ops]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
self.assertItemsEqual(elems, results)
def testDequeue(self):
with self.cached_session():
q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),))
elems = [10.0, 20.0, 30.0]
enqueue_ops = [q.enqueue((x,)) for x in elems]
dequeued_t = q.dequeue()
for enqueue_op in enqueue_ops:
enqueue_op.run()
for i in range(len(elems)):
vals = self.evaluate(dequeued_t)
self.assertEqual([elems[i]], vals)
def testEnqueueAndBlockingDequeue(self):
# We need each thread to keep its own device stack or the device scopes
# won't be properly nested.
ops.get_default_graph().switch_to_thread_local()
with self.cached_session() as sess:
q = data_flow_ops.PaddingFIFOQueue(3, dtypes_lib.float32, ((),))
elems = [10.0, 20.0, 30.0]
enqueue_ops = [q.enqueue((x,)) for x in elems]
dequeued_t = q.dequeue()
def enqueue():
# The enqueue_ops should run after the dequeue op has blocked.
# TODO(mrry): Figure out how to do this without sleeping.
time.sleep(0.1)
for enqueue_op in enqueue_ops:
self.evaluate(enqueue_op)
results = []
def dequeue():
for _ in range(len(elems)):
results.append(self.evaluate(dequeued_t))
enqueue_thread = self.checkedThread(target=enqueue)
dequeue_thread = self.checkedThread(target=dequeue)
enqueue_thread.start()
dequeue_thread.start()
enqueue_thread.join()
dequeue_thread.join()
for elem, result in zip(elems, results):
self.assertEqual([elem], result)
def testMultiEnqueueAndDequeue(self):
with self.cached_session() as sess:
q = data_flow_ops.PaddingFIFOQueue(10,
(dtypes_lib.int32, dtypes_lib.float32),
((), ()))
elems = [(5, 10.0), (10, 20.0), (15, 30.0)]
enqueue_ops = [q.enqueue((x, y)) for x, y in elems]
dequeued_t = q.dequeue()
for enqueue_op in enqueue_ops:
enqueue_op.run()
for i in range(len(elems)):
x_val, y_val = self.evaluate(dequeued_t)
x, y = elems[i]
self.assertEqual([x], x_val)
self.assertEqual([y], y_val)
def testQueueSizeEmpty(self):
with self.cached_session():
q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),))
self.assertEqual([0], q.size().eval())
def testQueueSizeAfterEnqueueAndDequeue(self):
with self.cached_session():
q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),))
enqueue_op = q.enqueue((10.0,))
dequeued_t = q.dequeue()
size = q.size()
self.assertEqual([], size.get_shape())
enqueue_op.run()
self.assertEqual(1, self.evaluate(size))
dequeued_t.op.run()
self.assertEqual(0, self.evaluate(size))
def testEnqueueMany(self):
with self.cached_session():
q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),))
elems = [10.0, 20.0, 30.0, 40.0]
enqueue_op = q.enqueue_many((elems,))
dequeued_t = q.dequeue()
enqueue_op.run()
enqueue_op.run()
for i in range(8):
vals = self.evaluate(dequeued_t)
self.assertEqual([elems[i % 4]], vals)
def testEmptyEnqueueMany(self):
with self.cached_session():
q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, (
(None, None),))
empty_t = constant_op.constant(
[], dtype=dtypes_lib.float32, shape=[0, 2, 3])
enqueue_op = q.enqueue_many((empty_t,))
size_t = q.size()
self.assertEqual([0], self.evaluate(size_t))
enqueue_op.run()
self.assertEqual([0], self.evaluate(size_t))
def testEmptyDequeueMany(self):
with self.cached_session():
q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, shapes=((),))
enqueue_op = q.enqueue((10.0,))
dequeued_t = q.dequeue_many(0)
self.assertEqual([], self.evaluate(dequeued_t).tolist())
enqueue_op.run()
self.assertEqual([], self.evaluate(dequeued_t).tolist())
def testEmptyDequeueManyWithDynamicShape(self):
with self.cached_session():
q = data_flow_ops.PaddingFIFOQueue(
10, dtypes_lib.float32, shapes=((None,),))
enqueue_op = q.enqueue(([10.0],))
dequeued_t = q.dequeue_many(0)
self.assertEqual([], self.evaluate(dequeued_t).tolist())
enqueue_op.run()
self.assertEqual([], self.evaluate(dequeued_t).tolist())
def testEmptyDequeueUpToWithDynamicShape(self):
with self.cached_session():
q = data_flow_ops.PaddingFIFOQueue(
10, dtypes_lib.float32, shapes=((None,),))
enqueue_op = q.enqueue(([10.0],))
dequeued_t = q.dequeue_up_to(0)
self.assertEqual([], self.evaluate(dequeued_t).tolist())
enqueue_op.run()
self.assertEqual([], self.evaluate(dequeued_t).tolist())
def testConstructPaddingFIFOQueueWithNoShape(self):
with self.cached_session():
with self.assertRaisesRegex(
ValueError,
r"When providing partial shapes, a list of shapes must be provided."):
self.evaluate(
data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32,
None).queue_ref)
def testMultiEnqueueMany(self):
with self.cached_session() as sess:
q = data_flow_ops.PaddingFIFOQueue(10,
(dtypes_lib.float32, dtypes_lib.int32),
((), (2,)))
float_elems = [10.0, 20.0, 30.0, 40.0]
int_elems = [[1, 2], [3, 4], [5, 6], [7, 8]]
enqueue_op = q.enqueue_many((float_elems, int_elems))
dequeued_t = q.dequeue()
enqueue_op.run()
enqueue_op.run()
for i in range(8):
float_val, int_val = self.evaluate(dequeued_t)
self.assertEqual(float_elems[i % 4], float_val)
self.assertAllEqual(int_elems[i % 4], int_val)
def testMultiEnqueueManyWithPartiallyKnownShapes(self):
with self.cached_session() as sess:
q = data_flow_ops.PaddingFIFOQueue(
10, (dtypes_lib.float32, dtypes_lib.int32), shapes=((), (None,)))
float_elems = [10.0, 20.0, 30.0, 40.0]
int_elems = [[1, 2], [3, 4], [5, 6], [7, 8]]
enqueue_op = q.enqueue_many((float_elems, int_elems))
dequeued_t = q.dequeue()
enqueue_op.run()
enqueue_op.run()
for i in range(8):
float_val, int_val = self.evaluate(dequeued_t)
self.assertEqual(float_elems[i % 4], float_val)
self.assertAllEqual(int_elems[i % 4], int_val)
def testDequeueMany(self):
with self.cached_session():
q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),))
elems = [10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0]
enqueue_op = q.enqueue_many((elems,))
dequeued_t = q.dequeue_many(4)
enqueue_op.run()
self.assertAllEqual(elems[0:4], self.evaluate(dequeued_t))
self.assertAllEqual(elems[4:8], self.evaluate(dequeued_t))
def testDequeueUpToNoBlocking(self):
with self.cached_session():
q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),))
elems = [10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0]
enqueue_op = q.enqueue_many((elems,))
dequeued_t = q.dequeue_up_to(4)
enqueue_op.run()
self.assertAllEqual(elems[0:4], self.evaluate(dequeued_t))
self.assertAllEqual(elems[4:8], self.evaluate(dequeued_t))
def testMultiDequeueMany(self):
with self.cached_session() as sess:
q = data_flow_ops.PaddingFIFOQueue(
10, (dtypes_lib.float32, dtypes_lib.int32), shapes=((), (2,)))
float_elems = [
10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0
]
int_elems = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12], [13, 14],
[15, 16], [17, 18], [19, 20]]
enqueue_op = q.enqueue_many((float_elems, int_elems))
dequeued_t = q.dequeue_many(4)
dequeued_single_t = q.dequeue()
enqueue_op.run()
float_val, int_val = self.evaluate(dequeued_t)
self.assertAllEqual(float_elems[0:4], float_val)
self.assertAllEqual(int_elems[0:4], int_val)
self.assertEqual(float_val.shape, dequeued_t[0].get_shape())
self.assertEqual(int_val.shape, dequeued_t[1].get_shape())
float_val, int_val = self.evaluate(dequeued_t)
self.assertAllEqual(float_elems[4:8], float_val)
self.assertAllEqual(int_elems[4:8], int_val)
float_val, int_val = self.evaluate(dequeued_single_t)
self.assertAllEqual(float_elems[8], float_val)
self.assertAllEqual(int_elems[8], int_val)
self.assertEqual(float_val.shape, dequeued_single_t[0].get_shape())
self.assertEqual(int_val.shape, dequeued_single_t[1].get_shape())
def testMultiDequeueManyWithPartiallyKnownShapes(self):
with self.cached_session() as sess:
q = data_flow_ops.PaddingFIFOQueue(
10, (dtypes_lib.float32, dtypes_lib.int32), shapes=((), (None,)))
float_elems = [
10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0
]
int_elems = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12], [13, 14],
[15, 16], [17, 18], [19, 20]]
enqueue_op = q.enqueue_many((float_elems, int_elems))
dequeued_t = q.dequeue_many(4)
dequeued_single_t = q.dequeue()
enqueue_op.run()
float_val, int_val = self.evaluate(dequeued_t)
self.assertAllEqual(float_elems[0:4], float_val)
self.assertAllEqual(int_elems[0:4], int_val)
self.assertTrue(
tensor_shape.TensorShape(float_val.shape).is_compatible_with(
dequeued_t[0].get_shape()))
self.assertTrue(
tensor_shape.TensorShape(int_val.shape).is_compatible_with(dequeued_t[
1].get_shape()))
float_val, int_val = self.evaluate(dequeued_t)
self.assertAllEqual(float_elems[4:8], float_val)
self.assertAllEqual(int_elems[4:8], int_val)
float_val, int_val = self.evaluate(dequeued_single_t)
self.assertAllEqual(float_elems[8], float_val)
self.assertAllEqual(int_elems[8], int_val)
self.assertTrue(
tensor_shape.TensorShape(float_val.shape).is_compatible_with(
dequeued_single_t[0].get_shape()))
self.assertTrue(
tensor_shape.TensorShape(int_val.shape).is_compatible_with(
dequeued_single_t[1].get_shape()))
def testMultiDequeueManyWithPartiallyKnownShapesAndVariableSizeInput(self):
with self.cached_session() as sess:
q = data_flow_ops.PaddingFIFOQueue(
10, (dtypes_lib.string, dtypes_lib.int32),
shapes=((None,), (1, None)))
str_elems = [["a"], ["ab"], ["abc"], ["abc", "d"], ["abc", "d", "e"],
["abc", "d", "e", "f"]]
int_elems = [[[1]], [[2]], [[3]], [[1, 2]], [[1, 2, 3]], [[1, 2, 3, 4]]]
enqueue_ops = [q.enqueue((str_elems[i], int_elems[i])) for i in range(6)]
dequeued_t = q.dequeue_many(5)
dequeued_single_t = q.dequeue()
for enqueue_op in enqueue_ops:
enqueue_op.run()
string_val, int_val = self.evaluate(dequeued_t)
self.assertAllEqual([[b"a", b"", b""], [b"ab", b"", b""],
[b"abc", b"", b""], [b"abc", b"d", b""],
[b"abc", b"d", b"e"]], string_val)
self.assertAllEqual([[[1, 0, 0]], [[2, 0, 0]], [[3, 0, 0]], [[1, 2, 0]],
[[1, 2, 3]]], int_val)
self.assertTrue(
tensor_shape.TensorShape(string_val.shape).is_compatible_with(
dequeued_t[0].get_shape()))
self.assertTrue(
tensor_shape.TensorShape(int_val.shape).is_compatible_with(dequeued_t[
1].get_shape()))
string_val, int_val = self.evaluate(dequeued_single_t)
self.assertAllEqual([b"abc", b"d", b"e", b"f"], string_val)
self.assertAllEqual([[1, 2, 3, 4]], int_val)
self.assertTrue(
tensor_shape.TensorShape(string_val.shape).is_compatible_with(
dequeued_single_t[0].get_shape()))
self.assertTrue(
tensor_shape.TensorShape(int_val.shape).is_compatible_with(
dequeued_single_t[1].get_shape()))
def testMultiDequeueUpToPartiallyKnownShapesAndVariableInputNoBlocking(self):
with self.cached_session() as sess:
q = data_flow_ops.PaddingFIFOQueue(
10, (dtypes_lib.string, dtypes_lib.int32),
shapes=((None,), (1, None)))
str_elems = [["a"], ["ab"], ["abc"], ["abc", "d"], ["abc", "d", "e"],
["abc", "d", "e", "f"]]
int_elems = [[[1]], [[2]], [[3]], [[1, 2]], [[1, 2, 3]], [[1, 2, 3, 4]]]
enqueue_ops = [q.enqueue((str_elems[i], int_elems[i])) for i in range(6)]
dequeued_t = q.dequeue_up_to(5)
dequeued_single_t = q.dequeue()
for enqueue_op in enqueue_ops:
enqueue_op.run()
string_val, int_val = self.evaluate(dequeued_t)
self.assertAllEqual([[b"a", b"", b""], [b"ab", b"", b""],
[b"abc", b"", b""], [b"abc", b"d", b""],
[b"abc", b"d", b"e"]], string_val)
self.assertAllEqual([[[1, 0, 0]], [[2, 0, 0]], [[3, 0, 0]], [[1, 2, 0]],
[[1, 2, 3]]], int_val)
self.assertTrue(
tensor_shape.TensorShape(string_val.shape).is_compatible_with(
dequeued_t[0].get_shape()))
self.assertTrue(
tensor_shape.TensorShape(int_val.shape).is_compatible_with(dequeued_t[
1].get_shape()))
string_val, int_val = self.evaluate(dequeued_single_t)
self.assertAllEqual([b"abc", b"d", b"e", b"f"], string_val)
self.assertAllEqual([[1, 2, 3, 4]], int_val)
self.assertTrue(
tensor_shape.TensorShape(string_val.shape).is_compatible_with(
dequeued_single_t[0].get_shape()))
self.assertTrue(
tensor_shape.TensorShape(int_val.shape).is_compatible_with(
dequeued_single_t[1].get_shape()))
def testHighDimension(self):
with self.cached_session():
q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.int32, ((4, 4, 4, 4),))
elems = np.array([[[[[x] * 4] * 4] * 4] * 4 for x in range(10)], np.int32)
enqueue_op = q.enqueue_many((elems,))
dequeued_t = q.dequeue_many(10)
enqueue_op.run()
self.assertAllEqual(dequeued_t, elems)
def testPartiallyKnownHighDimension(self):
with self.cached_session():
q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.int32, (
(4, None, 4, None),))
elems = np.array([[[[[x] * 4] * 4] * 4] * 4 for x in range(10)], np.int32)
enqueue_op = q.enqueue_many((elems,))
dequeued_t = q.dequeue_many(10)
enqueue_op.run()
self.assertAllEqual(dequeued_t, elems)
def testEnqueueWrongShape(self):
q = data_flow_ops.PaddingFIFOQueue(10, (dtypes_lib.int32, dtypes_lib.int32),
((), (2,)))
with self.assertRaises(ValueError):
q.enqueue(([1, 2], [2, 2]))
with self.assertRaises(ValueError):
q.enqueue_many((7, [[1, 2], [3, 4], [5, 6]]))
def testBatchSizeMismatch(self):
q = data_flow_ops.PaddingFIFOQueue(10, (dtypes_lib.int32, dtypes_lib.int32,
dtypes_lib.int32), ((), (), ()))
with self.assertRaises(ValueError):
q.enqueue_many(([1, 2, 3], [1, 2], [1, 2, 3]))
with self.assertRaises(ValueError):
q.enqueue_many(
([1, 2, 3], [1, 2], array_ops.placeholder(dtypes_lib.int32)))
with self.assertRaises(ValueError):
q.enqueue_many(
(array_ops.placeholder(dtypes_lib.int32), [1, 2], [1, 2, 3]))
def testEnqueueManyEmptyTypeConversion(self):
q = data_flow_ops.PaddingFIFOQueue(10,
(dtypes_lib.int32, dtypes_lib.float32), (
(), ()))
enq = q.enqueue_many(([], []))
self.assertEqual(dtypes_lib.int32, enq.inputs[1].dtype)
self.assertEqual(dtypes_lib.float32, enq.inputs[2].dtype)
def testEnqueueWrongType(self):
q = data_flow_ops.PaddingFIFOQueue(10,
(dtypes_lib.int32, dtypes_lib.float32), (
(), ()))
with self.assertRaises(ValueError):
q.enqueue((array_ops.placeholder(dtypes_lib.int32),
array_ops.placeholder(dtypes_lib.int32)))
with self.assertRaises(ValueError):
q.enqueue_many((array_ops.placeholder(dtypes_lib.int32),
array_ops.placeholder(dtypes_lib.int32)))
def testEnqueueWrongPartiallyKnownShapeAtRuntime(self):
with self.cached_session() as sess:
# First dimension of second component is unknown, second
# dimension must be 3.
q = data_flow_ops.PaddingFIFOQueue(10,
(dtypes_lib.int32, dtypes_lib.int32), (
(2, 2), (None, 3)))
elems_ok = np.array([1] * 4).reshape((2, 2)).astype(np.int32)
elems_bad = array_ops.placeholder(dtypes_lib.int32)
enqueue_op = q.enqueue((elems_ok, elems_bad))
with self.assertRaisesRegex(errors_impl.InvalidArgumentError,
r"Expected \[\?,3\], got \[3,4\]"):
sess.run([enqueue_op],
feed_dict={elems_bad: np.array([1] * 12).reshape((3, 4))})
def testEnqueueDequeueManyWrongPartiallyKnownShape(self):
with self.cached_session() as sess:
# First dimension of second component is unknown, second
# dimension must be 3.
q = data_flow_ops.PaddingFIFOQueue(10,
(dtypes_lib.int32, dtypes_lib.int32), (
(2, 2), (None, 3)))
elems_ok = np.array([1] * 8).reshape((2, 2, 2)).astype(np.int32)
elems_bad = array_ops.placeholder(dtypes_lib.int32)
enqueue_op = q.enqueue_many((elems_ok, elems_bad))
dequeued_t = q.dequeue_many(2)
with self.assertRaisesRegex(
errors_impl.InvalidArgumentError,
"Shape mismatch in tuple component 1. "
r"Expected \[2,\?,3\], got \[2,3,4\]"):
sess.run([enqueue_op],
feed_dict={elems_bad: np.array([1] * 24).reshape((2, 3, 4))})
self.evaluate(dequeued_t)
def testParallelEnqueueMany(self):
# We need each thread to keep its own device stack or the device scopes
# won't be properly nested.
ops.get_default_graph().switch_to_thread_local()
with self.cached_session() as sess:
q = data_flow_ops.PaddingFIFOQueue(1000, dtypes_lib.float32, shapes=((),))
elems = [10.0 * x for x in range(100)]
enqueue_op = q.enqueue_many((elems,))
dequeued_t = q.dequeue_many(1000)
# Enqueue 100 items in parallel on 10 threads.
def enqueue():
self.evaluate(enqueue_op)
threads = [self.checkedThread(target=enqueue) for _ in range(10)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
self.assertCountEqual(self.evaluate(dequeued_t), elems * 10)
def testParallelDequeueMany(self):
# We need each thread to keep its own device stack or the device scopes
# won't be properly nested.
ops.get_default_graph().switch_to_thread_local()
with self.cached_session() as sess:
q = data_flow_ops.PaddingFIFOQueue(1000, dtypes_lib.float32, shapes=((),))
elems = [10.0 * x for x in range(1000)]
enqueue_op = q.enqueue_many((elems,))
dequeued_t = q.dequeue_many(100)
enqueue_op.run()
# Dequeue 100 items in parallel on 10 threads.
dequeued_elems = []
def dequeue():
dequeued_elems.extend(self.evaluate(dequeued_t))
threads = [self.checkedThread(target=dequeue) for _ in range(10)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
self.assertItemsEqual(elems, dequeued_elems)
def testParallelDequeueUpTo(self):
# We need each thread to keep its own device stack or the device scopes
# won't be properly nested.
ops.get_default_graph().switch_to_thread_local()
with self.cached_session() as sess:
q = data_flow_ops.PaddingFIFOQueue(1000, dtypes_lib.float32, shapes=((),))
elems = [10.0 * x for x in range(1000)]
enqueue_op = q.enqueue_many((elems,))
close_op = q.close()
dequeued_t = q.dequeue_up_to(101)
enqueue_op.run()
close_op.run()
# Dequeue up to 101 items in parallel on 10 threads, from closed queue.
dequeued_elems = []
def dequeue():
dequeued_elems.extend(self.evaluate(dequeued_t))
threads = [self.checkedThread(target=dequeue) for _ in range(10)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
self.assertItemsEqual(elems, dequeued_elems)
def testParallelEnqueueAndDequeue(self):
# We need each thread to keep its own device stack or the device scopes
# won't be properly nested.
ops.get_default_graph().switch_to_thread_local()
with self.cached_session() as sess:
q = data_flow_ops.PaddingFIFOQueue(50, dtypes_lib.float32, shapes=((),))
initial_elements = [10.0] * 49
q.enqueue_many((initial_elements,)).run()
enqueue_op = q.enqueue((20.0,))
dequeued_t = q.dequeue()
def enqueue():
for _ in range(100):
self.evaluate(enqueue_op)
def dequeue():
for _ in range(100):
self.assertTrue(self.evaluate(dequeued_t) in (10.0, 20.0))
enqueue_threads = [self.checkedThread(target=enqueue) for _ in range(10)]
dequeue_threads = [self.checkedThread(target=dequeue) for _ in range(10)]
for enqueue_thread in enqueue_threads:
enqueue_thread.start()
for dequeue_thread in dequeue_threads:
dequeue_thread.start()
for enqueue_thread in enqueue_threads:
enqueue_thread.join()
for dequeue_thread in dequeue_threads:
dequeue_thread.join()
# Dequeue the initial count of elements to clean up.
cleanup_elems = q.dequeue_many(49).eval()
for elem in cleanup_elems:
self.assertTrue(elem in (10.0, 20.0))
def testMixtureOfEnqueueAndEnqueueMany(self):
with self.cached_session() as sess:
q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.int32, shapes=((),))
enqueue_placeholder = array_ops.placeholder(dtypes_lib.int32, shape=())
enqueue_op = q.enqueue((enqueue_placeholder,))
enqueuemany_placeholder = array_ops.placeholder(
dtypes_lib.int32, shape=(None,))
enqueuemany_op = q.enqueue_many((enqueuemany_placeholder,))
dequeued_t = q.dequeue()
close_op = q.close()
def dequeue():
for i in range(250):
self.assertEqual(i, self.evaluate(dequeued_t))
dequeue_thread = self.checkedThread(target=dequeue)
dequeue_thread.start()
elements_enqueued = 0
while elements_enqueued < 250:
# With equal probability, run Enqueue or enqueue_many.
if random.random() > 0.5:
enqueue_op.run({enqueue_placeholder: elements_enqueued})
elements_enqueued += 1
else:
count = random.randint(0, min(20, 250 - elements_enqueued))
range_to_enqueue = np.arange(
elements_enqueued, elements_enqueued + count, dtype=np.int32)
enqueuemany_op.run({enqueuemany_placeholder: range_to_enqueue})
elements_enqueued += count
close_op.run()
dequeue_thread.join()
self.assertEqual(0, q.size().eval())
def testMixtureOfDequeueAndDequeueMany(self):
with self.cached_session() as sess:
q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.int32, shapes=((),))
enqueue_op = q.enqueue_many((np.arange(250, dtype=np.int32),))
dequeued_t = q.dequeue()
count_placeholder = array_ops.placeholder(dtypes_lib.int32, shape=())
dequeuemany_t = q.dequeue_many(count_placeholder)
def enqueue():
self.evaluate(enqueue_op)
enqueue_thread = self.checkedThread(target=enqueue)
enqueue_thread.start()
elements_dequeued = 0
while elements_dequeued < 250:
# With equal probability, run Dequeue or dequeue_many.
if random.random() > 0.5:
self.assertEqual(elements_dequeued, self.evaluate(dequeued_t))
elements_dequeued += 1
else:
count = random.randint(0, min(20, 250 - elements_dequeued))
expected_range = np.arange(
elements_dequeued, elements_dequeued + count, dtype=np.int32)
self.assertAllEqual(expected_range,
dequeuemany_t.eval({
count_placeholder: count
}))
elements_dequeued += count
q.close().run()
enqueue_thread.join()
self.assertEqual(0, q.size().eval())
def testBlockingDequeueMany(self):
# We need each thread to keep its own device stack or the device scopes
# won't be properly nested.
ops.get_default_graph().switch_to_thread_local()
with self.cached_session() as sess:
q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),))
elems = [10.0, 20.0, 30.0, 40.0]
enqueue_op = q.enqueue_many((elems,))
dequeued_t = q.dequeue_many(4)
dequeued_elems = []
def enqueue():
# The enqueue_op should run after the dequeue op has blocked.
# TODO(mrry): Figure out how to do this without sleeping.
time.sleep(0.1)
self.evaluate(enqueue_op)
def dequeue():
dequeued_elems.extend(self.evaluate(dequeued_t).tolist())
enqueue_thread = self.checkedThread(target=enqueue)
dequeue_thread = self.checkedThread(target=dequeue)
enqueue_thread.start()
dequeue_thread.start()
enqueue_thread.join()
dequeue_thread.join()
self.assertAllEqual(elems, dequeued_elems)
def testBlockingDequeueUpTo(self):
# We need each thread to keep its own device stack or the device scopes
# won't be properly nested.
ops.get_default_graph().switch_to_thread_local()
with self.cached_session() as sess:
q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),))
elems = [10.0, 20.0, 30.0, 40.0]
enqueue_op = q.enqueue_many((elems,))
dequeued_t = q.dequeue_up_to(4)
dequeued_elems = []
def enqueue():
# The enqueue_op should run after the dequeue op has blocked.
# TODO(mrry): Figure out how to do this without sleeping.
time.sleep(0.1)
self.evaluate(enqueue_op)
def dequeue():
dequeued_elems.extend(self.evaluate(dequeued_t).tolist())
enqueue_thread = self.checkedThread(target=enqueue)
dequeue_thread = self.checkedThread(target=dequeue)
enqueue_thread.start()
dequeue_thread.start()
enqueue_thread.join()
dequeue_thread.join()
self.assertAllEqual(elems, dequeued_elems)
def testDequeueManyWithTensorParameter(self):
with self.cached_session():
# Define a first queue that contains integer counts.
dequeue_counts = [random.randint(1, 10) for _ in range(100)]
count_q = data_flow_ops.PaddingFIFOQueue(100, dtypes_lib.int32, ((),))
enqueue_counts_op = count_q.enqueue_many((dequeue_counts,))
total_count = sum(dequeue_counts)
# Define a second queue that contains total_count elements.
elems = [random.randint(0, 100) for _ in range(total_count)]
q = data_flow_ops.PaddingFIFOQueue(total_count, dtypes_lib.int32, ((),))
enqueue_elems_op = q.enqueue_many((elems,))
# Define a subgraph that first dequeues a count, then DequeuesMany
# that number of elements.
dequeued_t = q.dequeue_many(count_q.dequeue())
enqueue_counts_op.run()
enqueue_elems_op.run()
dequeued_elems = []
for _ in dequeue_counts:
dequeued_elems.extend(self.evaluate(dequeued_t))
self.assertEqual(elems, dequeued_elems)
def testDequeueFromClosedQueue(self):
with self.cached_session():
q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),))
elems = [10.0, 20.0, 30.0, 40.0]
enqueue_op = q.enqueue_many((elems,))
close_op = q.close()
dequeued_t = q.dequeue()
enqueue_op.run()
close_op.run()
for elem in elems:
self.assertEqual([elem], self.evaluate(dequeued_t))
# Expect the operation to fail due to the queue being closed.
with self.assertRaisesRegex(errors_impl.OutOfRangeError,
"is closed and has insufficient"):
self.evaluate(dequeued_t)
def testBlockingDequeueFromClosedQueue(self):
# We need each thread to keep its own device stack or the device scopes
# won't be properly nested.
ops.get_default_graph().switch_to_thread_local()
with self.cached_session() as sess:
q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),))
elems = [10.0, 20.0, 30.0, 40.0]
enqueue_op = q.enqueue_many((elems,))
close_op = q.close()
dequeued_t = q.dequeue()
enqueue_op.run()
def dequeue():
for elem in elems:
self.assertEqual([elem], self.evaluate(dequeued_t))
# Expect the operation to fail due to the queue being closed.
with self.assertRaisesRegex(errors_impl.OutOfRangeError,
"is closed and has insufficient"):
self.evaluate(dequeued_t)
dequeue_thread = self.checkedThread(target=dequeue)
dequeue_thread.start()
# The close_op should run after the dequeue_thread has blocked.
# TODO(mrry): Figure out how to do this without sleeping.
time.sleep(0.1)
close_op.run()
dequeue_thread.join()
def testDequeueUpToFromClosedQueueReturnsRemainder(self):
with self.cached_session() as sess:
q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),))
elems = [10.0, 20.0, 30.0, 40.0]
enqueue_op = q.enqueue_many((elems,))
close_op = q.close()
dequeued_t = q.dequeue_up_to(3)
enqueue_op.run()
def dequeue():
self.assertAllEqual(elems[:3], self.evaluate(dequeued_t))
self.assertAllEqual(elems[3:], self.evaluate(dequeued_t))
dequeue_thread = self.checkedThread(target=dequeue)
dequeue_thread.start()
# The close_op should run after the dequeue_thread has blocked.
# TODO(mrry): Figure out how to do this without sleeping.
time.sleep(0.1)
close_op.run()
dequeue_thread.join()
def testBlockingDequeueFromClosedEmptyQueue(self):
# We need each thread to keep its own device stack or the device scopes
# won't be properly nested.
ops.get_default_graph().switch_to_thread_local()
with self.cached_session() as sess:
q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),))
close_op = q.close()
dequeued_t = q.dequeue()
def dequeue():
# Expect the operation to fail due to the queue being closed.
with self.assertRaisesRegex(errors_impl.OutOfRangeError,
"is closed and has insufficient"):
self.evaluate(dequeued_t)
dequeue_thread = self.checkedThread(target=dequeue)
dequeue_thread.start()
# The close_op should run after the dequeue_thread has blocked.
# TODO(mrry): Figure out how to do this without sleeping.
time.sleep(0.1)
close_op.run()
dequeue_thread.join()
def testBlockingDequeueManyFromClosedQueue(self):
# We need each thread to keep its own device stack or the device scopes
# won't be properly nested.
ops.get_default_graph().switch_to_thread_local()
with self.cached_session() as sess:
q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),))
elems = [10.0, 20.0, 30.0, 40.0]
enqueue_op = q.enqueue_many((elems,))
close_op = q.close()
dequeued_t = q.dequeue_many(4)
enqueue_op.run()
def dequeue():
self.assertAllEqual(elems, self.evaluate(dequeued_t))
# Expect the operation to fail due to the queue being closed.
with self.assertRaisesRegex(errors_impl.OutOfRangeError,
"is closed and has insufficient"):
self.evaluate(dequeued_t)
dequeue_thread = self.checkedThread(target=dequeue)
dequeue_thread.start()
# The close_op should run after the dequeue_thread has blocked.
# TODO(mrry): Figure out how to do this without sleeping.
time.sleep(0.1)
close_op.run()
dequeue_thread.join()
def testBlockingDequeueManyButNotAllFromClosedQueue(self):
# We need each thread to keep its own device stack or the device scopes
# won't be properly nested.
ops.get_default_graph().switch_to_thread_local()
with self.cached_session() as sess:
q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),))
elems = [10.0, 20.0, 30.0, 40.0]
enqueue_op = q.enqueue_many((elems,))
close_op = q.close()
dequeued_t = q.dequeue_many(3)
enqueue_op.run()
def dequeue():
self.assertAllEqual(elems[:3], self.evaluate(dequeued_t))
# Expect the operation to fail due to the queue being closed.
with self.assertRaisesRegex(errors_impl.OutOfRangeError,
"is closed and has insufficient"):
self.evaluate(dequeued_t)
dequeue_thread = self.checkedThread(target=dequeue)
dequeue_thread.start()
# The close_op should run after the dequeue_thread has blocked.
# TODO(mrry): Figure out how to do this without sleeping.
time.sleep(0.1)
close_op.run()
dequeue_thread.join()
def testEnqueueManyLargerThanCapacityWithConcurrentDequeueMany(self):
# We need each thread to keep its own device stack or the device scopes
# won't be properly nested.
ops.get_default_graph().switch_to_thread_local()
with self.cached_session() as sess:
q = data_flow_ops.PaddingFIFOQueue(4, dtypes_lib.float32, ((),))
elems = [10.0, 20.0, 30.0, 40.0]
enqueue_op = q.enqueue_many((elems,))
close_op = q.close()
dequeued_t = q.dequeue_many(3)
cleanup_dequeue_t = q.dequeue()
def enqueue():
self.evaluate(enqueue_op)
def dequeue():
self.assertAllEqual(elems[0:3], self.evaluate(dequeued_t))
with self.assertRaises(errors_impl.OutOfRangeError):
self.evaluate(dequeued_t)
self.assertEqual(elems[3], self.evaluate(cleanup_dequeue_t))
def close():
self.evaluate(close_op)
enqueue_thread = self.checkedThread(target=enqueue)
enqueue_thread.start()
dequeue_thread = self.checkedThread(target=dequeue)
dequeue_thread.start()
# The close_op should run after the dequeue_thread has blocked.
# TODO(mrry): Figure out how to do this without sleeping.
time.sleep(0.1)
close_thread = self.checkedThread(target=close)
close_thread.start()
enqueue_thread.join()
dequeue_thread.join()
close_thread.join()
def testClosedBlockingDequeueManyRestoresPartialBatch(self):
with self.cached_session() as sess:
q = data_flow_ops.PaddingFIFOQueue(4, (dtypes_lib.float32,
dtypes_lib.float32), ((), ()))
elems_a = [1.0, 2.0, 3.0]
elems_b = [10.0, 20.0, 30.0]
enqueue_op = q.enqueue_many((elems_a, elems_b))
dequeued_a_t, dequeued_b_t = q.dequeue_many(4)
cleanup_dequeue_a_t, cleanup_dequeue_b_t = q.dequeue()
close_op = q.close()
enqueue_op.run()
def dequeue():
with self.assertRaises(errors_impl.OutOfRangeError):
self.evaluate([dequeued_a_t, dequeued_b_t])
dequeue_thread = self.checkedThread(target=dequeue)
dequeue_thread.start()
# The close_op should run after the dequeue_thread has blocked.
# TODO(mrry): Figure out how to do this without sleeping.
time.sleep(0.1)
close_op.run()
dequeue_thread.join()
# Test that the elements in the partially-dequeued batch are
# restored in the correct order.
for elem_a, elem_b in zip(elems_a, elems_b):
val_a, val_b = self.evaluate([cleanup_dequeue_a_t, cleanup_dequeue_b_t])
self.assertEqual(elem_a, val_a)
self.assertEqual(elem_b, val_b)
self.assertEqual(0, q.size().eval())
def testBlockingDequeueManyFromClosedEmptyQueue(self):
# We need each thread to keep its own device stack or the device scopes
# won't be properly nested.
ops.get_default_graph().switch_to_thread_local()
with self.cached_session() as sess:
q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),))
close_op = q.close()
dequeued_t = q.dequeue_many(4)
def dequeue():
# Expect the operation to fail due to the queue being closed.
with self.assertRaisesRegex(errors_impl.OutOfRangeError,
"is closed and has insufficient"):
self.evaluate(dequeued_t)
dequeue_thread = self.checkedThread(target=dequeue)
dequeue_thread.start()
# The close_op should run after the dequeue_thread has blocked.
# TODO(mrry): Figure out how to do this without sleeping.
time.sleep(0.1)
close_op.run()
dequeue_thread.join()
def testBlockingDequeueUpToFromClosedEmptyQueue(self):
# We need each thread to keep its own device stack or the device scopes
# won't be properly nested.
ops.get_default_graph().switch_to_thread_local()
with self.cached_session() as sess:
q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),))
close_op = q.close()
dequeued_t = q.dequeue_up_to(4)
def dequeue():
# Expect the operation to fail due to the queue being closed.
with self.assertRaisesRegex(errors_impl.OutOfRangeError,
"is closed and has insufficient"):
self.evaluate(dequeued_t)
dequeue_thread = self.checkedThread(target=dequeue)
dequeue_thread.start()
# The close_op should run after the dequeue_thread has blocked.
# TODO(mrry): Figure out how to do this without sleeping.
time.sleep(0.1)
close_op.run()
dequeue_thread.join()
def testEnqueueToClosedQueue(self):
with self.cached_session():
q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),))
enqueue_op = q.enqueue((10.0,))
close_op = q.close()
enqueue_op.run()
close_op.run()
# Expect the operation to fail due to the queue being closed.
with self.assertRaisesRegex(errors_impl.CancelledError, "is closed"):
enqueue_op.run()
def testEnqueueManyToClosedQueue(self):
with self.cached_session():
q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),))
elems = [10.0, 20.0, 30.0, 40.0]
enqueue_op = q.enqueue_many((elems,))
close_op = q.close()
enqueue_op.run()
close_op.run()
# Expect the operation to fail due to the queue being closed.
with self.assertRaisesRegex(errors_impl.CancelledError, "is closed"):
enqueue_op.run()
def testBlockingEnqueueToFullQueue(self):
# We need each thread to keep its own device stack or the device scopes
# won't be properly nested.
ops.get_default_graph().switch_to_thread_local()
with self.cached_session() as sess:
q = data_flow_ops.PaddingFIFOQueue(4, dtypes_lib.float32, ((),))
elems = [10.0, 20.0, 30.0, 40.0]
enqueue_op = q.enqueue_many((elems,))
blocking_enqueue_op = q.enqueue((50.0,))
dequeued_t = q.dequeue()
enqueue_op.run()
def blocking_enqueue():
self.evaluate(blocking_enqueue_op)
thread = self.checkedThread(target=blocking_enqueue)
thread.start()
# The dequeue ops should run after the blocking_enqueue_op has blocked.
# TODO(mrry): Figure out how to do this without sleeping.
time.sleep(0.1)
for elem in elems:
self.assertEqual([elem], self.evaluate(dequeued_t))
self.assertEqual([50.0], self.evaluate(dequeued_t))
thread.join()
def testBlockingEnqueueManyToFullQueue(self):
# We need each thread to keep its own device stack or the device scopes
# won't be properly nested.
ops.get_default_graph().switch_to_thread_local()
with self.cached_session() as sess:
q = data_flow_ops.PaddingFIFOQueue(4, dtypes_lib.float32, ((),))
elems = [10.0, 20.0, 30.0, 40.0]
enqueue_op = q.enqueue_many((elems,))
blocking_enqueue_op = q.enqueue_many(([50.0, 60.0],))
dequeued_t = q.dequeue()
enqueue_op.run()
def blocking_enqueue():
self.evaluate(blocking_enqueue_op)
thread = self.checkedThread(target=blocking_enqueue)
thread.start()
# The dequeue ops should run after the blocking_enqueue_op has blocked.
# TODO(mrry): Figure out how to do this without sleeping.
time.sleep(0.1)
for elem in elems:
self.assertEqual([elem], self.evaluate(dequeued_t))
time.sleep(0.01)
self.assertEqual([50.0], self.evaluate(dequeued_t))
self.assertEqual([60.0], self.evaluate(dequeued_t))
# Make sure the thread finishes before exiting.
thread.join()
def testBlockingEnqueueBeforeClose(self):
# We need each thread to keep its own device stack or the device scopes
# won't be properly nested.
ops.get_default_graph().switch_to_thread_local()
with self.cached_session() as sess:
q = data_flow_ops.PaddingFIFOQueue(4, dtypes_lib.float32, ((),))
elems = [10.0, 20.0, 30.0, 40.0]
enqueue_op = q.enqueue_many((elems,))
blocking_enqueue_op = q.enqueue((50.0,))
close_op = q.close()
dequeued_t = q.dequeue()
enqueue_op.run()
def blocking_enqueue():
# Expect the operation to succeed once the dequeue op runs.
self.evaluate(blocking_enqueue_op)
enqueue_thread = self.checkedThread(target=blocking_enqueue)
enqueue_thread.start()
# The close_op should run after the blocking_enqueue_op has blocked.
# TODO(mrry): Figure out how to do this without sleeping.
time.sleep(0.1)
def close():
self.evaluate(close_op)
close_thread = self.checkedThread(target=close)
close_thread.start()
# The dequeue will unblock both threads.
self.assertEqual(10.0, self.evaluate(dequeued_t))
enqueue_thread.join()
close_thread.join()
for elem in [20.0, 30.0, 40.0, 50.0]:
self.assertEqual(elem, self.evaluate(dequeued_t))
self.assertEqual(0, q.size().eval())
def testBlockingEnqueueManyBeforeClose(self):
# We need each thread to keep its own device stack or the device scopes
# won't be properly nested.
ops.get_default_graph().switch_to_thread_local()
with self.cached_session() as sess:
q = data_flow_ops.PaddingFIFOQueue(4, dtypes_lib.float32, ((),))
elems = [10.0, 20.0, 30.0]
enqueue_op = q.enqueue_many((elems,))
blocking_enqueue_op = q.enqueue_many(([50.0, 60.0],))
close_op = q.close()
dequeued_t = q.dequeue()
enqueue_op.run()
def blocking_enqueue():
self.evaluate(blocking_enqueue_op)
enqueue_thread = self.checkedThread(target=blocking_enqueue)
enqueue_thread.start()
# The close_op should run after the blocking_enqueue_op has blocked.
# TODO(mrry): Figure out how to do this without sleeping.
time.sleep(0.1)
def close():
self.evaluate(close_op)
close_thread = self.checkedThread(target=close)
close_thread.start()
# The dequeue will unblock both threads.
self.assertEqual(10.0, self.evaluate(dequeued_t))
enqueue_thread.join()
close_thread.join()
for elem in [20.0, 30.0, 50.0, 60.0]:
self.assertEqual(elem, self.evaluate(dequeued_t))
def testDoesNotLoseValue(self):
with self.cached_session():
q = data_flow_ops.PaddingFIFOQueue(1, dtypes_lib.float32, ((),))
enqueue_op = q.enqueue((10.0,))
size_t = q.size()
enqueue_op.run()
for _ in range(500):
self.assertEqual(self.evaluate(size_t), [1])
def testSharedQueueSameSession(self):
with self.cached_session():
q1 = data_flow_ops.PaddingFIFOQueue(
1, dtypes_lib.float32, ((),), shared_name="shared_queue")
q1.enqueue((10.0,)).run()
q2 = data_flow_ops.PaddingFIFOQueue(
1, dtypes_lib.float32, ((),), shared_name="shared_queue")
q1_size_t = q1.size()
q2_size_t = q2.size()
self.assertEqual(self.evaluate(q1_size_t), [1])
self.assertEqual(self.evaluate(q2_size_t), [1])
self.assertEqual(q2.dequeue().eval(), [10.0])
self.assertEqual(self.evaluate(q1_size_t), [0])
self.assertEqual(self.evaluate(q2_size_t), [0])
q2.enqueue((20.0,)).run()
self.assertEqual(self.evaluate(q1_size_t), [1])
self.assertEqual(self.evaluate(q2_size_t), [1])
self.assertEqual(q1.dequeue().eval(), [20.0])
self.assertEqual(self.evaluate(q1_size_t), [0])
self.assertEqual(self.evaluate(q2_size_t), [0])
def testIncompatibleSharedQueueErrors(self):
with self.cached_session():
q_a_1 = data_flow_ops.PaddingFIFOQueue(
10, dtypes_lib.float32, ((),), shared_name="q_a")
q_a_2 = data_flow_ops.PaddingFIFOQueue(
15, dtypes_lib.float32, ((),), shared_name="q_a")
q_a_1.queue_ref.op.run()
with self.assertRaisesOpError("capacity"):
q_a_2.queue_ref.op.run()
q_b_1 = data_flow_ops.PaddingFIFOQueue(
10, dtypes_lib.float32, ((),), shared_name="q_b")
q_b_2 = data_flow_ops.PaddingFIFOQueue(
10, dtypes_lib.int32, ((),), shared_name="q_b")
q_b_1.queue_ref.op.run()
with self.assertRaisesOpError("component types"):
q_b_2.queue_ref.op.run()
q_c_1 = data_flow_ops.PaddingFIFOQueue(
10, dtypes_lib.float32, ((),), shared_name="q_c")
q_c_2 = data_flow_ops.PaddingFIFOQueue(
10, dtypes_lib.float32, shapes=[(1, 1, 2, 3)], shared_name="q_c")
q_c_1.queue_ref.op.run()
with self.assertRaisesOpError("component shapes"):
q_c_2.queue_ref.op.run()
q_d_1 = data_flow_ops.PaddingFIFOQueue(
10, dtypes_lib.float32, shapes=[(1, 1, 2, 3)], shared_name="q_d")
q_d_2 = data_flow_ops.PaddingFIFOQueue(
10, dtypes_lib.float32, ((),), shared_name="q_d")
q_d_1.queue_ref.op.run()
with self.assertRaisesOpError("component shapes"):
q_d_2.queue_ref.op.run()
q_e_1 = data_flow_ops.PaddingFIFOQueue(
10, dtypes_lib.float32, shapes=[(1, 1, 2, 3)], shared_name="q_e")
q_e_2 = data_flow_ops.PaddingFIFOQueue(
10, dtypes_lib.float32, shapes=[(1, 1, 2, 4)], shared_name="q_e")
q_e_1.queue_ref.op.run()
with self.assertRaisesOpError("component shapes"):
q_e_2.queue_ref.op.run()
q_f_1 = data_flow_ops.PaddingFIFOQueue(
10, dtypes_lib.float32, ((),), shared_name="q_f")
q_f_2 = data_flow_ops.PaddingFIFOQueue(
10, (dtypes_lib.float32, dtypes_lib.int32), ((), ()),
shared_name="q_f")
q_f_1.queue_ref.op.run()
with self.assertRaisesOpError("component types"):
q_f_2.queue_ref.op.run()
def testSelectQueue(self):
with self.cached_session():
num_queues = 10
qlist = []
for _ in range(num_queues):
qlist.append(
data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),)))
# Enqueue/Dequeue into a dynamically selected queue
for _ in range(20):
index = np.random.randint(num_queues)
q = data_flow_ops.PaddingFIFOQueue.from_list(index, qlist)
q.enqueue((10.,)).run()
self.assertEqual(q.dequeue().eval(), 10.0)
def testSelectQueueOutOfRange(self):
with self.cached_session():
q1 = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),))
q2 = data_flow_ops.PaddingFIFOQueue(15, dtypes_lib.float32, ((),))
enq_q = data_flow_ops.PaddingFIFOQueue.from_list(3, [q1, q2])
with self.assertRaisesOpError("is not in"):
enq_q.dequeue().eval()
def _blockingDequeue(self, sess, dequeue_op):
with self.assertRaisesOpError("was cancelled"):
self.evaluate(dequeue_op)
def _blockingDequeueMany(self, sess, dequeue_many_op):
with self.assertRaisesOpError("was cancelled"):
self.evaluate(dequeue_many_op)
def _blockingEnqueue(self, sess, enqueue_op):
with self.assertRaisesOpError("was cancelled"):
self.evaluate(enqueue_op)
def _blockingEnqueueMany(self, sess, enqueue_many_op):
with self.assertRaisesOpError("was cancelled"):
self.evaluate(enqueue_many_op)
@test_util.run_deprecated_v1
def testResetOfBlockingOperation(self):
# We need each thread to keep its own device stack or the device scopes
# won't be properly nested.
ops.get_default_graph().switch_to_thread_local()
with self.cached_session() as sess:
q_empty = data_flow_ops.PaddingFIFOQueue(5, dtypes_lib.float32, ((),))
dequeue_op = q_empty.dequeue()
dequeue_many_op = q_empty.dequeue_many(1)
q_full = data_flow_ops.PaddingFIFOQueue(5, dtypes_lib.float32, ((),))
sess.run(q_full.enqueue_many(([1.0, 2.0, 3.0, 4.0, 5.0],)))
enqueue_op = q_full.enqueue((6.0,))
enqueue_many_op = q_full.enqueue_many(([6.0],))
threads = [
self.checkedThread(
self._blockingDequeue, args=(sess, dequeue_op)),
self.checkedThread(
self._blockingDequeueMany, args=(sess, dequeue_many_op)),
self.checkedThread(
self._blockingEnqueue, args=(sess, enqueue_op)),
self.checkedThread(
self._blockingEnqueueMany, args=(sess, enqueue_many_op))
]
for t in threads:
t.start()
time.sleep(0.1)
sess.close() # Will cancel the blocked operations.
for t in threads:
t.join()
def testBigEnqueueMany(self):
with self.cached_session() as sess:
q = data_flow_ops.PaddingFIFOQueue(5, dtypes_lib.int32, ((),))
elem = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
enq = q.enqueue_many((elem,))
deq = q.dequeue()
size_op = q.size()
enq_done = []
def blocking_enqueue():
enq_done.append(False)
# This will fill the queue and then block until enough dequeues happen.
self.evaluate(enq)
enq_done.append(True)
thread = self.checkedThread(target=blocking_enqueue)
thread.start()
# The enqueue should start and then block.
results = []
results.append(
self.evaluate(deq)) # Will only complete after the enqueue starts.
self.assertEqual(len(enq_done), 1)
self.assertEqual(self.evaluate(size_op), 5)
for _ in range(3):
results.append(self.evaluate(deq))
time.sleep(0.1)
self.assertEqual(len(enq_done), 1)
self.assertEqual(self.evaluate(size_op), 5)
# This dequeue will unblock the thread.
results.append(self.evaluate(deq))
time.sleep(0.1)
self.assertEqual(len(enq_done), 2)
thread.join()
for i in range(5):
self.assertEqual(self.evaluate(size_op), 5 - i)
results.append(self.evaluate(deq))
self.assertEqual(self.evaluate(size_op), 5 - i - 1)
self.assertAllEqual(elem, results)
def testBigDequeueMany(self):
with self.cached_session() as sess:
q = data_flow_ops.PaddingFIFOQueue(2, dtypes_lib.int32, ((),))
elem = np.arange(4, dtype=np.int32)
enq_list = [q.enqueue((e,)) for e in elem]
deq = q.dequeue_many(4)
results = []
def blocking_dequeue():
# Will only complete after 4 enqueues complete.
results.extend(self.evaluate(deq))
thread = self.checkedThread(target=blocking_dequeue)
thread.start()
# The dequeue should start and then block.
for enq in enq_list:
# TODO(mrry): Figure out how to do this without sleeping.
time.sleep(0.1)
self.assertEqual(len(results), 0)
self.evaluate(enq)
# Enough enqueued to unblock the dequeue
thread.join()
self.assertAllEqual(elem, results)
def testDtypes(self):
with self.cached_session() as sess:
dtypes = [
dtypes_lib.float32, dtypes_lib.float64, dtypes_lib.int32,
dtypes_lib.uint8, dtypes_lib.int16, dtypes_lib.int8, dtypes_lib.int64,
dtypes_lib.bool, dtypes_lib.complex64, dtypes_lib.complex128
]
shape = (32, 4, 128)
q = data_flow_ops.PaddingFIFOQueue(32, dtypes, [shape[1:]] * len(dtypes))
input_tuple = []
for dtype in dtypes:
np_dtype = dtype.as_numpy_dtype
np_array = np.random.randint(-10, 10, shape)
if dtype == dtypes_lib.bool:
np_array = np_array > 0
elif dtype in (dtypes_lib.complex64, dtypes_lib.complex128):
np_array = np.sqrt(np_array.astype(np_dtype))
else:
np_array = np_array.astype(np_dtype)
input_tuple.append(np_array)
q.enqueue_many(input_tuple).run()
output_tuple_t = q.dequeue_many(32)
output_tuple = self.evaluate(output_tuple_t)
for (input_elem, output_elem) in zip(input_tuple, output_tuple):
self.assertAllEqual(input_elem, output_elem)
def testUnknownRank(self):
with self.assertRaisesRegex(ValueError, "must have a defined rank"):
data_flow_ops.PaddingFIFOQueue(32, [dtypes_lib.float32],
[tensor_shape.TensorShape(None)])
| PaddingFIFOQueueTest |
python | scikit-learn__scikit-learn | sklearn/linear_model/_ridge.py | {
"start": 91647,
"end": 99442
} | class ____(MultiOutputMixin, RegressorMixin, _BaseRidgeCV):
"""Ridge regression with built-in cross-validation.
See glossary entry for :term:`cross-validation estimator`.
By default, it performs efficient Leave-One-Out Cross-Validation.
Read more in the :ref:`User Guide <ridge_regression>`.
Parameters
----------
alphas : array-like of shape (n_alphas,), default=(0.1, 1.0, 10.0)
Array of alpha values to try.
Regularization strength; must be a positive float. Regularization
improves the conditioning of the problem and reduces the variance of
the estimates. Larger values specify stronger regularization.
Alpha corresponds to ``1 / (2C)`` in other linear models such as
:class:`~sklearn.linear_model.LogisticRegression` or
:class:`~sklearn.svm.LinearSVC`.
If using Leave-One-Out cross-validation, alphas must be strictly positive.
fit_intercept : bool, default=True
Whether to calculate the intercept for this model. If set
to false, no intercept will be used in calculations
(i.e. data is expected to be centered).
scoring : str, callable, default=None
The scoring method to use for cross-validation. Options:
- str: see :ref:`scoring_string_names` for options.
- callable: a scorer callable object (e.g., function) with signature
``scorer(estimator, X, y)``. See :ref:`scoring_callable` for details.
- `None`: negative :ref:`mean squared error <mean_squared_error>` if cv is
None (i.e. when using leave-one-out cross-validation), or
:ref:`coefficient of determination <r2_score>` (:math:`R^2`) otherwise.
cv : int, cross-validation generator or an iterable, default=None
Determines the cross-validation splitting strategy.
Possible inputs for cv are:
- None, to use the efficient Leave-One-Out cross-validation
- integer, to specify the number of folds.
- :term:`CV splitter`,
- An iterable yielding (train, test) splits as arrays of indices.
For integer/None inputs, if ``y`` is binary or multiclass,
:class:`~sklearn.model_selection.StratifiedKFold` is used, else,
:class:`~sklearn.model_selection.KFold` is used.
Refer :ref:`User Guide <cross_validation>` for the various
cross-validation strategies that can be used here.
gcv_mode : {'auto', 'svd', 'eigen'}, default='auto'
Flag indicating which strategy to use when performing
Leave-One-Out Cross-Validation. Options are::
'auto' : use 'svd' if n_samples > n_features, otherwise use 'eigen'
'svd' : force use of singular value decomposition of X when X is
dense, eigenvalue decomposition of X^T.X when X is sparse.
'eigen' : force computation via eigendecomposition of X.X^T
The 'auto' mode is the default and is intended to pick the cheaper
option of the two depending on the shape of the training data.
store_cv_results : bool, default=False
Flag indicating if the cross-validation values corresponding to
each alpha should be stored in the ``cv_results_`` attribute (see
below). This flag is only compatible with ``cv=None`` (i.e. using
Leave-One-Out Cross-Validation).
.. versionchanged:: 1.5
Parameter name changed from `store_cv_values` to `store_cv_results`.
alpha_per_target : bool, default=False
Flag indicating whether to optimize the alpha value (picked from the
`alphas` parameter list) for each target separately (for multi-output
settings: multiple prediction targets). When set to `True`, after
fitting, the `alpha_` attribute will contain a value for each target.
When set to `False`, a single alpha is used for all targets.
.. versionadded:: 0.24
Attributes
----------
cv_results_ : ndarray of shape (n_samples, n_alphas) or \
shape (n_samples, n_targets, n_alphas), optional
Cross-validation values for each alpha (only available if
``store_cv_results=True`` and ``cv=None``). After ``fit()`` has been
called, this attribute will contain the mean squared errors if
`scoring is None` otherwise it will contain standardized per point
prediction values.
.. versionchanged:: 1.5
`cv_values_` changed to `cv_results_`.
coef_ : ndarray of shape (n_features) or (n_targets, n_features)
Weight vector(s).
intercept_ : float or ndarray of shape (n_targets,)
Independent term in decision function. Set to 0.0 if
``fit_intercept = False``.
alpha_ : float or ndarray of shape (n_targets,)
Estimated regularization parameter, or, if ``alpha_per_target=True``,
the estimated regularization parameter for each target.
best_score_ : float or ndarray of shape (n_targets,)
Score of base estimator with best alpha, or, if
``alpha_per_target=True``, a score for each target.
.. versionadded:: 0.23
n_features_in_ : int
Number of features seen during :term:`fit`.
.. versionadded:: 0.24
feature_names_in_ : ndarray of shape (`n_features_in_`,)
Names of features seen during :term:`fit`. Defined only when `X`
has feature names that are all strings.
.. versionadded:: 1.0
See Also
--------
Ridge : Ridge regression.
RidgeClassifier : Classifier based on ridge regression on {-1, 1} labels.
RidgeClassifierCV : Ridge classifier with built-in cross validation.
Examples
--------
>>> from sklearn.datasets import load_diabetes
>>> from sklearn.linear_model import RidgeCV
>>> X, y = load_diabetes(return_X_y=True)
>>> clf = RidgeCV(alphas=[1e-3, 1e-2, 1e-1, 1]).fit(X, y)
>>> clf.score(X, y)
0.5166...
"""
@_fit_context(prefer_skip_nested_validation=True)
def fit(self, X, y, sample_weight=None, **params):
"""Fit Ridge regression model with cv.
Parameters
----------
X : ndarray of shape (n_samples, n_features)
Training data. If using GCV, will be cast to float64
if necessary.
y : ndarray of shape (n_samples,) or (n_samples, n_targets)
Target values. Will be cast to X's dtype if necessary.
sample_weight : float or ndarray of shape (n_samples,), default=None
Individual weights for each sample. If given a float, every sample
will have the same weight.
**params : dict, default=None
Parameters to be passed to the underlying scorer.
.. versionadded:: 1.5
Only available if `enable_metadata_routing=True`,
which can be set by using
``sklearn.set_config(enable_metadata_routing=True)``.
See :ref:`Metadata Routing User Guide <metadata_routing>` for
more details.
Returns
-------
self : object
Fitted estimator.
Notes
-----
When sample_weight is provided, the selected hyperparameter may depend
on whether we use leave-one-out cross-validation (cv=None)
or another form of cross-validation, because only leave-one-out
cross-validation takes the sample weights into account when computing
the validation score.
"""
super().fit(X, y, sample_weight=sample_weight, **params)
return self
def _get_scorer_instance(self):
"""Return a scorer which corresponds to what's defined in RegressorMixin
parent class. This is used for routing `sample_weight`.
"""
return get_scorer("r2")
| RidgeCV |
python | coleifer__peewee | tests/queries.py | {
"start": 5574,
"end": 7472
} | class ____(BaseTestCase):
def test_clone_tables(self):
self._do_test_clone(User, Tweet)
def test_clone_models(self):
class User(TestModel):
username = TextField()
class Meta:
table_name = 'users'
class Tweet(TestModel):
user = ForeignKeyField(User, backref='tweets')
content = TextField()
self._do_test_clone(User, Tweet)
def _do_test_clone(self, User, Tweet):
query = Tweet.select(Tweet.id)
base_sql = 'SELECT "t1"."id" FROM "tweet" AS "t1"'
self.assertSQL(query, base_sql, [])
qj = query.join(User, on=(Tweet.user_id == User.id))
self.assertSQL(query, base_sql, [])
self.assertSQL(qj, (
'SELECT "t1"."id" FROM "tweet" AS "t1" '
'INNER JOIN "users" AS "t2" ON ("t1"."user_id" = "t2"."id")'), [])
qw = query.where(Tweet.id > 3)
self.assertSQL(query, base_sql, [])
self.assertSQL(qw, base_sql + ' WHERE ("t1"."id" > ?)', [3])
qw2 = qw.where(Tweet.id < 6)
self.assertSQL(query, base_sql, [])
self.assertSQL(qw, base_sql + ' WHERE ("t1"."id" > ?)', [3])
self.assertSQL(qw2, base_sql + (' WHERE (("t1"."id" > ?) '
'AND ("t1"."id" < ?))'), [3, 6])
qo = query.order_by(Tweet.id)
self.assertSQL(query, base_sql, [])
self.assertSQL(qo, base_sql + ' ORDER BY "t1"."id"', [])
qo2 = qo.order_by(Tweet.content, Tweet.id)
self.assertSQL(query, base_sql, [])
self.assertSQL(qo, base_sql + ' ORDER BY "t1"."id"', [])
self.assertSQL(qo2,
base_sql + ' ORDER BY "t1"."content", "t1"."id"', [])
qg = query.group_by(Tweet.id)
self.assertSQL(query, base_sql, [])
self.assertSQL(qg, base_sql + ' GROUP BY "t1"."id"', [])
| TestQueryCloning |
python | ray-project__ray | python/ray/llm/_internal/common/utils/cloud_filesystem/pyarrow_filesystem.py | {
"start": 563,
"end": 14600
} | class ____(BaseCloudFileSystem):
"""PyArrow-based implementation of cloud filesystem operations.
This class provides a unified interface for cloud storage operations using
PyArrow's filesystem abstraction. It supports S3, GCS, and Azure storage
providers.
"""
@staticmethod
def get_fs_and_path(object_uri: str) -> Tuple[pa_fs.FileSystem, str]:
"""Get the appropriate filesystem and path from a URI.
Args:
object_uri: URI of the file (s3://, gs://, abfss://, or azure://)
If URI contains 'anonymous@', anonymous access is used.
Example: s3://anonymous@bucket/path
Returns:
Tuple of (filesystem, path)
"""
if object_uri.startswith("pyarrow-"):
object_uri = object_uri[8:]
anonymous = False
# Check for anonymous access pattern (only for S3/GCS)
# e.g. s3://anonymous@bucket/path
if "@" in object_uri and not (
object_uri.startswith("abfss://") or object_uri.startswith("azure://")
):
parts = object_uri.split("@", 1)
# Check if the first part ends with "anonymous"
if parts[0].endswith("anonymous"):
anonymous = True
# Remove the anonymous@ part, keeping the scheme
scheme = parts[0].split("://")[0]
object_uri = f"{scheme}://{parts[1]}"
if object_uri.startswith("s3://"):
endpoint = os.getenv("AWS_ENDPOINT_URL_S3", None)
virtual_hosted_style = os.getenv("AWS_S3_ADDRESSING_STYLE", None)
fs = pa_fs.S3FileSystem(
anonymous=anonymous,
endpoint_override=endpoint,
force_virtual_addressing=(virtual_hosted_style == "virtual"),
)
path = object_uri[5:] # Remove "s3://"
elif object_uri.startswith("gs://"):
fs = pa_fs.GcsFileSystem(anonymous=anonymous)
path = object_uri[5:] # Remove "gs://"
elif object_uri.startswith("abfss://"):
fs, path = PyArrowFileSystem._create_abfss_filesystem(object_uri)
elif object_uri.startswith("azure://"):
fs, path = PyArrowFileSystem._create_azure_filesystem(object_uri)
else:
raise ValueError(f"Unsupported URI scheme: {object_uri}")
return fs, path
@staticmethod
def _create_azure_filesystem(object_uri: str) -> Tuple[pa_fs.FileSystem, str]:
"""Create an Azure filesystem for Azure Blob Storage or ABFSS.
Args:
object_uri: Azure URI (azure://container@account.blob.core.windows.net/path or
abfss://container@account.dfs.core.windows.net/path)
Returns:
Tuple of (PyArrow FileSystem, path without scheme prefix)
Raises:
ImportError: If required dependencies are not installed.
ValueError: If the Azure URI format is invalid.
"""
try:
import adlfs
from azure.identity import DefaultAzureCredential
except ImportError:
raise ImportError(
"You must `pip install adlfs azure-identity` "
"to use Azure/ABFSS URIs. "
"Note that these must be preinstalled on all nodes in the Ray cluster."
)
# Parse and validate the Azure URI
parsed = urlparse(object_uri)
scheme = parsed.scheme.lower()
# Validate URI format: scheme://container@account.domain/path
if not parsed.netloc or "@" not in parsed.netloc:
raise ValueError(
f"Invalid {scheme.upper()} URI format - missing container@account: {object_uri}"
)
container_part, hostname_part = parsed.netloc.split("@", 1)
# Validate container name (must be non-empty)
if not container_part:
raise ValueError(
f"Invalid {scheme.upper()} URI format - empty container name: {object_uri}"
)
# Validate hostname format based on scheme
valid_hostname = False
if scheme == "abfss":
valid_hostname = hostname_part.endswith(".dfs.core.windows.net")
expected_domains = ".dfs.core.windows.net"
elif scheme == "azure":
valid_hostname = hostname_part.endswith(
".blob.core.windows.net"
) or hostname_part.endswith(".dfs.core.windows.net")
expected_domains = ".blob.core.windows.net or .dfs.core.windows.net"
if not hostname_part or not valid_hostname:
raise ValueError(
f"Invalid {scheme.upper()} URI format - invalid hostname (must end with {expected_domains}): {object_uri}"
)
# Extract and validate account name
azure_storage_account_name = hostname_part.split(".")[0]
if not azure_storage_account_name:
raise ValueError(
f"Invalid {scheme.upper()} URI format - empty account name: {object_uri}"
)
# Create the adlfs filesystem
adlfs_fs = adlfs.AzureBlobFileSystem(
account_name=azure_storage_account_name,
credential=DefaultAzureCredential(),
)
# Wrap with PyArrow's PyFileSystem for compatibility
fs = pa_fs.PyFileSystem(pa_fs.FSSpecHandler(adlfs_fs))
# Return the path without the scheme prefix
path = f"{container_part}{parsed.path}"
return fs, path
@staticmethod
def _create_abfss_filesystem(object_uri: str) -> Tuple[pa_fs.FileSystem, str]:
"""Create an ABFSS filesystem for Azure Data Lake Storage Gen2.
This is a wrapper around _create_azure_filesystem for backward compatibility.
Args:
object_uri: ABFSS URI (abfss://container@account.dfs.core.windows.net/path)
Returns:
Tuple of (PyArrow FileSystem, path without abfss:// prefix)
"""
return PyArrowFileSystem._create_azure_filesystem(object_uri)
@staticmethod
def _filter_files(
fs: pa_fs.FileSystem,
source_path: str,
destination_path: str,
substrings_to_include: Optional[List[str]] = None,
suffixes_to_exclude: Optional[List[str]] = None,
) -> List[Tuple[str, str]]:
"""Filter files from cloud storage based on inclusion and exclusion criteria.
Args:
fs: PyArrow filesystem instance
source_path: Source path in cloud storage
destination_path: Local destination path
substrings_to_include: Only include files containing these substrings
suffixes_to_exclude: Exclude files ending with these suffixes
Returns:
List of tuples containing (source_file_path, destination_file_path)
"""
file_selector = pa_fs.FileSelector(source_path, recursive=True)
file_infos = fs.get_file_info(file_selector)
path_pairs = []
for file_info in file_infos:
if file_info.type != pa_fs.FileType.File:
continue
rel_path = file_info.path[len(source_path) :].lstrip("/")
# Apply filters
if substrings_to_include:
if not any(
substring in rel_path for substring in substrings_to_include
):
continue
if suffixes_to_exclude:
if any(rel_path.endswith(suffix) for suffix in suffixes_to_exclude):
continue
path_pairs.append(
(file_info.path, os.path.join(destination_path, rel_path))
)
return path_pairs
@staticmethod
def get_file(
object_uri: str, decode_as_utf_8: bool = True
) -> Optional[Union[str, bytes]]:
"""Download a file from cloud storage into memory.
Args:
object_uri: URI of the file (s3://, gs://, abfss://, or azure://)
decode_as_utf_8: If True, decode the file as UTF-8
Returns:
File contents as string or bytes, or None if file doesn't exist
"""
try:
fs, path = PyArrowFileSystem.get_fs_and_path(object_uri)
# Check if file exists
if not fs.get_file_info(path).type == pa_fs.FileType.File:
logger.info(f"URI {object_uri} does not exist.")
return None
# Read file
with fs.open_input_file(path) as f:
body = f.read()
if decode_as_utf_8:
body = body.decode("utf-8")
return body
except Exception as e:
logger.warning(f"Error reading {object_uri}: {e}")
return None
@staticmethod
def list_subfolders(folder_uri: str) -> List[str]:
"""List the immediate subfolders in a cloud directory.
Args:
folder_uri: URI of the directory (s3://, gs://, abfss://, or azure://)
Returns:
List of subfolder names (without trailing slashes)
"""
# Ensure that the folder_uri has a trailing slash.
folder_uri = f"{folder_uri.rstrip('/')}/"
try:
fs, path = PyArrowFileSystem.get_fs_and_path(folder_uri)
# List directory contents
file_infos = fs.get_file_info(pa_fs.FileSelector(path, recursive=False))
# Filter for directories and extract subfolder names
subfolders = []
for file_info in file_infos:
if file_info.type == pa_fs.FileType.Directory:
# Extract just the subfolder name without the full path
subfolder = os.path.basename(file_info.path.rstrip("/"))
subfolders.append(subfolder)
return subfolders
except Exception as e:
logger.error(f"Error listing subfolders in {folder_uri}: {e}")
return []
@staticmethod
def download_files(
path: str,
bucket_uri: str,
substrings_to_include: Optional[List[str]] = None,
suffixes_to_exclude: Optional[List[str]] = None,
max_concurrency: int = 10,
chunk_size: int = 64 * 1024 * 1024,
) -> None:
"""Download files from cloud storage to a local directory.
Args:
path: Local directory where files will be downloaded
bucket_uri: URI of cloud directory
substrings_to_include: Only include files containing these substrings
suffixes_to_exclude: Exclude certain files from download
max_concurrency: Maximum number of concurrent files to download (default: 10)
chunk_size: Size of transfer chunks (default: 64MB)
"""
try:
fs, source_path = PyArrowFileSystem.get_fs_and_path(bucket_uri)
# Ensure destination exists
os.makedirs(path, exist_ok=True)
# If no filters, use direct copy_files
if not substrings_to_include and not suffixes_to_exclude:
pa_fs.copy_files(
source=source_path,
destination=path,
source_filesystem=fs,
destination_filesystem=pa_fs.LocalFileSystem(),
use_threads=True,
chunk_size=chunk_size,
)
return
# List and filter files
files_to_download = PyArrowFileSystem._filter_files(
fs, source_path, path, substrings_to_include, suffixes_to_exclude
)
if not files_to_download:
logger.info("Filters do not match any of the files, skipping download")
return
def download_single_file(file_paths):
source_file_path, dest_file_path = file_paths
# Create destination directory if needed
dest_dir = os.path.dirname(dest_file_path)
if dest_dir:
os.makedirs(dest_dir, exist_ok=True)
# Use PyArrow's copy_files for individual files,
pa_fs.copy_files(
source=source_file_path,
destination=dest_file_path,
source_filesystem=fs,
destination_filesystem=pa_fs.LocalFileSystem(),
use_threads=True,
chunk_size=chunk_size,
)
return dest_file_path
max_workers = min(max_concurrency, len(files_to_download))
with ThreadPoolExecutor(max_workers=max_workers) as executor:
futures = [
executor.submit(download_single_file, file_paths)
for file_paths in files_to_download
]
for future in futures:
try:
future.result()
except Exception as e:
logger.error(f"Failed to download file: {e}")
raise
except Exception as e:
logger.exception(f"Error downloading files from {bucket_uri}: {e}")
raise
@staticmethod
def upload_files(
local_path: str,
bucket_uri: str,
) -> None:
"""Upload files to cloud storage.
Args:
local_path: The local path of the files to upload.
bucket_uri: The bucket uri to upload the files to, must start with
`s3://`, `gs://`, `abfss://`, or `azure://`.
"""
try:
fs, dest_path = PyArrowFileSystem.get_fs_and_path(bucket_uri)
pa_fs.copy_files(
source=local_path,
destination=dest_path,
source_filesystem=pa_fs.LocalFileSystem(),
destination_filesystem=fs,
)
except Exception as e:
logger.exception(f"Error uploading files to {bucket_uri}: {e}")
raise
| PyArrowFileSystem |
python | lazyprogrammer__machine_learning_examples | unsupervised_class2/rbm_tf.py | {
"start": 467,
"end": 4912
} | class ____(object):
def __init__(self, D, M, an_id):
self.D = D
self.M = M
self.id = an_id
self.build(D, M)
def set_session(self, session):
self.session = session
def build(self, D, M):
# params
self.W = tf.Variable(tf.random.normal(shape=(D, M)) * np.sqrt(2.0 / M))
# note: without limiting variance, you get numerical stability issues
self.c = tf.Variable(np.zeros(M).astype(np.float32))
self.b = tf.Variable(np.zeros(D).astype(np.float32))
# data
self.X_in = tf.compat.v1.placeholder(tf.float32, shape=(None, D))
# conditional probabilities
# NOTE: tf.contrib.distributions.Bernoulli API has changed in Tensorflow v1.2
V = self.X_in
p_h_given_v = tf.nn.sigmoid(tf.matmul(V, self.W) + self.c)
self.p_h_given_v = p_h_given_v # save for later
# self.rng_h_given_v = tf.contrib.distributions.Bernoulli(
# probs=p_h_given_v,
# dtype=tf.float32
# )
r = tf.random.uniform(shape=tf.shape(input=p_h_given_v))
H = tf.cast(r < p_h_given_v, dtype=tf.float32)
p_v_given_h = tf.nn.sigmoid(tf.matmul(H, tf.transpose(a=self.W)) + self.b)
# self.rng_v_given_h = tf.contrib.distributions.Bernoulli(
# probs=p_v_given_h,
# dtype=tf.float32
# )
r = tf.random.uniform(shape=tf.shape(input=p_v_given_h))
X_sample = tf.cast(r < p_v_given_h, dtype=tf.float32)
# build the objective
objective = tf.reduce_mean(input_tensor=self.free_energy(self.X_in)) - tf.reduce_mean(input_tensor=self.free_energy(X_sample))
self.train_op = tf.compat.v1.train.AdamOptimizer(1e-2).minimize(objective)
# self.train_op = tf.train.GradientDescentOptimizer(1e-3).minimize(objective)
# build the cost
# we won't use this to optimize the model parameters
# just to observe what happens during training
logits = self.forward_logits(self.X_in)
self.cost = tf.reduce_mean(
input_tensor=tf.nn.sigmoid_cross_entropy_with_logits(
labels=self.X_in,
logits=logits,
)
)
def fit(self, X, epochs=1, batch_sz=100, show_fig=False):
N, D = X.shape
n_batches = N // batch_sz
costs = []
print("training rbm: %s" % self.id)
for i in range(epochs):
print("epoch:", i)
X = shuffle(X)
for j in range(n_batches):
batch = X[j*batch_sz:(j*batch_sz + batch_sz)]
_, c = self.session.run((self.train_op, self.cost), feed_dict={self.X_in: batch})
if j % 10 == 0:
print("j / n_batches:", j, "/", n_batches, "cost:", c)
costs.append(c)
if show_fig:
plt.plot(costs)
plt.show()
def free_energy(self, V):
b = tf.reshape(self.b, (self.D, 1))
first_term = -tf.matmul(V, b)
first_term = tf.reshape(first_term, (-1,))
second_term = -tf.reduce_sum(
# tf.log(1 + tf.exp(tf.matmul(V, self.W) + self.c)),
input_tensor=tf.nn.softplus(tf.matmul(V, self.W) + self.c),
axis=1
)
return first_term + second_term
def forward_hidden(self, X):
return tf.nn.sigmoid(tf.matmul(X, self.W) + self.c)
def forward_logits(self, X):
Z = self.forward_hidden(X)
return tf.matmul(Z, tf.transpose(a=self.W)) + self.b
def forward_output(self, X):
return tf.nn.sigmoid(self.forward_logits(X))
def transform(self, X):
# accepts and returns a real numpy array
# unlike forward_hidden and forward_output
# which deal with tensorflow variables
return self.session.run(self.p_h_given_v, feed_dict={self.X_in: X})
def main():
Xtrain, Ytrain, Xtest, Ytest = getKaggleMNIST()
# same as autoencoder_tf.py
Xtrain = Xtrain.astype(np.float32)
Xtest = Xtest.astype(np.float32)
_, D = Xtrain.shape
K = len(set(Ytrain))
dnn = DNN(D, [1000, 750, 500], K, UnsupervisedModel=RBM)
init_op = tf.compat.v1.global_variables_initializer()
with tf.compat.v1.Session() as session:
session.run(init_op)
dnn.set_session(session)
dnn.fit(Xtrain, Ytrain, Xtest, Ytest, pretrain=True, epochs=10)
if __name__ == '__main__':
main() | RBM |
python | plotly__plotly.py | tests/test_core/test_graph_objs/test_figure_properties.py | {
"start": 102,
"end": 9891
} | class ____(TestCase):
def setUp(self):
# Disable default template
pio.templates.default = None
# Construct initial scatter object
self.figure = go.Figure(
data=[go.Scatter(y=[3, 2, 1], marker={"color": "green"})],
layout={"xaxis": {"range": [-1, 4]}},
frames=[go.Frame(layout={"yaxis": {"title": "f1"}})],
)
def tearDown(self):
# Reenable default template
pio.templates.default = "plotly"
def test_attr_access(self):
scatt_uid = self.figure.data[0].uid
self.assertEqual(
self.figure.data,
(go.Scatter(y=[3, 2, 1], marker={"color": "green"}, uid=scatt_uid),),
)
self.assertEqual(self.figure.layout, go.Layout(xaxis={"range": [-1, 4]}))
self.assertEqual(
self.figure.frames, (go.Frame(layout={"yaxis": {"title": "f1"}}),)
)
def test_contains(self):
self.assertIn("data", self.figure)
self.assertIn("layout", self.figure)
self.assertIn("frames", self.figure)
def test_iter(self):
self.assertEqual(set(self.figure), {"data", "layout", "frames"})
def test_attr_item(self):
# test that equal objects can be retrieved using attr or item
# syntax
self.assertEqual(self.figure.data, self.figure["data"])
self.assertEqual(self.figure.layout, self.figure["layout"])
self.assertEqual(self.figure.frames, self.figure["frames"])
def test_property_assignment_tuple(self):
# Empty
self.assertIs(self.figure[()], self.figure)
# Layout
self.figure[("layout", "xaxis", "range")] = (-10, 10)
self.assertEqual(self.figure[("layout", "xaxis", "range")], (-10, 10))
# Data
self.figure[("data", 0, "marker", "color")] = "red"
self.assertEqual(self.figure[("data", 0, "marker", "color")], "red")
# Frames
self.figure[("frames", 0, "layout", "yaxis", "title", "text")] = "f2"
self.assertEqual(
self.figure[("frames", 0, "layout", "yaxis", "title", "text")], "f2"
)
def test_property_assignment_dots(self):
# Layout
self.figure["layout.xaxis.range"] = (-10, 10)
self.assertEqual(self.figure["layout.xaxis.range"], (-10, 10))
# Data
self.figure["data.0.marker.color"] = "red"
self.assertEqual(self.figure["data[0].marker.color"], "red")
# Frames
self.figure["frames[0].layout.yaxis.title.text"] = "f2"
self.assertEqual(self.figure["frames.0.layout.yaxis.title.text"], "f2")
def test_access_invalid_attr(self):
with pytest.raises(AttributeError):
self.figure.bogus
def test_access_invalid_item(self):
with pytest.raises(KeyError):
self.figure["bogus"]
def test_assign_invalid_attr(self):
with pytest.raises(AttributeError):
self.figure.bogus = "val"
def test_assign_invalid_item(self):
with pytest.raises(KeyError):
self.figure["bogus"] = "val"
# Update
def test_update_layout(self):
# Check initial x-range
self.assertEqual(self.figure.layout.xaxis.range, (-1, 4))
# Update with kwarg
self.figure.update(layout={"xaxis": {"range": [10, 20]}})
self.assertEqual(self.figure.layout.xaxis.range, (10, 20))
# Update with dict
self.figure.update({"layout": {"xaxis": {"range": [100, 200]}}})
self.assertEqual(self.figure.layout.xaxis.range, (100, 200))
def test_update_data(self):
# Check initial marker color
self.assertEqual(self.figure.data[0].marker.color, "green")
# Update with dict kwarg
self.figure.update(data={0: {"marker": {"color": "blue"}}})
self.assertEqual(self.figure.data[0].marker.color, "blue")
# Update with list kwarg
self.figure.update(data=[{"marker": {"color": "red"}}])
self.assertEqual(self.figure.data[0].marker.color, "red")
# Update with dict
self.figure.update({"data": {0: {"marker": {"color": "yellow"}}}})
self.assertEqual(self.figure.data[0].marker.color, "yellow")
def test_update_data_dots(self):
# Check initial marker color
self.assertEqual(self.figure.data[0].marker.color, "green")
# Update with dict kwarg
self.figure.update(data={0: {"marker.color": "blue"}})
self.assertEqual(self.figure.data[0].marker.color, "blue")
# Update with list kwarg
self.figure.update(data=[{"marker.color": "red"}])
self.assertEqual(self.figure.data[0].marker.color, "red")
# Update with dict
self.figure.update({"data[0].marker.color": "yellow"})
self.assertEqual(self.figure.data[0].marker.color, "yellow")
def test_update_data_underscores(self):
# Check initial marker color
self.assertEqual(self.figure.data[0].marker.color, "green")
# Update with dict kwarg
self.figure.update(data={0: {"marker_color": "blue"}})
self.assertEqual(self.figure.data[0].marker.color, "blue")
# Update with list kwarg
self.figure.update(data=[{"marker_color": "red"}])
self.assertEqual(self.figure.data[0].marker.color, "red")
# Update with dict
self.figure.update({"data_0_marker_color": "yellow"})
self.assertEqual(self.figure.data[0].marker.color, "yellow")
# Update with kwarg
self.figure.update(data_0_marker_color="yellow")
self.assertEqual(self.figure.data[0].marker.color, "yellow")
def test_update_data_empty(self):
# Create figure with empty data (no traces)
figure = go.Figure(layout={"width": 1000})
# Update data with new traces
figure.update(data=[go.Scatter(y=[2, 1, 3]), go.Bar(y=[1, 2, 3])])
# Build expected dict
expected = {
"data": [
{"y": [2, 1, 3], "type": "scatter"},
{"y": [1, 2, 3], "type": "bar"},
],
"layout": {"width": 1000},
}
# Compute expected figure dict (pop uids for comparison)
result = figure.to_dict()
# Perform comparison
self.assertEqual(result, expected)
def test_update_frames(self):
# Check initial frame axis title
self.assertEqual(self.figure.frames[0].layout.yaxis.title.text, "f1")
# Update with dict kwarg
self.figure.update(frames={0: {"layout": {"yaxis": {"title": {"text": "f2"}}}}})
self.assertEqual(self.figure.frames[0].layout.yaxis.title.text, "f2")
# Update with list kwarg
self.figure.update(frames=[{"layout": {"yaxis": {"title": {"text": "f3"}}}}])
self.assertEqual(self.figure.frames[0].layout.yaxis.title.text, "f3")
# Update with dict
self.figure.update(
{"frames": [{"layout": {"yaxis": {"title": {"text": "f4"}}}}]}
)
self.assertEqual(self.figure.frames[0].layout.yaxis.title.text, "f4")
def test_update_invalid_attr(self):
with pytest.raises(ValueError):
self.figure.layout.update({"xaxis": {"bogus": 32}})
# plotly_restyle
def test_plotly_restyle(self):
# Check initial marker color
self.assertEqual(self.figure.data[0].marker.color, "green")
# Update with dict kwarg
self.figure.plotly_restyle(
restyle_data={"marker.color": "blue"}, trace_indexes=0
)
self.assertEqual(self.figure.data[0].marker.color, "blue")
def test_restyle_validate_property(self):
with pytest.raises(ValueError):
self.figure.plotly_restyle({"bogus": 3}, trace_indexes=[0])
def test_restyle_validate_property_nested(self):
with pytest.raises(ValueError):
self.figure.plotly_restyle({"marker.bogus": 3}, trace_indexes=[0])
# plotly_relayout
def test_plotly_relayout(self):
# Check initial x-range
self.assertEqual(self.figure.layout.xaxis.range, (-1, 4))
# Update with kwarg
self.figure.plotly_relayout(relayout_data={"xaxis.range": [10, 20]})
self.assertEqual(self.figure.layout.xaxis.range, (10, 20))
def test_relayout_validate_property(self):
with pytest.raises(ValueError):
self.figure.plotly_relayout({"bogus": [1, 3]})
def test_relayout_validate_property_nested(self):
with pytest.raises(ValueError):
self.figure.plotly_relayout({"xaxis.bogus": [1, 3]})
def test_relayout_validate_unintialized_subplot(self):
with pytest.raises(ValueError):
self.figure.plotly_relayout({"xaxis2.range": [1, 3]})
# plotly_update
def test_plotly_update_layout(self):
# Check initial x-range
self.assertEqual(self.figure.layout.xaxis.range, (-1, 4))
# Update with kwarg
self.figure.plotly_update(relayout_data={"xaxis.range": [10, 20]})
self.assertEqual(self.figure.layout.xaxis.range, (10, 20))
def test_plotly_update_data(self):
# Check initial marker color
self.assertEqual(self.figure.data[0].marker.color, "green")
# Update with dict kwarg
self.figure.plotly_update(
restyle_data={"marker.color": "blue"}, trace_indexes=0
)
self.assertEqual(self.figure.data[0].marker.color, "blue")
def test_plotly_update_validate_property_trace(self):
with pytest.raises(ValueError):
self.figure.plotly_update(restyle_data={"bogus": 3}, trace_indexes=[0])
def test_plotly_update_validate_property_layout(self):
with pytest.raises(ValueError):
self.figure.plotly_update(relayout_data={"xaxis.bogus": [1, 3]})
| TestFigureProperties |
python | arrow-py__arrow | tests/test_locales.py | {
"start": 1799,
"end": 3245
} | class ____:
def test_get_locale(self, mocker):
mock_locale = mocker.Mock()
mock_locale_cls = mocker.Mock()
mock_locale_cls.return_value = mock_locale
with pytest.raises(ValueError):
arrow.locales.get_locale("locale-name")
cls_dict = arrow.locales._locale_map
mocker.patch.dict(cls_dict, {"locale-name": mock_locale_cls})
result = arrow.locales.get_locale("locale_name")
assert result == mock_locale
# Capitalization and hyphenation should still yield the same locale
result = arrow.locales.get_locale("locale-name")
assert result == mock_locale
result = arrow.locales.get_locale("locale-NAME")
assert result == mock_locale
def test_get_locale_by_class_name(self, mocker):
mock_locale_cls = mocker.Mock()
mock_locale_obj = mock_locale_cls.return_value = mocker.Mock()
globals_fn = mocker.Mock()
globals_fn.return_value = {"NonExistentLocale": mock_locale_cls}
with pytest.raises(ValueError):
arrow.locales.get_locale_by_class_name("NonExistentLocale")
mocker.patch.object(locales, "globals", globals_fn)
result = arrow.locales.get_locale_by_class_name("NonExistentLocale")
mock_locale_cls.assert_called_once_with()
assert result == mock_locale_obj
def test_locales(self):
assert len(locales._locale_map) > 0
| TestModule |
python | numba__numba | numba/core/typing/npydecl.py | {
"start": 25027,
"end": 25669
} | class ____(AbstractTemplate):
def generic(self, args, kws):
assert not kws
# Either ndindex(shape) or ndindex(*shape)
if len(args) == 1 and isinstance(args[0], types.BaseTuple):
tup = args[0]
if tup.count > 0 and not isinstance(tup, types.UniTuple):
# Heterogeneous tuple
return
shape = list(tup)
else:
shape = args
if all(isinstance(x, types.Integer) for x in shape):
iterator_type = types.NumpyNdIndexType(len(shape))
return signature(iterator_type, *args)
@infer_global(operator.eq)
| NdIndex |
python | PyCQA__pylint | tests/functional/e/enum_self_defined_member_6805.py | {
"start": 582,
"end": 898
} | class ____(IntEnum):
MONDAY = (1, "Mon")
TUESDAY = (2, "Tue")
WEDNESDAY = (3, "Wed")
THURSDAY = (4, "Thu")
FRIDAY = (5, "Fri")
SATURDAY = (6, "Sat")
SUNDAY = (7, "Sun")
def __new__(cls, value, _abbr=None):
return int.__new__(cls, value)
print(Day.FRIDAY.foo) # [no-member]
| Day |
python | getsentry__sentry | src/sentry/conf/types/sdk_config.py | {
"start": 1255,
"end": 1402
} | class ____(SdkConfig):
# these get popped before sending along to the sdk
dsn: NotRequired[str]
relay_dsn: NotRequired[str]
| ServerSdkConfig |
python | pytorch__pytorch | test/distributed/tensor/test_op_strategy.py | {
"start": 19402,
"end": 23886
} | class ____(DTensorTestBase):
@with_comms
@patch(
"torch.distributed.tensor._sharding_prop.ShardingPropagator._select_strategy"
)
def test_replicate_strategy_placement(self, mock_select_strategy):
costs_from__select_strategy = []
def mock_select_func(strategy, op_schema=None):
"""function copied from _select_strategy but with cost capturing"""
nonlocal costs_from__select_strategy
if len(strategy.strategies) == 1:
costs_from__select_strategy = strategy.strategies[0].redistribute_cost
return strategy.strategies[0]
op_spec_costs: list[float] = []
for op_spec in strategy.strategies:
assert op_spec.redistribute_cost is not None, (
"must set redistribute cost each OpSpec!"
)
costs_from__select_strategy.append(op_spec.redistribute_cost)
redistribute_cost = sum(chain.from_iterable(op_spec.redistribute_cost))
op_spec_costs.append(redistribute_cost)
return strategy.strategies[op_spec_costs.index(min(op_spec_costs))]
mock_select_strategy.side_effect = mock_select_func
mesh = init_device_mesh(self.device_type, (2, self.world_size // 2))
comm_mode = CommDebugMode()
test_op = torch.ops.mylib.numpy_sin
input_x = torch.randn([8, 16, 32], device=self.device_type)
input_y = torch.randn([8, 16, 32], device=self.device_type)
output = test_op(input_x, input_y)
input_x_dt = distribute_tensor(input_x, mesh, [Shard(0), Shard(1)])
input_y_dt = distribute_tensor(input_y, mesh, [Shard(0), Shard(1)])
x_spec = DTensorSpec(mesh, input_x_dt.placements, extract_tensor_meta(input_x))
new_x_spec = DTensorSpec(
mesh, (Replicate(), Replicate()), extract_tensor_meta(input_x)
)
y_spec = DTensorSpec(mesh, input_y_dt.placements, extract_tensor_meta(input_y))
new_y_spec = DTensorSpec(
mesh, (Replicate(), Replicate()), extract_tensor_meta(input_y)
)
with comm_mode:
with op_strategy_context(test_op.default, replicate_op_strategy):
output_dt = test_op(input_x_dt, input_y_dt)
self.assertEqual(
comm_mode.get_comm_counts(),
{
torch.ops.c10d_functional.all_gather_into_tensor: self.world_size,
},
)
expected_cost = [
[redistribute_cost(x_spec, new_x_spec)],
[redistribute_cost(y_spec, new_y_spec)],
]
self.assertEqual(expected_cost, costs_from__select_strategy)
self.assertEqual(output_dt.full_tensor(), output)
self.assertEqual(output_dt.placements, [Replicate(), Replicate()])
self.assertTrue(
detect_exists_identical_opspec(
input_x,
input_y,
op=test_op.default,
mesh=mesh,
strategy_function=replicate_op_strategy,
)
)
@with_comms
def test_tuple_replicate_strategy_placement(self):
mesh = init_device_mesh(self.device_type, (2, self.world_size // 2))
test_op = torch.ops.mylib.numpy_tuple_sin
with op_strategy_context(
test_op.default,
replicate_op_strategy,
schema_info=RuntimeSchemaInfo(needs_pytree=True),
):
input_x = torch.randn([8, 16, 8], device=self.device_type)
input_y = [
torch.randn([8, 16, 8], device=self.device_type) for _ in range(3)
]
input_z = torch.randn([8, 16, 8], device=self.device_type)
output = test_op(input_x, input_y, input_z)
input_x_dt = distribute_tensor(input_x, mesh, [Shard(0), Shard(1)])
input_y_dt = [
distribute_tensor(i, mesh, [Shard(1), Shard(1)]) for i in input_y
]
input_z_dt = distribute_tensor(input_z, mesh, [Shard(1), Shard(0)])
output_dt = test_op(input_x_dt, input_y_dt, input_z_dt)
self.assertEqual(output_dt.full_tensor(), output)
self.assertEqual(output_dt.placements, [Replicate(), Replicate()])
| DistTensorReplicateStrategyRegistrationTest |
python | spack__spack | lib/spack/spack/test/error_messages.py | {
"start": 803,
"end": 925
} | class ____(Package):
version("2.1")
version("2.0")
depends_on("x4@4.1")
""",
)
_pkgx3 = (
"x3",
"""\
| X2 |
python | getsentry__sentry | tests/sentry/issue_detection/test_file_io_on_main_thread_detector.py | {
"start": 1214,
"end": 7034
} | class ____(TestCase):
def setUp(self) -> None:
super().setUp()
self._settings = get_detection_settings()
def create_proguard(self, uuid: str) -> None:
with ZipFile(BytesIO(), "w") as f:
f.writestr(f"proguard/{uuid}.txt", PROGUARD_SOURCE)
create_files_from_dif_zip(f, project=self.project)
def find_problems(self, event: dict[str, Any]) -> list[PerformanceProblem]:
detector = FileIOMainThreadDetector(self._settings, event)
run_detector_on_data(detector, event)
return list(detector.stored_problems.values())
def test_respects_project_option(self) -> None:
project = self.create_project()
event = get_event("file-io-on-main-thread/file-io-on-main-thread")
event["project_id"] = project.id
settings = get_detection_settings(project.id)
detector = FileIOMainThreadDetector(settings, event)
assert detector.is_creation_allowed_for_project(project)
ProjectOption.objects.set_value(
project=project,
key="sentry:performance_issue_settings",
value={"file_io_on_main_thread_detection_enabled": False},
)
settings = get_detection_settings(project.id)
detector = FileIOMainThreadDetector(settings, event)
assert not detector.is_creation_allowed_for_project(project)
def test_detects_file_io_main_thread(self) -> None:
event = get_event("file-io-on-main-thread/file-io-on-main-thread")
assert self.find_problems(event) == [
PerformanceProblem(
fingerprint=f"1-{PerformanceFileIOMainThreadGroupType.type_id}-153198dd61706844cf3d9a922f6f82543df8125f",
op="file.write",
desc="1669031858711_file.txt (4.0 kB)",
type=PerformanceFileIOMainThreadGroupType,
parent_span_ids=["b93d2be92cd64fd5"],
cause_span_ids=[],
offender_span_ids=["054ba3a374d543eb"],
evidence_data={
"op": "file.write",
"parent_span_ids": ["b93d2be92cd64fd5"],
"cause_span_ids": [],
"offender_span_ids": ["054ba3a374d543eb"],
},
evidence_display=[],
)
]
def test_does_not_detect_file_io_main_thread(self) -> None:
event = get_event("file-io-on-main-thread/file-io-on-main-thread")
event["spans"][0]["data"]["blocked_main_thread"] = False
assert self.find_problems(event) == []
def test_ignores_nib_files(self) -> None:
event = get_event("file-io-on-main-thread/file-io-on-main-thread")
event["spans"][0]["data"]["file.path"] = "somethins/stuff.txt/blah/yup/ios.nib"
assert self.find_problems(event) == []
def test_ignores_keyboard_files(self) -> None:
event = get_event("file-io-on-main-thread/file-io-on-main-thread")
event["spans"][0]["data"]["file.path"] = "somethins/stuff/blah/yup/KBLayout_iPhone.dat"
assert self.find_problems(event) == []
def test_gives_problem_correct_title(self) -> None:
event = get_event("file-io-on-main-thread/file-io-on-main-thread")
event["spans"][0]["data"]["blocked_main_thread"] = True
problem = self.find_problems(event)[0]
assert problem.title == "File IO on Main Thread"
def test_duplicate_calls_do_not_change_callstack(self) -> None:
event = get_event("file-io-on-main-thread/file-io-on-main-thread")
event["spans"][0]["data"]["blocked_main_thread"] = True
single_span_problem = self.find_problems(event)[0]
single_problem_fingerprint = single_span_problem.fingerprint
event["spans"].append(event["spans"][0])
double_span_problem = self.find_problems(event)[0]
assert double_span_problem.title == "File IO on Main Thread"
assert double_span_problem.fingerprint == single_problem_fingerprint
def test_file_io_with_proguard(self) -> None:
event = get_event("file-io-on-main-thread/file-io-on-main-thread-with-obfuscation")
event["project"] = self.project.id
uuid = event["debug_meta"]["images"][0]["uuid"]
self.create_proguard(uuid)
problem = self.find_problems(event)[0]
call_stack = b"org.slf4j.helpers.Util$ClassContextSecurityManager.getExtraClassContext"
hashed_stack = hashlib.sha1(call_stack).hexdigest()
assert (
problem.fingerprint
== f"1-{PerformanceFileIOMainThreadGroupType.type_id}-{hashed_stack}"
)
assert problem.title == "File IO on Main Thread"
def test_parallel_spans_detected(self) -> None:
event = get_event("file-io-on-main-thread/file-io-on-main-thread-with-parallel-spans")
problem = self.find_problems(event)[0]
assert problem.offender_span_ids == ["054ba3a374d543eb", "054ba3a3a4d543ab"]
def test_parallel_spans_not_detected_when_total_too_short(self) -> None:
event = get_event("file-io-on-main-thread/file-io-on-main-thread-with-parallel-spans")
event["spans"][1]["timestamp"] = 1669031858.015
problems = self.find_problems(event)
assert len(problems) == 0
def test_complicated_structure(self) -> None:
event = get_event(
"file-io-on-main-thread/file-io-on-main-thread-with-complicated-structure"
)
problem = self.find_problems(event)[0]
assert problem.offender_span_ids == [
"054ba3a374d543eb",
"054ba3a3a4d543ab",
"054ba3a3a4d543cd",
"054ba3a3a4d543ef",
"054ba3a3a4d54ab1",
"054ba3a3a4d54ab2",
"054ba3a3a4d54ab3",
"054ba3a3a4d54ab4",
]
| FileIOMainThreadDetectorTest |
python | huggingface__transformers | src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py | {
"start": 155473,
"end": 156024
} | class ____(nn.Module):
"""Layer scale from [Touvron et al 2021] (https://huggingface.co/papers/2103.17239).
This rescales diagonally the residual outputs close to 0, with a learnt scale.
"""
def __init__(self, config):
super().__init__()
channels = config.hidden_size
initial_scale = config.layer_scale_initial_scale
self.scale = nn.Parameter(torch.full((channels,), initial_scale, requires_grad=True))
def forward(self, x: torch.Tensor):
return self.scale * x
| Qwen3OmniMoeCode2WavLayerScale |
python | doocs__leetcode | solution/3300-3399/3356.Zero Array Transformation II/Solution.py | {
"start": 0,
"end": 546
} | class ____:
def minZeroArray(self, nums: List[int], queries: List[List[int]]) -> int:
def check(k: int) -> bool:
d = [0] * (len(nums) + 1)
for l, r, val in queries[:k]:
d[l] += val
d[r + 1] -= val
s = 0
for x, y in zip(nums, d):
s += y
if x > s:
return False
return True
m = len(queries)
l = bisect_left(range(m + 1), True, key=check)
return -1 if l > m else l
| Solution |
python | gevent__gevent | src/greentest/3.10/test_wsgiref.py | {
"start": 19417,
"end": 19941
} | class ____(BaseCGIHandler):
"""Simple handler subclass for testing BaseHandler"""
# BaseHandler records the OS environment at import time, but envvars
# might have been changed later by other tests, which trips up
# HandlerTests.testEnviron().
os_environ = dict(os.environ.items())
def __init__(self,**kw):
setup_testing_defaults(kw)
BaseCGIHandler.__init__(
self, BytesIO(), BytesIO(), StringIO(), kw,
multithread=True, multiprocess=True
)
| ErrorHandler |
python | lxml__lxml | src/lxml/tests/common_imports.py | {
"start": 5684,
"end": 6731
} | class ____:
def __init__(self, path):
self.path = path
def __fspath__(self):
return self.path
def fileInTestDir(name):
_testdir = os.path.dirname(__file__)
return os.path.join(_testdir, name)
def path2url(path):
return urlparse.urljoin(
'file://', pathname2url(path))
def fileUrlInTestDir(name):
return path2url(fileInTestDir(name))
def read_file(name, mode='r'):
with open(name, mode) as f:
data = f.read()
return data
def write_to_file(name, data, mode='w'):
with open(name, mode) as f:
f.write(data)
def readFileInTestDir(name, mode='r'):
return read_file(fileInTestDir(name), mode)
def canonicalize(xml):
tree = etree.parse(BytesIO(xml) if isinstance(xml, bytes) else StringIO(xml))
f = BytesIO()
tree.write_c14n(f)
return f.getvalue()
@contextmanager
def tmpfile(**kwargs):
handle, filename = tempfile.mkstemp(**kwargs)
try:
yield filename
finally:
os.close(handle)
os.remove(filename)
| SimpleFSPath |
python | django__django | django/contrib/gis/db/backends/base/features.py | {
"start": 101,
"end": 4106
} | class ____:
gis_enabled = True
# Does the database contain a SpatialRefSys model to store SRID
# information?
has_spatialrefsys_table = True
# Does the backend support the django.contrib.gis.utils.add_srs_entry()
# utility?
supports_add_srs_entry = True
# Does the backend introspect GeometryField to its subtypes?
supports_geometry_field_introspection = True
# Does the database have a geography type?
supports_geography = False
# Does the backend support storing 3D geometries?
supports_3d_storage = False
# Reference implementation of 3D functions is:
# https://postgis.net/docs/PostGIS_Special_Functions_Index.html#PostGIS_3D_Functions
supports_3d_functions = False
# Does the database support SRID transform operations?
supports_transform = True
# Can geometry fields be null?
supports_null_geometries = True
# Are empty geometries supported?
supports_empty_geometries = False
# Can the function be applied on geodetic coordinate systems?
supports_distance_geodetic = True
supports_length_geodetic = True
supports_perimeter_geodetic = False
supports_area_geodetic = True
# Is the database able to count vertices on polygons (with `num_points`)?
supports_num_points_poly = True
# Does the backend support expressions for specifying distance in the
# dwithin lookup?
supports_dwithin_distance_expr = True
# Does the database have raster support?
supports_raster = False
# Does the database support a unique index on geometry fields?
supports_geometry_field_unique_index = True
# Can SchemaEditor alter geometry fields?
can_alter_geometry_field = True
# Do the database functions/aggregates support the tolerance parameter?
supports_tolerance_parameter = False
# Set of options that AsGeoJSON() doesn't support.
unsupported_geojson_options = {}
# Does Intersection() return None (rather than an empty GeometryCollection)
# for empty results?
empty_intersection_returns_none = True
@property
def supports_bbcontains_lookup(self):
return "bbcontains" in self.connection.ops.gis_operators
@property
def supports_contained_lookup(self):
return "contained" in self.connection.ops.gis_operators
@property
def supports_crosses_lookup(self):
return "crosses" in self.connection.ops.gis_operators
@property
def supports_distances_lookups(self):
return self.has_Distance_function
@property
def supports_dwithin_lookup(self):
return "dwithin" in self.connection.ops.gis_operators
@property
def supports_relate_lookup(self):
return "relate" in self.connection.ops.gis_operators
@property
def supports_isvalid_lookup(self):
return self.has_IsValid_function
# Is the aggregate supported by the database?
@property
def supports_collect_aggr(self):
return models.Collect not in self.connection.ops.disallowed_aggregates
@property
def supports_extent_aggr(self):
return models.Extent not in self.connection.ops.disallowed_aggregates
@property
def supports_make_line_aggr(self):
return models.MakeLine not in self.connection.ops.disallowed_aggregates
@property
def supports_union_aggr(self):
return models.Union not in self.connection.ops.disallowed_aggregates
def __getattr__(self, name):
m = re.match(r"has_(\w*)_function$", name)
if m:
func_name = m[1]
if func_name not in BaseSpatialOperations.unsupported_functions:
raise ValueError(
f"DatabaseFeatures.has_{func_name}_function isn't valid. "
f'Is "{func_name}" missing from '
"BaseSpatialOperations.unsupported_functions?"
)
return func_name not in self.connection.ops.unsupported_functions
raise AttributeError
| BaseSpatialFeatures |
python | sympy__sympy | sympy/functions/elementary/hyperbolic.py | {
"start": 47976,
"end": 53220
} | class ____(InverseHyperbolicFunction):
"""
``atanh(x)`` is the inverse hyperbolic tangent of ``x``.
The inverse hyperbolic tangent function.
Examples
========
>>> from sympy import atanh
>>> from sympy.abc import x
>>> atanh(x).diff(x)
1/(1 - x**2)
See Also
========
sympy.functions.elementary.hyperbolic.asinh
sympy.functions.elementary.hyperbolic.acosh
sympy.functions.elementary.hyperbolic.tanh
"""
def fdiff(self, argindex=1):
if argindex == 1:
return 1/(1 - self.args[0]**2)
else:
raise ArgumentIndexError(self, argindex)
@classmethod
def eval(cls, arg):
if arg.is_Number:
if arg is S.NaN:
return S.NaN
elif arg.is_zero:
return S.Zero
elif arg is S.One:
return S.Infinity
elif arg is S.NegativeOne:
return S.NegativeInfinity
elif arg is S.Infinity:
return -I * atan(arg)
elif arg is S.NegativeInfinity:
return I * atan(-arg)
elif arg.is_negative:
return -cls(-arg)
else:
if arg is S.ComplexInfinity:
from sympy.calculus.accumulationbounds import AccumBounds
return I*AccumBounds(-pi/2, pi/2)
i_coeff = _imaginary_unit_as_coefficient(arg)
if i_coeff is not None:
return I * atan(i_coeff)
else:
if arg.could_extract_minus_sign():
return -cls(-arg)
if arg.is_zero:
return S.Zero
if isinstance(arg, tanh):
z = arg.args[0]
if z.is_real:
return z
if z.is_number:
r, i = match_real_imag(z)
if r is not None and i is not None:
f = floor(2*i/pi)
even = f.is_even
m = z - I*f*pi/2
if even is True:
return m
elif even is False:
return m - I*pi/2
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms):
if n < 0 or n % 2 == 0:
return S.Zero
else:
x = sympify(x)
return x**n / n
def _eval_as_leading_term(self, x, logx, cdir):
arg = self.args[0]
x0 = arg.subs(x, 0).cancel()
if x0.is_zero:
return arg.as_leading_term(x)
if x0 is S.NaN:
expr = self.func(arg.as_leading_term(x))
if expr.is_finite:
return expr
else:
return self
# Handling branch points
if x0 in (-S.One, S.One, S.ComplexInfinity):
return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
# Handling points lying on branch cuts (-oo, -1] U [1, oo)
if (1 - x0**2).is_negative:
ndir = arg.dir(x, cdir if cdir else 1)
if im(ndir).is_negative:
if x0.is_negative:
return self.func(x0) - I*pi
elif im(ndir).is_positive:
if x0.is_positive:
return self.func(x0) + I*pi
else:
return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
return self.func(x0)
def _eval_nseries(self, x, n, logx, cdir=0): # atanh
arg = self.args[0]
arg0 = arg.subs(x, 0)
# Handling branch points
if arg0 in (S.One, S.NegativeOne):
return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
res = super()._eval_nseries(x, n=n, logx=logx)
if arg0 is S.ComplexInfinity:
return res
# Handling points lying on branch cuts (-oo, -1] U [1, oo)
if (1 - arg0**2).is_negative:
ndir = arg.dir(x, cdir if cdir else 1)
if im(ndir).is_negative:
if arg0.is_negative:
return res - I*pi
elif im(ndir).is_positive:
if arg0.is_positive:
return res + I*pi
else:
return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
return res
def _eval_rewrite_as_log(self, x, **kwargs):
return (log(1 + x) - log(1 - x)) / 2
_eval_rewrite_as_tractable = _eval_rewrite_as_log
def _eval_rewrite_as_asinh(self, x, **kwargs):
f = sqrt(1/(x**2 - 1))
return (pi*x/(2*sqrt(-x**2)) -
sqrt(-x)*sqrt(1 - x**2)/sqrt(x)*f*asinh(f))
def _eval_is_zero(self):
if self.args[0].is_zero:
return True
def _eval_is_extended_real(self):
return fuzzy_and([self.args[0].is_extended_real, (1 - self.args[0]).is_nonnegative, (self.args[0] + 1).is_nonnegative])
def _eval_is_finite(self):
return fuzzy_not(fuzzy_or([(self.args[0] - 1).is_zero, (self.args[0] + 1).is_zero]))
def _eval_is_imaginary(self):
return self.args[0].is_imaginary
def inverse(self, argindex=1):
"""
Returns the inverse of this function.
"""
return tanh
| atanh |
python | streamlit__streamlit | lib/streamlit/elements/widgets/chat.py | {
"start": 14129,
"end": 38692
} | class ____:
@gather_metrics("chat_message")
def chat_message(
self,
name: Literal["user", "assistant", "ai", "human"] | str,
*,
avatar: Literal["user", "assistant"] | str | AtomicImage | None = None,
width: Width = "stretch",
) -> DeltaGenerator:
"""Insert a chat message container.
To add elements to the returned container, you can use ``with`` notation
(preferred) or just call methods directly on the returned object. See the
examples below.
.. note::
To follow best design practices and maintain a good appearance on
all screen sizes, don't nest chat message containers.
Parameters
----------
name : "user", "assistant", "ai", "human", or str
The name of the message author. Can be "human"/"user" or
"ai"/"assistant" to enable preset styling and avatars.
Currently, the name is not shown in the UI but is only set as an
accessibility label. For accessibility reasons, you should not use
an empty string.
avatar : Anything supported by st.image (except list), str, or None
The avatar shown next to the message.
If ``avatar`` is ``None`` (default), the icon will be determined
from ``name`` as follows:
- If ``name`` is ``"user"`` or ``"human"``, the message will have a
default user icon.
- If ``name`` is ``"ai"`` or ``"assistant"``, the message will have
a default bot icon.
- For all other values of ``name``, the message will show the first
letter of the name.
In addition to the types supported by |st.image|_ (except list),
the following strings are valid:
- A single-character emoji. For example, you can set ``avatar="🧑💻"``
or ``avatar="🦖"``. Emoji short codes are not supported.
- An icon from the Material Symbols library (rounded style) in the
format ``":material/icon_name:"`` where "icon_name" is the name
of the icon in snake case.
For example, ``icon=":material/thumb_up:"`` will display the
Thumb Up icon. Find additional icons in the `Material Symbols \
<https://fonts.google.com/icons?icon.set=Material+Symbols&icon.style=Rounded>`_
font library.
- ``"spinner"``: Displays a spinner as an icon.
.. |st.image| replace:: ``st.image``
.. _st.image: https://docs.streamlit.io/develop/api-reference/media/st.image
width : "stretch", "content", or int
The width of the chat message container. This can be one of the following:
- ``"stretch"`` (default): The width of the container matches the
width of the parent container.
- ``"content"``: The width of the container matches the width of its
content, but doesn't exceed the width of the parent container.
- An integer specifying the width in pixels: The container has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the container matches the width
of the parent container.
Returns
-------
Container
A single container that can hold multiple elements.
Examples
--------
You can use ``with`` notation to insert any element into an expander
>>> import streamlit as st
>>> import numpy as np
>>>
>>> with st.chat_message("user"):
... st.write("Hello 👋")
... st.line_chart(np.random.randn(30, 3))
.. output ::
https://doc-chat-message-user.streamlit.app/
height: 450px
Or you can just call methods directly in the returned objects:
>>> import streamlit as st
>>> import numpy as np
>>>
>>> message = st.chat_message("assistant")
>>> message.write("Hello human")
>>> message.bar_chart(np.random.randn(30, 3))
.. output ::
https://doc-chat-message-user1.streamlit.app/
height: 450px
"""
if name is None:
raise StreamlitAPIException(
"The author name is required for a chat message, please set it via the parameter `name`."
)
if avatar is None and (
name.lower() in {item.value for item in PresetNames} or is_emoji(name)
):
# For selected labels, we are mapping the label to an avatar
avatar = name.lower()
avatar_type, converted_avatar = _process_avatar_input(
avatar, self.dg._get_delta_path_str()
)
validate_width(width, allow_content=True)
message_container_proto = BlockProto.ChatMessage()
message_container_proto.name = name
message_container_proto.avatar = converted_avatar
message_container_proto.avatar_type = avatar_type
# Set up width configuration
width_config = WidthConfig()
if isinstance(width, int):
width_config.pixel_width = width
elif width == "content":
width_config.use_content = True
else:
width_config.use_stretch = True
block_proto = BlockProto()
block_proto.allow_empty = True
block_proto.chat_message.CopyFrom(message_container_proto)
block_proto.width_config.CopyFrom(width_config)
return self.dg._block(block_proto=block_proto)
@overload
def chat_input(
self,
placeholder: str = "Your message",
*,
key: Key | None = None,
max_chars: int | None = None,
accept_file: Literal[False] = False,
file_type: str | Sequence[str] | None = None,
accept_audio: Literal[False] = False,
disabled: bool = False,
on_submit: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
width: WidthWithoutContent = "stretch",
) -> str | None: ...
@overload
def chat_input(
self,
placeholder: str = "Your message",
*,
key: Key | None = None,
max_chars: int | None = None,
accept_file: Literal[False] = False,
file_type: str | Sequence[str] | None = None,
accept_audio: Literal[True],
audio_sample_rate: int | None = 16000,
disabled: bool = False,
on_submit: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
width: WidthWithoutContent = "stretch",
) -> ChatInputValue | None: ...
@overload
def chat_input(
self,
placeholder: str = "Your message",
*,
key: Key | None = None,
max_chars: int | None = None,
accept_file: Literal[True, "multiple", "directory"],
file_type: str | Sequence[str] | None = None,
accept_audio: bool = False,
audio_sample_rate: int | None = 16000,
disabled: bool = False,
on_submit: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
width: WidthWithoutContent = "stretch",
) -> ChatInputValue | None: ...
@gather_metrics("chat_input")
def chat_input(
self,
placeholder: str = "Your message",
*,
key: Key | None = None,
max_chars: int | None = None,
accept_file: bool | Literal["multiple", "directory"] = False,
file_type: str | Sequence[str] | None = None,
accept_audio: bool = False,
audio_sample_rate: int | None = 16000,
disabled: bool = False,
on_submit: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
width: WidthWithoutContent = "stretch",
) -> str | ChatInputValue | None:
"""Display a chat input widget.
Parameters
----------
placeholder : str
A placeholder text shown when the chat input is empty. This
defaults to ``"Your message"``. For accessibility reasons, you
should not use an empty string.
key : str or int
An optional string or integer to use as the unique key for the widget.
If this is omitted, a key will be generated for the widget based on
its content. No two widgets may have the same key.
max_chars : int or None
The maximum number of characters that can be entered. If this is
``None`` (default), there will be no maximum.
accept_file : bool, "multiple", or "directory"
Whether the chat input should accept files. This can be one of the
following values:
- ``False`` (default): No files are accepted and the user can only
submit a message.
- ``True``: The user can add a single file to their submission.
- ``"multiple"``: The user can add multiple files to their
submission.
- ``"directory"``: The user can add multiple files to their
submission by selecting a directory. If ``file_type`` is set,
only files matching those type(s) will be uploaded.
By default, uploaded files are limited to 200 MB each. You can
configure this using the ``server.maxUploadSize`` config option.
For more information on how to set config options, see
|config.toml|_.
.. |config.toml| replace:: ``config.toml``
.. _config.toml: https://docs.streamlit.io/develop/api-reference/configuration/config.toml
file_type : str, Sequence[str], or None
The allowed file extension(s) for uploaded files. This can be one
of the following types:
- ``None`` (default): All file extensions are allowed.
- A string: A single file extension is allowed. For example, to
only accept CSV files, use ``"csv"``.
- A sequence of strings: Multiple file extensions are allowed. For
example, to only accept JPG/JPEG and PNG files, use
``["jpg", "jpeg", "png"]``.
.. note::
This is a best-effort check, but doesn't provide a
security guarantee against users uploading files of other types
or type extensions. The correct handling of uploaded files is
part of the app developer's responsibility.
accept_audio : bool
Whether to show an audio recording button in the chat input.
When enabled, users can record and submit audio messages.
Recorded audio is uploaded as a WAV file and can be accessed
through the ``audio`` attribute of the returned dict-like object.
The ``audio`` attribute is only present when ``accept_audio=True``.
When present, it contains an ``UploadedFile`` object or ``None``
if no audio was recorded.
This defaults to ``False``.
audio_sample_rate : int or None
The target sample rate for audio recording in Hz. This defaults to
16000 Hz, which is optimal for speech recognition. Common sample
rates include:
- ``8000`` Hz: Telephone quality
- ``16000`` Hz: Speech recognition (default)
- ``48000`` Hz: High-quality recording
Set to ``None`` to use the browser's default sample rate (no
resampling). Allowed values are ``8000``, ``11025``, ``16000``,
``22050``, ``24000``, ``32000``, ``44100``, ``48000``, or ``None``.
disabled : bool
Whether the chat input should be disabled. This defaults to
``False``.
on_submit : callable
An optional callback invoked when the chat input's value is submitted.
args : list or tuple
An optional list or tuple of args to pass to the callback.
kwargs : dict
An optional dict of kwargs to pass to the callback.
width : "stretch" or int
The width of the chat input widget. This can be one of the
following:
- ``"stretch"`` (default): The width of the widget matches the
width of the parent container.
- An integer specifying the width in pixels: The widget has a
fixed width. If the specified width is greater than the width of
the parent container, the width of the widget matches the width
of the parent container.
Returns
-------
None, str, or dict-like
The user's submission. This is one of the following types:
- ``None``: If the user didn't submit a message, file, or audio
in the last rerun, the widget returns ``None``.
- A string: When the widget is not configured to accept files or
audio and the user submitted a message in the last rerun, the
widget returns the user's message as a string.
- A dict-like object: When the widget is configured to accept files
and/or audio and the user submitted a message and/or file(s)
and/or audio in the last rerun, the widget returns a dict-like
object. The object always includes the ``text`` attribute, and
optionally includes ``files`` and/or ``audio`` attributes depending
on the ``accept_file`` and ``accept_audio`` parameters.
When the widget is configured to accept files or audio and the user
submits something in the last rerun, you can access the user's
submission with key or attribute notation from the dict-like object.
This is shown in Example 3 below.
The ``text`` attribute holds a string, which is the user's message.
This is an empty string if the user only submitted one or more
files or audio.
The ``files`` attribute is only present when ``accept_file`` is not
``False``. When present, it holds a list of ``UploadedFile`` objects.
The list is empty if the user only submitted a message or audio.
Unlike ``st.file_uploader``, this attribute always returns a list,
even when the widget is configured to accept only one file at a time.
The ``audio`` attribute is only present when ``accept_audio=True``.
When present, it holds an ``UploadedFile`` object representing
the recorded audio, or ``None`` if no audio was recorded.
The UploadedFile class is a subclass of BytesIO, and therefore is
"file-like". This means you can pass an instance of it anywhere a
file is expected.
Examples
--------
**Example 1: Pin the chat input widget to the bottom of your app**
When ``st.chat_input`` is used in the main body of an app, it will be
pinned to the bottom of the page.
>>> import streamlit as st
>>>
>>> prompt = st.chat_input("Say something")
>>> if prompt:
... st.write(f"User has sent the following prompt: {prompt}")
.. output ::
https://doc-chat-input.streamlit.app/
height: 350px
**Example 2: Use the chat input widget inline**
The chat input can also be used inline by nesting it inside any layout
container (container, columns, tabs, sidebar, etc) or fragment. Create
chat interfaces embedded next to other content, or have multiple
chatbots!
>>> import streamlit as st
>>>
>>> with st.sidebar:
>>> messages = st.container(height=300)
>>> if prompt := st.chat_input("Say something"):
>>> messages.chat_message("user").write(prompt)
>>> messages.chat_message("assistant").write(f"Echo: {prompt}")
.. output ::
https://doc-chat-input-inline.streamlit.app/
height: 350px
**Example 3: Let users upload files**
When you configure your chat input widget to allow file attachments, it
will return a dict-like object when the user sends a submission. You
can access the user's message through the ``text`` attribute of this
dictionary. You can access a list of the user's submitted file(s)
through the ``files`` attribute. Similar to ``st.session_state``, you
can use key or attribute notation.
>>> import streamlit as st
>>>
>>> prompt = st.chat_input(
>>> "Say something and/or attach an image",
>>> accept_file=True,
>>> file_type=["jpg", "jpeg", "png"],
>>> )
>>> if prompt and prompt.text:
>>> st.markdown(prompt.text)
>>> if prompt and prompt["files"]:
>>> st.image(prompt["files"][0])
.. output ::
https://doc-chat-input-file-uploader.streamlit.app/
height: 350px
**Example 4: Programmatically set the text via session state**
You can use ``st.session_state`` to set the text of the chat input widget.
>>> import streamlit as st
>>>
>>> if st.button("Set Value"):
>>> st.session_state.chat_input = "Hello, world!"
>>> st.chat_input(key="chat_input")
>>> st.write("Chat input value:", st.session_state.chat_input)
.. output ::
https://doc-chat-input-session-state.streamlit.app/
height: 350px
**Example 5: Enable audio recording**
You can enable audio recording by setting ``accept_audio=True``.
The ``accept_audio`` parameter works independently of ``accept_file``,
allowing you to enable audio recording with or without file uploads.
>>> import streamlit as st
>>>
>>> prompt = st.chat_input(
>>> "Say or record something",
>>> accept_audio=True,
>>> )
>>> if prompt:
>>> if prompt.text:
>>> st.write("Text:", prompt.text)
>>> if prompt.audio:
>>> st.audio(prompt.audio)
>>> st.write("Audio file:", prompt.audio.name)
"""
key = to_key(key)
check_widget_policies(
self.dg,
key,
on_submit,
default_value=None,
writes_allowed=True,
)
if accept_file not in {True, False, "multiple", "directory"}:
raise StreamlitAPIException(
"The `accept_file` parameter must be a boolean or 'multiple' or 'directory'."
)
ctx = get_script_run_ctx()
element_id = compute_and_register_element_id(
"chat_input",
user_key=key,
# Treat the provided key as the main identity. Only include
# properties that can invalidate the current widget state
# when changed. For chat_input, those are:
# - accept_file: Changes whether files can be attached (and how)
# - file_type: Restricts the accepted file types
# - max_chars: Changes the maximum allowed characters for the input
key_as_main_identity={"accept_file", "file_type", "max_chars"},
dg=self.dg,
placeholder=placeholder,
max_chars=max_chars,
accept_file=accept_file,
file_type=file_type,
accept_audio=accept_audio,
audio_sample_rate=audio_sample_rate,
width=width,
)
if file_type:
file_type = normalize_upload_file_type(file_type)
# Validate audio_sample_rate if provided
if (
audio_sample_rate is not None
and audio_sample_rate not in ALLOWED_SAMPLE_RATES
):
raise StreamlitAPIException(
f"Invalid audio_sample_rate: {audio_sample_rate}. "
f"Must be one of {sorted(ALLOWED_SAMPLE_RATES)} Hz, or None for browser default."
)
# It doesn't make sense to create a chat input inside a form.
# We throw an error to warn the user about this.
# We omit this check for scripts running outside streamlit, because
# they will have no script_run_ctx.
if runtime.exists() and is_in_form(self.dg):
raise StreamlitAPIException(
"`st.chat_input()` can't be used in a `st.form()`."
)
# Determine the position of the chat input:
# Use bottom position if chat input is within the main container
# either directly or within a vertical container. If it has any
# other container types as parents, we use inline position.
ancestor_block_types = set(self.dg._active_dg._ancestor_block_types)
if (
self.dg._active_dg._root_container == RootContainer.MAIN
and not ancestor_block_types
):
position = "bottom"
else:
position = "inline"
chat_input_proto = ChatInputProto()
chat_input_proto.id = element_id
chat_input_proto.placeholder = str(placeholder)
if max_chars is not None:
chat_input_proto.max_chars = max_chars
# Setting a default value is currently not supported for chat input.
chat_input_proto.default = ""
chat_input_proto.accept_file = get_chat_input_accept_file_proto_value(
accept_file
)
chat_input_proto.file_type[:] = file_type if file_type is not None else []
chat_input_proto.max_upload_size_mb = config.get_option("server.maxUploadSize")
chat_input_proto.accept_audio = accept_audio
if audio_sample_rate is not None:
chat_input_proto.audio_sample_rate = audio_sample_rate
serde = ChatInputSerde(
accept_files=accept_file in {True, "multiple", "directory"},
accept_audio=accept_audio,
allowed_types=file_type,
)
widget_state = register_widget( # type: ignore[misc]
chat_input_proto.id,
on_change_handler=on_submit,
args=args,
kwargs=kwargs,
deserializer=serde.deserialize,
serializer=serde.serialize,
ctx=ctx,
value_type="chat_input_value",
)
validate_width(width)
layout_config = LayoutConfig(width=width)
chat_input_proto.disabled = disabled
if widget_state.value_changed and widget_state.value is not None:
# Support for programmatically setting the text in the chat input
# via session state. Since chat input has a trigger state,
# it works a bit differently to other widgets. We are not changing
# the actual widget state here, but only inserting the provided value
# into the chat input field. The user needs to submit the value in
# order for the chat input to reflect the value in the backend state.
chat_input_proto.value = widget_state.value
chat_input_proto.set_value = True
session_state = get_session_state()
if key is not None and key in session_state:
# Reset the session state value to None to reflect the actual state
# of the widget. Which is None since the value hasn't been submitted yet.
session_state.reset_state_value(key, None)
if ctx:
save_for_app_testing(ctx, element_id, widget_state.value)
if position == "bottom":
# We need to enqueue the chat input into the bottom container
# instead of the currently active dg.
get_dg_singleton_instance().bottom_dg._enqueue(
"chat_input", chat_input_proto, layout_config=layout_config
)
else:
self.dg._enqueue(
"chat_input", chat_input_proto, layout_config=layout_config
)
return widget_state.value if not widget_state.value_changed else None
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
| ChatMixin |
python | pytorch__pytorch | torch/distributed/_composable/replicate_with_fsdp.py | {
"start": 2587,
"end": 10193
} | class ____(FSDPState):
"""
Replicate state functionality is adapted from FSDP state.
In the future, could experiment with inheriting from it instead.
"""
def __init__(self) -> None:
super().__init__()
self._state_ctx = _ReplicateStateContext() # type: ignore[assignment]
# Define a separate init since `__init__` is called in the contract
def init(
self,
modules: tuple[nn.Module, ...],
device: torch.device,
mp_policy: MixedPrecisionPolicy,
auto_reshard_after_forward: bool = False,
) -> None:
for module in modules:
_insert_module_state(module, self)
self._modules = modules
# pyrefly: ignore [read-only]
self._device = device
self._device_handle = _get_device_handle(device.type)
self._mp_policy = mp_policy
self._auto_reshard_after_forward = auto_reshard_after_forward
if len(modules) == 1:
self._pre_forward_hook_handle = modules[0].register_forward_pre_hook(
self._pre_forward, prepend=True, with_kwargs=True
)
self._post_forward_hook_handle = modules[0].register_forward_hook(
self._post_forward, prepend=False
)
else:
hook_handle = _register_group_forward_hooks(
modules,
self._pre_forward,
self._post_forward,
self._modules_to_run_forward,
)
self._pre_forward_hook_handle = hook_handle
self._post_forward_hook_handle = hook_handle
def _lazy_init(self) -> None:
"""
Lazy initialization represents when all modules' parallelisms have
finalized (e.g. Replicate has been applied to all desired modules). This
means that we can determine which state is the root, and we do so by
the 1st state to run forward.
"""
if self._is_root is not None:
return # no-op: already initialized
self._is_root = True
if len(self._modules) > 1:
raise RuntimeError(
f"Replicate requires a single root module but got {self._modules}"
)
detect_compiled_autograd()
root_module = self._modules[0]
visited_states: set[_ReplicateState] = set()
for module_name, module in root_module.named_modules():
if (state := _get_module_replicate_state(module)) is None:
continue
if module is not root_module:
if state not in visited_states and state._is_root is not None:
raise RuntimeError(
"Replicate state has already been lazily initialized for "
f"{module_name}\nReplicate requires running forward through "
"the root module first"
)
state._is_root = False
self._state_ctx.all_states.append(state)
# pyrefly: ignore [bad-argument-type]
visited_states.add(state)
if self._fsdp_param_group and self._auto_reshard_after_forward:
# For the root, do not reshard after forward since for training,
# the parameters would be freed and all-gathered immediately
self._fsdp_param_group.post_forward_mesh_info = None
self._init_fqns()
self._init_shared_state()
# Run parameter group lazy inits after initializing FQNs for improved
# error messages
for state in self._state_ctx.all_states: # type: ignore[assignment]
if state._fsdp_param_group: # type: ignore[union-attr]
state._fsdp_param_group.lazy_init() # type: ignore[union-attr]
def replicate_impl(
module,
mesh: DeviceMesh,
*,
device_id: Optional[Union[int, torch.device]] = None,
mp_policy: MixedPrecisionPolicy = MixedPrecisionPolicy(),
offload_policy: OffloadPolicy = OffloadPolicy(),
ignored_params: Optional[set[nn.Parameter]] = None,
):
torch._C._log_api_usage_once("torch.distributed._composable.replicate_with_fsdp")
if isinstance(module, (nn.ModuleList, nn.ModuleDict)):
raise ValueError(
f"replicate does not support containers that do not implement forward: {module}"
)
mesh = mesh or _init_default_fully_shard_mesh()
if mesh.ndim != 1:
raise ValueError(f"replicate expects a 1D DeviceMesh but got {mesh}")
else:
if mesh.mesh_dim_names is None:
raise AssertionError(
"Please init the 2D mesh for HSDP with mesh_dim_names specified"
)
mesh_info = DDPMeshInfo(mesh, replicate_mesh_dim=0)
device = _get_device_from_mesh(mesh)
post_forward_mesh_info = None
arg_module = module
modules = (
(module,) if isinstance(module, nn.Module) else tuple(_get_root_modules(module))
)
state = replicate.state(modules[0]) # type: ignore[attr-defined] # see [1]
state.init(modules, device, mp_policy)
managed_modules = _get_managed_modules(modules, ignored_params)
params, buffers = _get_managed_states(managed_modules, ignored_params)
_move_states_to_device(params, buffers, device)
if params:
state._fsdp_param_group = FSDPParamGroup(
params,
modules,
mesh_info, # type: ignore[arg-type]
post_forward_mesh_info,
device,
None,
mp_policy,
offload_policy,
)
# Place Replicate leftmost for highest priority in the method resolution order
for module in modules:
cls = module.__class__
new_cls = cls_to_replicate_cls.get(cls)
if not new_cls:
dct = {"__deepcopy__": _unimplemented_deepcopy}
new_cls = type(f"Replicate{cls.__name__}", (ReplicateModule, cls), dct)
cls_to_replicate_cls[cls] = new_cls
module.__class__ = new_cls
return arg_module
@overload
# pyrefly: ignore [inconsistent-overload]
def replicate(
module: nn.Module,
*,
mesh: Optional[DeviceMesh] = ...,
mp_policy: MixedPrecisionPolicy = ...,
offload_policy: OffloadPolicy = ...,
ignored_params: Optional[set[nn.Parameter]] = ...,
) -> ReplicateModule: ...
@overload
# pyrefly: ignore [inconsistent-overload]
def replicate(
module: list[nn.Module],
*,
mesh: Optional[DeviceMesh] = ...,
mp_policy: MixedPrecisionPolicy = ...,
offload_policy: OffloadPolicy = ...,
ignored_params: Optional[set[nn.Parameter]] = ...,
) -> list[ReplicateModule]: ...
@contract(state_cls=_ReplicateState) # type: ignore[misc]
def replicate(
module: nn.Module,
*,
mesh: Optional[DeviceMesh] = None,
mp_policy: MixedPrecisionPolicy = MixedPrecisionPolicy(),
offload_policy: OffloadPolicy = OffloadPolicy(),
ignored_params: Optional[set[nn.Parameter]] = None,
):
r"""Replicates a module
Args:
module (torch.nn.Module): module to replicate
Example::
>>> # xdoctest: +REQUIRES(module:torch._C._distributed_c10d)
>>> module = nn.Linear(3, 3)
>>> replicate(module)
"""
if not is_composable_with_replicate(module):
raise RuntimeError(
"Cannot apply `replicate()` on a Module already managed by `fully_shard`"
)
if mesh is None:
mesh = replicate_mesh()
return replicate_impl(
module,
mesh,
mp_policy=mp_policy,
offload_policy=offload_policy,
ignored_params=ignored_params,
)
| _ReplicateState |
python | great-expectations__great_expectations | contrib/capitalone_dataprofiler_expectations/capitalone_dataprofiler_expectations/rule_based_profiler/data_assistant/data_profiler_structured_data_assistant.py | {
"start": 1481,
"end": 19608
} | class ____(DataAssistant):
"""
ProfileReportBasedColumnsDataAssistant provides dataset exploration and validation for columns of tabular data.
"""
__alias__: str = "data_profiler"
def __init__(
self,
name: str,
validator: Validator,
) -> None:
super().__init__(
name=name,
validator=validator,
)
def get_variables(self) -> Optional[Dict[str, Any]]:
"""
Returns:
Optional "variables" configuration attribute name/value pairs (overrides), commonly-used in Builder objects.
"""
return None
def get_rules(self) -> Optional[List[Rule]]:
"""
Returns:
Optional custom list of "Rule" objects implementing particular "DataAssistant" functionality.
"""
numeric_rule: Rule = self._build_numeric_rule()
float_rule: Rule = self._build_float_rule()
return [
numeric_rule,
float_rule,
]
def _build_data_assistant_result(
self, data_assistant_result: DataAssistantResult
) -> DataAssistantResult:
return DataProfilerStructuredDataAssistantResult(
_batch_id_to_batch_identifier_display_name_map=data_assistant_result._batch_id_to_batch_identifier_display_name_map,
profiler_config=data_assistant_result.profiler_config,
profiler_execution_time=data_assistant_result.profiler_execution_time,
rule_domain_builder_execution_time=data_assistant_result.rule_domain_builder_execution_time,
rule_execution_time=data_assistant_result.rule_execution_time,
rule_exception_tracebacks=data_assistant_result.rule_exception_tracebacks,
metrics_by_domain=data_assistant_result.metrics_by_domain,
expectation_configurations=data_assistant_result.expectation_configurations,
citation=data_assistant_result.citation,
_usage_statistics_handler=data_assistant_result._usage_statistics_handler,
)
@staticmethod
def _build_numeric_rule() -> Rule:
"""
This method builds "Rule" object configured to emit "ExpectationConfiguration" objects for column "Domain" type.
This rule holds expectations which are associated with the numeric metrics in the data profiler report. There
are additional rules which are planned to be created, such as timestamp_rule, text_rule, categorical_rule, etc.
Currently, the numeric_rule uses ColumnDomainBuilder, so it doesn't discriminate by data type when applying the
rule.
"""
"""
Subject to inclusion/exclusion arguments, "DataProfilerColumnDomainBuilder" emits "Domain" object for every
column name in profiler report; GreatExpectations "table.columns" metric is used to validate column existence.
"""
data_profiler_column_domain_builder: DomainBuilder = DataProfilerColumnDomainBuilder()
data_profiler_profile_report_metric_single_batch_parameter_builder_for_metrics: ParameterBuilder = DataAssistant.commonly_used_parameter_builders.build_metric_single_batch_parameter_builder(
metric_name="data_profiler.column_profile_report",
suffix=None,
metric_domain_kwargs=DOMAIN_KWARGS_PARAMETER_FULLY_QUALIFIED_NAME,
metric_value_kwargs={
"profile_path": f"{VARIABLES_KEY}profile_path",
},
)
data_profiler_profile_report_metric_single_batch_parameter_builder_for_validations: ParameterBuilder = data_profiler_profile_report_metric_single_batch_parameter_builder_for_metrics
validation_parameter_builder_configs: Optional[List[ParameterBuilderConfig]]
validation_parameter_builder_configs = [
ParameterBuilderConfig(
**data_profiler_profile_report_metric_single_batch_parameter_builder_for_validations.to_json_dict(),
),
]
expect_column_min_to_be_between_expectation_configuration_builder: ExpectationConfigurationBuilder = DefaultExpectationConfigurationBuilder(
expectation_type="expect_column_min_to_be_between",
validation_parameter_builder_configs=validation_parameter_builder_configs,
column=f"{DOMAIN_KWARGS_PARAMETER_FULLY_QUALIFIED_NAME}{FULLY_QUALIFIED_PARAMETER_NAME_SEPARATOR_CHARACTER}column",
min_value=f"{data_profiler_profile_report_metric_single_batch_parameter_builder_for_validations.json_serialized_fully_qualified_parameter_name}{FULLY_QUALIFIED_PARAMETER_NAME_SEPARATOR_CHARACTER}{FULLY_QUALIFIED_PARAMETER_NAME_VALUE_KEY}.statistics.min",
max_value=None,
strict_min=f"{VARIABLES_KEY}strict_min",
strict_max=None,
meta={
"profiler_details": f"{data_profiler_profile_report_metric_single_batch_parameter_builder_for_validations.json_serialized_fully_qualified_parameter_name}{FULLY_QUALIFIED_PARAMETER_NAME_SEPARATOR_CHARACTER}{FULLY_QUALIFIED_PARAMETER_NAME_METADATA_KEY}",
},
)
expect_column_max_to_be_between_expectation_configuration_builder: ExpectationConfigurationBuilder = DefaultExpectationConfigurationBuilder(
expectation_type="expect_column_max_to_be_between",
validation_parameter_builder_configs=validation_parameter_builder_configs,
column=f"{DOMAIN_KWARGS_PARAMETER_FULLY_QUALIFIED_NAME}{FULLY_QUALIFIED_PARAMETER_NAME_SEPARATOR_CHARACTER}column",
min_value=None,
max_value=f"{data_profiler_profile_report_metric_single_batch_parameter_builder_for_validations.json_serialized_fully_qualified_parameter_name}{FULLY_QUALIFIED_PARAMETER_NAME_SEPARATOR_CHARACTER}{FULLY_QUALIFIED_PARAMETER_NAME_VALUE_KEY}.statistics.max",
strict_min=None,
strict_max=f"{VARIABLES_KEY}strict_max",
meta={
"profiler_details": f"{data_profiler_profile_report_metric_single_batch_parameter_builder_for_validations.json_serialized_fully_qualified_parameter_name}{FULLY_QUALIFIED_PARAMETER_NAME_SEPARATOR_CHARACTER}{FULLY_QUALIFIED_PARAMETER_NAME_METADATA_KEY}",
},
)
expect_column_mean_to_be_between_expectation_configuration_builder: ExpectationConfigurationBuilder = DefaultExpectationConfigurationBuilder(
expectation_type="expect_column_mean_to_be_between",
validation_parameter_builder_configs=validation_parameter_builder_configs,
column=f"{DOMAIN_KWARGS_PARAMETER_FULLY_QUALIFIED_NAME}{FULLY_QUALIFIED_PARAMETER_NAME_SEPARATOR_CHARACTER}column",
min_value=f"{data_profiler_profile_report_metric_single_batch_parameter_builder_for_validations.json_serialized_fully_qualified_parameter_name}{FULLY_QUALIFIED_PARAMETER_NAME_SEPARATOR_CHARACTER}{FULLY_QUALIFIED_PARAMETER_NAME_VALUE_KEY}.statistics.mean",
max_value=f"{data_profiler_profile_report_metric_single_batch_parameter_builder_for_validations.json_serialized_fully_qualified_parameter_name}{FULLY_QUALIFIED_PARAMETER_NAME_SEPARATOR_CHARACTER}{FULLY_QUALIFIED_PARAMETER_NAME_VALUE_KEY}.statistics.mean",
strict_min=f"{VARIABLES_KEY}strict_min",
strict_max=f"{VARIABLES_KEY}strict_max",
meta={
"profiler_details": f"{data_profiler_profile_report_metric_single_batch_parameter_builder_for_validations.json_serialized_fully_qualified_parameter_name}{FULLY_QUALIFIED_PARAMETER_NAME_SEPARATOR_CHARACTER}{FULLY_QUALIFIED_PARAMETER_NAME_METADATA_KEY}",
},
)
expect_column_stddev_to_be_between_expectation_configuration_builder: ExpectationConfigurationBuilder = DefaultExpectationConfigurationBuilder(
expectation_type="expect_column_stdev_to_be_between",
validation_parameter_builder_configs=validation_parameter_builder_configs,
column=f"{DOMAIN_KWARGS_PARAMETER_FULLY_QUALIFIED_NAME}{FULLY_QUALIFIED_PARAMETER_NAME_SEPARATOR_CHARACTER}column",
min_value=f"{data_profiler_profile_report_metric_single_batch_parameter_builder_for_validations.json_serialized_fully_qualified_parameter_name}{FULLY_QUALIFIED_PARAMETER_NAME_SEPARATOR_CHARACTER}{FULLY_QUALIFIED_PARAMETER_NAME_VALUE_KEY}.statistics.stddev",
max_value=f"{data_profiler_profile_report_metric_single_batch_parameter_builder_for_validations.json_serialized_fully_qualified_parameter_name}{FULLY_QUALIFIED_PARAMETER_NAME_SEPARATOR_CHARACTER}{FULLY_QUALIFIED_PARAMETER_NAME_VALUE_KEY}.statistics.stddev",
strict_min=f"{VARIABLES_KEY}strict_min",
strict_max=f"{VARIABLES_KEY}strict_max",
meta={
"profiler_details": f"{data_profiler_profile_report_metric_single_batch_parameter_builder_for_validations.json_serialized_fully_qualified_parameter_name}{FULLY_QUALIFIED_PARAMETER_NAME_SEPARATOR_CHARACTER}{FULLY_QUALIFIED_PARAMETER_NAME_METADATA_KEY}",
},
)
variables: dict = {
"strict_min": False,
"strict_max": False,
"profile_path": "default_profiler_path",
"profile_report_filtering_key": "data_type",
"profile_report_accepted_filtering_values": ["int", "float", "string"],
}
parameter_builders: List[ParameterBuilder] = [
data_profiler_profile_report_metric_single_batch_parameter_builder_for_metrics,
]
expectation_configuration_builders: List[ExpectationConfigurationBuilder] = [
expect_column_min_to_be_between_expectation_configuration_builder,
expect_column_max_to_be_between_expectation_configuration_builder,
expect_column_mean_to_be_between_expectation_configuration_builder,
expect_column_stddev_to_be_between_expectation_configuration_builder,
]
rule = Rule(
name="numeric_rule",
variables=variables,
domain_builder=data_profiler_column_domain_builder,
parameter_builders=parameter_builders,
expectation_configuration_builders=expectation_configuration_builders,
)
return rule
@staticmethod
def _build_float_rule() -> Rule:
"""
This method builds "Rule" object configured to emit "ExpectationConfiguration" objects for column "Domain" type.
This rule holds expectations which are associated with the float metrics in the data profiler report. There
are additional rules which are planned to be created, such as timestamp_rule, text_rule, categorical_rule, etc.
Currently, the float_rule uses DataProfilerColumnDomainBuilder, so it doesn't discriminate by data type when applying the
rule.
"""
data_profiler_column_domain_builder: DomainBuilder = DataProfilerColumnDomainBuilder()
data_profiler_profile_report_metric_single_batch_parameter_builder_for_metrics: ParameterBuilder = DataAssistant.commonly_used_parameter_builders.build_metric_single_batch_parameter_builder(
metric_name="data_profiler.column_profile_report",
suffix=None,
metric_domain_kwargs=DOMAIN_KWARGS_PARAMETER_FULLY_QUALIFIED_NAME,
metric_value_kwargs={
"profile_path": f"{VARIABLES_KEY}profile_path",
},
)
data_profiler_profile_report_metric_single_batch_parameter_builder_for_validations: ParameterBuilder = data_profiler_profile_report_metric_single_batch_parameter_builder_for_metrics
validation_parameter_builder_configs: Optional[List[ParameterBuilderConfig]]
validation_parameter_builder_configs = [
ParameterBuilderConfig(
**data_profiler_profile_report_metric_single_batch_parameter_builder_for_validations.to_json_dict(),
),
]
expect_column_min_to_be_between_expectation_configuration_builder: ExpectationConfigurationBuilder = DefaultExpectationConfigurationBuilder(
expectation_type="expect_column_min_to_be_between",
validation_parameter_builder_configs=validation_parameter_builder_configs,
column=f"{DOMAIN_KWARGS_PARAMETER_FULLY_QUALIFIED_NAME}{FULLY_QUALIFIED_PARAMETER_NAME_SEPARATOR_CHARACTER}column",
min_value=f"{data_profiler_profile_report_metric_single_batch_parameter_builder_for_validations.json_serialized_fully_qualified_parameter_name}{FULLY_QUALIFIED_PARAMETER_NAME_SEPARATOR_CHARACTER}{FULLY_QUALIFIED_PARAMETER_NAME_VALUE_KEY}.statistics.precision.min",
max_value=None,
strict_min=f"{VARIABLES_KEY}strict_min",
strict_max=None,
meta={
"profiler_details": f"{data_profiler_profile_report_metric_single_batch_parameter_builder_for_validations.json_serialized_fully_qualified_parameter_name}{FULLY_QUALIFIED_PARAMETER_NAME_SEPARATOR_CHARACTER}{FULLY_QUALIFIED_PARAMETER_NAME_METADATA_KEY}",
},
)
expect_column_max_to_be_between_expectation_configuration_builder: ExpectationConfigurationBuilder = DefaultExpectationConfigurationBuilder(
expectation_type="expect_column_max_to_be_between",
validation_parameter_builder_configs=validation_parameter_builder_configs,
column=f"{DOMAIN_KWARGS_PARAMETER_FULLY_QUALIFIED_NAME}{FULLY_QUALIFIED_PARAMETER_NAME_SEPARATOR_CHARACTER}column",
min_value=None,
max_value=f"{data_profiler_profile_report_metric_single_batch_parameter_builder_for_validations.json_serialized_fully_qualified_parameter_name}{FULLY_QUALIFIED_PARAMETER_NAME_SEPARATOR_CHARACTER}{FULLY_QUALIFIED_PARAMETER_NAME_VALUE_KEY}.statistics.precision.max",
strict_min=None,
strict_max=f"{VARIABLES_KEY}strict_max",
meta={
"profiler_details": f"{data_profiler_profile_report_metric_single_batch_parameter_builder_for_validations.json_serialized_fully_qualified_parameter_name}{FULLY_QUALIFIED_PARAMETER_NAME_SEPARATOR_CHARACTER}{FULLY_QUALIFIED_PARAMETER_NAME_METADATA_KEY}",
},
)
expect_column_mean_to_be_between_expectation_configuration_builder: ExpectationConfigurationBuilder = DefaultExpectationConfigurationBuilder(
expectation_type="expect_column_mean_to_be_between",
validation_parameter_builder_configs=validation_parameter_builder_configs,
column=f"{DOMAIN_KWARGS_PARAMETER_FULLY_QUALIFIED_NAME}{FULLY_QUALIFIED_PARAMETER_NAME_SEPARATOR_CHARACTER}column",
min_value=f"{data_profiler_profile_report_metric_single_batch_parameter_builder_for_validations.json_serialized_fully_qualified_parameter_name}{FULLY_QUALIFIED_PARAMETER_NAME_SEPARATOR_CHARACTER}{FULLY_QUALIFIED_PARAMETER_NAME_VALUE_KEY}.statistics.precision.mean",
max_value=f"{data_profiler_profile_report_metric_single_batch_parameter_builder_for_validations.json_serialized_fully_qualified_parameter_name}{FULLY_QUALIFIED_PARAMETER_NAME_SEPARATOR_CHARACTER}{FULLY_QUALIFIED_PARAMETER_NAME_VALUE_KEY}.statistics.precision.mean",
strict_min=f"{VARIABLES_KEY}strict_min",
strict_max=f"{VARIABLES_KEY}strict_max",
meta={
"profiler_details": f"{data_profiler_profile_report_metric_single_batch_parameter_builder_for_validations.json_serialized_fully_qualified_parameter_name}{FULLY_QUALIFIED_PARAMETER_NAME_SEPARATOR_CHARACTER}{FULLY_QUALIFIED_PARAMETER_NAME_METADATA_KEY}",
},
)
expect_column_stddev_to_be_between_expectation_configuration_builder: ExpectationConfigurationBuilder = DefaultExpectationConfigurationBuilder(
expectation_type="expect_column_stdev_to_be_between",
validation_parameter_builder_configs=validation_parameter_builder_configs,
column=f"{DOMAIN_KWARGS_PARAMETER_FULLY_QUALIFIED_NAME}{FULLY_QUALIFIED_PARAMETER_NAME_SEPARATOR_CHARACTER}column",
min_value=f"{data_profiler_profile_report_metric_single_batch_parameter_builder_for_validations.json_serialized_fully_qualified_parameter_name}{FULLY_QUALIFIED_PARAMETER_NAME_SEPARATOR_CHARACTER}{FULLY_QUALIFIED_PARAMETER_NAME_VALUE_KEY}.statistics.precision.std",
max_value=f"{data_profiler_profile_report_metric_single_batch_parameter_builder_for_validations.json_serialized_fully_qualified_parameter_name}{FULLY_QUALIFIED_PARAMETER_NAME_SEPARATOR_CHARACTER}{FULLY_QUALIFIED_PARAMETER_NAME_VALUE_KEY}.statistics.precision.std",
strict_min=f"{VARIABLES_KEY}strict_min",
strict_max=f"{VARIABLES_KEY}strict_max",
meta={
"profiler_details": f"{data_profiler_profile_report_metric_single_batch_parameter_builder_for_validations.json_serialized_fully_qualified_parameter_name}{FULLY_QUALIFIED_PARAMETER_NAME_SEPARATOR_CHARACTER}{FULLY_QUALIFIED_PARAMETER_NAME_METADATA_KEY}",
},
)
variables: dict = {
"strict_min": False,
"strict_max": False,
"profile_path": "default_profiler_path",
"profile_report_filtering_key": "data_type",
"profile_report_accepted_filtering_values": ["float"],
}
parameter_builders: List[ParameterBuilder] = [
data_profiler_profile_report_metric_single_batch_parameter_builder_for_metrics,
]
expectation_configuration_builders: List[ExpectationConfigurationBuilder] = [
expect_column_min_to_be_between_expectation_configuration_builder,
expect_column_max_to_be_between_expectation_configuration_builder,
expect_column_mean_to_be_between_expectation_configuration_builder,
expect_column_stddev_to_be_between_expectation_configuration_builder,
]
rule = Rule(
name="float_rule",
variables=variables,
domain_builder=data_profiler_column_domain_builder,
parameter_builders=parameter_builders,
expectation_configuration_builders=expectation_configuration_builders,
)
return rule
| DataProfilerStructuredDataAssistant |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_translate.py | {
"start": 28491,
"end": 31046
} | class ____:
@mock.patch("airflow.providers.google.cloud.operators.translate.TranslateHook")
def test_minimal_green_path(self, mock_hook):
GLOSSARY_CREATION_RESULT = {
"name": f"projects/{PROJECT_ID}/locations/{LOCATION}/glossaries/{GLOSSARY_ID}",
"display_name": f"{GLOSSARY_ID}",
"entry_count": 42,
"input_config": {"gcs_source": {"input_uri": "gs://input_bucket_path/glossary.csv"}},
"language_pair": {"source_language_code": "en", "target_language_code": "es"},
"submit_time": "2024-11-17T14:05:00Z",
"end_time": "2024-11-17T17:09:03Z",
}
sample_operation = mock.MagicMock()
sample_operation.result.return_value = translation_service.Glossary(GLOSSARY_CREATION_RESULT)
mock_hook.return_value.create_glossary.return_value = sample_operation
mock_hook.return_value.wait_for_operation_result.side_effect = lambda operation: operation.result()
mock_hook.return_value.extract_object_id = TranslateHook.extract_object_id
GLOSSARY_FILE_INPUT = {"gcs_source": {"input_uri": "gs://RESOURCE_BUCKET/glossary_sample.tsv"}}
op = TranslateCreateGlossaryOperator(
task_id="task_id",
glossary_id=f"{GLOSSARY_ID}",
input_config=GLOSSARY_FILE_INPUT,
language_pair={"source_language_code": "en", "target_language_code": "es"},
language_codes_set=None,
project_id=PROJECT_ID,
location=LOCATION,
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
timeout=TIMEOUT_VALUE,
retry=None,
)
mock_ti = mock.MagicMock()
mock_context = {"ti": mock_ti}
result = op.execute(context=mock_context)
mock_hook.assert_called_once_with(
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
)
mock_hook.return_value.create_glossary.assert_called_once_with(
glossary_id=f"{GLOSSARY_ID}",
input_config=GLOSSARY_FILE_INPUT,
language_pair={"source_language_code": "en", "target_language_code": "es"},
language_codes_set=None,
project_id=PROJECT_ID,
location=LOCATION,
timeout=TIMEOUT_VALUE,
retry=None,
metadata=(),
)
mock_ti.xcom_push.assert_any_call(key="glossary_id", value=GLOSSARY_ID)
assert result == GLOSSARY_CREATION_RESULT
| TestTranslateGlossaryCreate |
python | getsentry__sentry | src/sentry/explore/models.py | {
"start": 1199,
"end": 1606
} | class ____(Model):
__relocation_scope__ = RelocationScope.Organization
project = FlexibleForeignKey("sentry.Project")
explore_saved_query = FlexibleForeignKey("explore.ExploreSavedQuery")
class Meta:
app_label = "explore"
db_table = "explore_exploresavedqueryproject"
unique_together = (("project", "explore_saved_query"),)
@region_silo_model
| ExploreSavedQueryProject |
python | airbytehq__airbyte | airbyte-integrations/bases/connector-acceptance-test/connector_acceptance_test/utils/backward_compatibility.py | {
"start": 5321,
"end": 11894
} | class ____(BaseDiffChecker):
"""A class to perform backward compatibility checks on a connector specification diff"""
context = BackwardIncompatibilityContext.SPEC
def compute_diffs(self):
self.connection_specification_diff = DeepDiff(
self._previous["connectionSpecification"],
self._current["connectionSpecification"],
view="tree",
ignore_order=True,
)
def assert_is_backward_compatible(self):
self.check_if_declared_new_required_field(self.connection_specification_diff)
self.check_if_added_a_new_required_property(self.connection_specification_diff)
self.check_if_value_of_a_field_changed(self.connection_specification_diff, "type")
self.check_if_value_of_a_field_changed(self.connection_specification_diff, "airbyte_type")
self.check_if_value_of_a_field_changed(self.connection_specification_diff, "format")
# self.check_if_new_type_was_added(self.connection_specification_diff) We want to allow type expansion atm
self.check_if_type_of_type_field_changed(self.connection_specification_diff, allow_type_widening=True)
self.check_if_field_was_made_not_nullable(self.connection_specification_diff)
self.check_if_enum_was_narrowed(self.connection_specification_diff)
self.check_if_declared_new_enum_field(self.connection_specification_diff)
def check_if_declared_new_required_field(self, diff: DeepDiff):
"""Check if the new spec declared a 'required' field."""
added_required_fields = [
addition for addition in diff.get("dictionary_item_added", []) if addition.path(output_format="list")[-1] == "required"
]
if added_required_fields:
self._raise_error("A new 'required' field was declared.", diff)
def check_if_added_a_new_required_property(self, diff: DeepDiff):
"""Check if the new spec added a property to the 'required' list"""
added_required_properties = [
addition for addition in diff.get("iterable_item_added", []) if addition.up.path(output_format="list")[-1] == "required"
]
if added_required_properties:
self._raise_error("A new property was added to 'required'", diff)
def check_if_field_was_made_not_nullable(self, diff: DeepDiff):
"""Detect when field was made not nullable but is still a list: e.g ["string", "null"] -> ["string"]"""
removed_nullable = [
change for change in diff.get("iterable_item_removed", []) if {"properties", "type"}.issubset(change.path(output_format="list"))
]
if removed_nullable:
self._raise_error("A field type was narrowed or made a field not nullable", diff)
def check_if_enum_was_narrowed(self, diff: DeepDiff):
"""Check if the list of values in a enum was shortened in a spec."""
enum_removals = [
enum_removal
for enum_removal in diff.get("iterable_item_removed", [])
if enum_removal.up.path(output_format="list")[-1] == "enum"
]
if enum_removals:
self._raise_error("An enum field was narrowed.", diff)
def check_if_declared_new_enum_field(self, diff: DeepDiff):
"""Check if an 'enum' field was added to the spec."""
enum_additions = [
enum_addition
for enum_addition in diff.get("dictionary_item_added", [])
if enum_addition.path(output_format="list")[-1] == "enum"
]
if enum_additions:
self._raise_error("An 'enum' field was declared on an existing property", diff)
def remove_date_time_pattern_format(schema: Dict[str, Any]) -> Dict[str, Any]:
"""
This function traverses a JSON schema and removes the 'format' field for properties
that are of 'date-time' format and have a 'pattern' field.
The 'pattern' is often more restrictive than the 'date-time' format, and Hypothesis can't natively generate
date-times that match a specific pattern. Therefore, in this case, we've opted to
remove the 'date-time' format since the 'pattern' is more restrictive and more likely
to cause a breaking change if not adhered to.
On the otherside we also validate the output of hypothesis against the new schema to ensure
that the generated data matches the new schema. In this case we will catch whether or not the
date-time format is still being adhered to.
Args:
schema (Dict[str, Any]): The JSON schema to be processed.
Returns:
Dict[str, Any]: The processed JSON schema where 'date-time' format has been removed
for properties that have a 'pattern'.
"""
if isinstance(schema, dict):
for key, value in schema.items():
if isinstance(value, dict):
if value.get("format") == "date-time" and "pattern" in value:
del value["format"]
remove_date_time_pattern_format(value)
return schema
def validate_previous_configs(
previous_connector_spec: ConnectorSpecification, actual_connector_spec: ConnectorSpecification, number_of_configs_to_generate=100
):
"""Use hypothesis and hypothesis-jsonschema to run property based testing:
1. Generate fake previous config with the previous connector specification json schema.
2. Validate a fake previous config against the actual connector specification json schema."""
prev_con_spec = previous_connector_spec.dict()["connectionSpecification"]
@given(from_schema(remove_date_time_pattern_format(prev_con_spec)))
@settings(
max_examples=number_of_configs_to_generate,
verbosity=Verbosity.verbose,
suppress_health_check=(HealthCheck.too_slow, HealthCheck.filter_too_much),
)
def check_fake_previous_config_against_actual_spec(fake_previous_config):
if isinstance(fake_previous_config, dict): # Looks like hypothesis-jsonschema not only generate dict objects...
fake_previous_config = SecretDict(fake_previous_config)
filtered_fake_previous_config = {key: value for key, value in fake_previous_config.data.items() if not key.startswith("_")}
try:
jsonschema.validate(instance=filtered_fake_previous_config, schema=actual_connector_spec.connectionSpecification)
except jsonschema.exceptions.ValidationError as err:
raise NonBackwardCompatibleError(err, BackwardIncompatibilityContext.SPEC)
check_fake_previous_config_against_actual_spec()
| SpecDiffChecker |
python | scipy__scipy | scipy/io/arff/tests/test_arffread.py | {
"start": 2866,
"end": 3057
} | class ____:
def test_missing(self):
data, meta = loadarff(missing)
for i in ['yop', 'yap']:
assert_array_almost_equal(data[i], expect_missing[i])
| TestMissingData |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/types/python_set.py | {
"start": 428,
"end": 1080
} | class ____(DagsterTypeLoader):
def __init__(self, item_dagster_type):
self._item_dagster_type = check.inst_param(
item_dagster_type, "item_dagster_type", DagsterType
)
@property
def schema_type(self):
return Array(self._item_dagster_type.loader.schema_type)
def construct_from_config_value(self, context, config_value):
runtime_value = set()
for item in config_value:
runtime_value.add(
self._item_dagster_type.loader.construct_from_config_value(
context, item
)
)
return runtime_value
| TypedSetLoader |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/call2.py | {
"start": 1504,
"end": 2958
} | class ____(str): ...
kwargs2: dict[MyStr, MyStr] = {}
func8(z=False, **kwargs2)
def func9(
x: int,
y: str,
*,
a: str = ...,
b: str,
c: str,
) -> None: ...
kwargs3: dict[str, str] = {}
func9(0, "", **kwargs3)
args4: list[str] = ["hi"]
func9(0, *args4, **kwargs3)
# This should generate an error.
func9(*args4, **kwargs3)
def func10(x: int): ...
func10(1, *())
# This should generate an error.
func10(1, *(1,))
func10(*(1,))
# This should generate an error.
func10(*(1, 1))
# This should generate an error.
func10(*("",))
def func11(y: tuple[int, ...]):
func10(1, *y)
def func12(x: int, /, y: str):
pass
# This should generate an error.
func12(1, **{"z": None})
def func13(*, a: str, b: str, c: int | None = None):
...
func_args1: dict[Literal["a", "b", "d"], str] = {
"a": "a",
"b": "b",
"d": "d",
}
func13(**func_args1)
func_args2: dict[Literal["a", "b", "c"], str] = {
"a": "a",
"b": "b",
"c": "c",
}
# This should generate an error.
func13(**func_args2)
def func14(cb1: Callable[..., Any], cb2: Any, x: None):
cb1(**x) # This should generate an error
cb2(**x) # This should generate an error
def func15(cb1: Callable[..., Any], cb2: Any, a: int, b: None | str):
print(*a) # This should generate an error
print(*b) # This should generate an error
cb1(*a) # This should generate an error
cb2(*b) # This should generate an error
| MyStr |
python | Textualize__textual | src/textual/getters.py | {
"start": 547,
"end": 1801
} | class ____(Generic[AppType]):
"""Create a property to return the active app.
All widgets have a default `app` property which returns an App instance.
Type checkers will complain if you try to access attributes defined on your App class, which aren't
present in the base class. To keep the type checker happy you can add this property to get your
specific App subclass.
Example:
```python
class MyWidget(Widget):
app = getters.app(MyApp)
```
Args:
app_type: The App subclass, or a callable which returns an App subclass.
"""
def __init__(self, app_type: type[AppType] | Callable[[], type[AppType]]) -> None:
self._app_type = app_type if isclass(app_type) else app_type()
def __get__(self, obj: MessagePump, obj_type: type[MessagePump]) -> AppType:
try:
app = active_app.get()
except LookupError:
from textual.app import App
node: MessagePump | None = obj
while not isinstance(node, App):
if node is None:
raise NoActiveAppError()
node = node._parent
app = node
assert isinstance(app, self._app_type)
return app
| app |
python | streamlit__streamlit | lib/tests/streamlit/net_util_test.py | {
"start": 741,
"end": 2430
} | class ____(unittest.TestCase):
def setUp(self):
net_util._external_ip = None
def test_get_external_ip(self):
# Test success
with requests_mock.mock() as m:
m.get(net_util._AWS_CHECK_IP, text="1.2.3.4")
assert net_util.get_external_ip() == "1.2.3.4"
net_util._external_ip = None
# Test failure
with requests_mock.mock() as m:
m.get(net_util._AWS_CHECK_IP, exc=requests.exceptions.ConnectTimeout)
assert None is net_util.get_external_ip()
def test_get_external_ip_use_http_by_default(self):
with requests_mock.mock() as m:
m.get(net_util._AWS_CHECK_IP, text="1.2.3.4")
m.get(net_util._AWS_CHECK_IP_HTTPS, text="5.6.7.8")
assert net_util.get_external_ip() == "1.2.3.4"
assert m.call_count == 1
def test_get_external_ip_https_if_http_fails(self):
with requests_mock.mock() as m:
m.get(net_util._AWS_CHECK_IP, exc=requests.exceptions.ConnectTimeout)
m.get(net_util._AWS_CHECK_IP_HTTPS, text="5.6.7.8")
assert net_util.get_external_ip() == "5.6.7.8"
assert m.call_count == 2
def test_get_external_ip_html(self):
# This tests the case where the external URL returns a web page.
# https://github.com/streamlit/streamlit/issues/554#issuecomment-604847244
response_text = """
<html>
... stuff
</html>
"""
with requests_mock.mock() as m:
m.get(net_util._AWS_CHECK_IP, text=response_text)
assert None is net_util.get_external_ip()
net_util._external_ip = None
| UtilTest |
python | plotly__plotly.py | _plotly_utils/exceptions.py | {
"start": 2111,
"end": 2640
} | class ____(PlotlyGraphObjectError):
def __init__(self, obj, path, notes=()):
"""See PlotlyGraphObjectError.__init__ for param docs."""
format_dict = {"index": path[-1], "object_name": obj._name}
message = "Invalid entry found in '{object_name}' at index, '{index}'".format(
**format_dict
)
notes = [obj.help(return_help=True)] + list(notes)
super(PlotlyListEntryError, self).__init__(
message=message, path=path, notes=notes
)
| PlotlyListEntryError |
python | tensorflow__tensorflow | tensorflow/python/data/experimental/kernel_tests/service/test_base.py | {
"start": 15997,
"end": 16460
} | class ____:
"""Temporary directory for unit testing."""
def __init__(self):
temp_dir = tempfile.mkdtemp(dir=googletest.GetTempDir())
self._path = os.path.join(
tempfile.mkdtemp(dir=temp_dir), "tf_data_snapshot")
@property
def full_path(self) -> str:
return self._path
def __fspath__(self) -> str:
return self._path
def __del__(self):
try:
shutil.rmtree(self.full_path)
except FileNotFoundError:
pass
| TempDir |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/run_status_sensor_definition.py | {
"start": 3595,
"end": 5129
} | class ____(
NamedTuple(
"_RunStatusSensorCursor",
[
("record_id", int),
# deprecated arg, used as a record cursor for the run-sharded sqlite implementation to
# filter records based on the update timestamp of the run. When populated, the record
# id is ignored (since it maybe run-scoped).
("update_timestamp", Optional[str]),
# debug arg, used to quickly inspect the last processed timestamp from the run status
# sensor's serialized state
("record_timestamp", Optional[str]),
],
)
):
def __new__(cls, record_id, update_timestamp=None, record_timestamp=None):
return super().__new__(
cls,
record_id=check.int_param(record_id, "record_id"),
update_timestamp=check.opt_str_param(update_timestamp, "update_timestamp"),
record_timestamp=check.opt_str_param(record_timestamp, "record_timestamp"),
)
@staticmethod
def is_valid(json_str: str) -> bool:
try:
obj = deserialize_value(json_str, RunStatusSensorCursor)
return isinstance(obj, RunStatusSensorCursor)
except (JSONDecodeError, DeserializationError):
return False
def to_json(self) -> str:
return serialize_value(cast("NamedTuple", self))
@staticmethod
def from_json(json_str: str) -> "RunStatusSensorCursor":
return deserialize_value(json_str, RunStatusSensorCursor)
@public
| RunStatusSensorCursor |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 40353,
"end": 40547
} | class ____(sgqlc.types.Enum):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__choices__ = ("BLANK", "COMMIT_MESSAGES", "PR_BODY")
| SquashMergeCommitMessage |
python | django__django | django/db/models/expressions.py | {
"start": 42372,
"end": 43588
} | class ____(Expression):
allowed_default = True
def __init__(self, sql, params, output_field=None):
if output_field is None:
output_field = fields.Field()
self.sql, self.params = sql, params
super().__init__(output_field=output_field)
def __repr__(self):
return "{}({}, {})".format(self.__class__.__name__, self.sql, self.params)
def as_sql(self, compiler, connection):
return "(%s)" % self.sql, self.params
def get_group_by_cols(self):
return [self]
def resolve_expression(
self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False
):
# Resolve parents fields used in raw SQL.
if query.model:
for parent in query.model._meta.all_parents:
for parent_field in parent._meta.local_fields:
if parent_field.column.lower() in self.sql.lower():
query.resolve_ref(
parent_field.name, allow_joins, reuse, summarize
)
break
return super().resolve_expression(
query, allow_joins, reuse, summarize, for_save
)
| RawSQL |
python | numba__numba | numba/core/typing/templates.py | {
"start": 48639,
"end": 49513
} | class ____(object):
"""
An incremental loader for a registry. Each new call to
new_registrations() will iterate over the not yet seen registrations.
The reason for this object is multiple:
- there can be several contexts
- each context wants to install all registrations
- registrations can be added after the first installation, so contexts
must be able to get the "new" installations
Therefore each context maintains its own loaders for each existing
registry, without duplicating the registries themselves.
"""
def __init__(self, registry):
self._registrations = dict(
(name, utils.stream_list(getattr(registry, name)))
for name in self.registry_items)
def new_registrations(self, name):
for item in next(self._registrations[name]):
yield item
| BaseRegistryLoader |
python | dask__distributed | distributed/http/scheduler/info.py | {
"start": 1343,
"end": 1953
} | class ____(RequestHandler):
@log_errors
def get(self, worker):
worker = escape.url_unescape(worker)
if worker not in self.server.workers:
self.send_error(404)
return
self.render(
"worker.html",
title="Worker: " + worker,
scheduler=self.server,
api_enabled=API_ENABLED,
Worker=worker,
**merge(
self.server.__dict__,
self.server.__pdict__,
ns,
self.extra,
rel_path_statics,
),
)
| Worker |
python | jazzband__tablib | tests/test_tablib.py | {
"start": 66445,
"end": 67028
} | class ____(BaseTestCase):
def test_jira_export(self):
expected = """||first_name||last_name||gpa||
|John|Adams|90|
|George|Washington|67|
|Thomas|Jefferson|50|"""
self.assertEqual(expected, self.founders.jira)
def test_jira_export_no_headers(self):
self.assertEqual('|a|b|c|', tablib.Dataset(['a', 'b', 'c']).jira)
def test_jira_export_none_and_empty_values(self):
self.assertEqual('| | |c|', tablib.Dataset(['', None, 'c']).jira)
def test_jira_export_empty_dataset(self):
self.assertIsNotNone(tablib.Dataset().jira)
| JiraTests |
python | pypa__warehouse | tests/common/db/oidc.py | {
"start": 406,
"end": 802
} | class ____(WarehouseFactory):
class Meta:
model = GitHubPublisher
id = factory.Faker("uuid4", cast_to=None)
repository_name = factory.Faker("pystr", max_chars=12)
repository_owner = factory.Faker("pystr", max_chars=12)
repository_owner_id = factory.Faker("pystr", max_chars=12)
workflow_filename = "example.yml"
environment = "production"
| GitHubPublisherFactory |
python | huggingface__transformers | src/transformers/models/llava_next_video/modular_llava_next_video.py | {
"start": 7992,
"end": 9142
} | class ____(LlavaNextModelOutputWithPast):
r"""
past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
`past_key_values` input) to speed up sequential decoding.
image_hidden_states (`torch.FloatTensor`, *optional*):
A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
video_hidden_states (`torch.FloatTensor`, *optional*):
A `torch.FloatTensor` of size `(batch_size * num_frames, num_videos, sequence_length, hidden_size)`.
video_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
"""
video_hidden_states: Optional[torch.FloatTensor] = None
| LlavaNextVideoModelOutputWithPast |
python | huggingface__transformers | src/transformers/models/vit_mae/modeling_vit_mae.py | {
"start": 14637,
"end": 17028
} | class ____(nn.Module):
def __init__(self, config: ViTMAEConfig):
super().__init__()
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
raise ValueError(
f"The hidden size {config.hidden_size} is not a multiple of the number of attention "
f"heads {config.num_attention_heads}."
)
self.config = config
self.num_attention_heads = config.num_attention_heads
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
self.all_head_size = self.num_attention_heads * self.attention_head_size
self.dropout_prob = config.attention_probs_dropout_prob
self.scaling = self.attention_head_size**-0.5
self.is_causal = False
self.query = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
self.key = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
self.value = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
batch_size = hidden_states.shape[0]
new_shape = batch_size, -1, self.num_attention_heads, self.attention_head_size
key_layer = self.key(hidden_states).view(*new_shape).transpose(1, 2)
value_layer = self.value(hidden_states).view(*new_shape).transpose(1, 2)
query_layer = self.query(hidden_states).view(*new_shape).transpose(1, 2)
attention_interface: Callable = eager_attention_forward
if self.config._attn_implementation != "eager":
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
context_layer, attention_probs = attention_interface(
self,
query_layer,
key_layer,
value_layer,
None,
is_causal=self.is_causal,
scaling=self.scaling,
dropout=0.0 if not self.training else self.dropout_prob,
)
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
context_layer = context_layer.reshape(new_context_layer_shape)
return context_layer, attention_probs
# Copied from transformers.models.vit.modeling_vit.ViTSelfOutput with ViT->ViTMAE
| ViTMAESelfAttention |
python | getsentry__sentry | src/sentry/api/bases/organizationmember.py | {
"start": 2820,
"end": 4642
} | class ____(OrganizationEndpoint):
def convert_args(
self,
request: Request,
organization_id_or_slug: str | int | None = None,
member_id: str = "me",
*args: Any,
**kwargs: Any,
) -> tuple[tuple[Any, ...], dict[str, Any]]:
args, kwargs = super().convert_args(request, organization_id_or_slug, *args, **kwargs)
serializer = MemberSerializer(data={"id": member_id})
if request.user.is_authenticated and serializer.is_valid():
result = serializer.validated_data
try:
kwargs["member"] = self._get_member(
request.user, kwargs["organization"], result["id"]
)
except OrganizationMember.DoesNotExist:
raise ResourceDoesNotExist
return args, kwargs
else:
raise ResourceDoesNotExist
def _get_member(
self,
request_user: User,
organization: Organization,
member_id: int | Literal["me"],
invite_status: InviteStatus | None = None,
) -> OrganizationMember:
kwargs: _FilterKwargs = {"organization": organization}
if member_id == "me":
kwargs["user_id"] = request_user.id
kwargs["user_is_active"] = True
else:
kwargs["id"] = member_id
kwargs["organization_id"] = organization.id
if invite_status:
kwargs["invite_status"] = invite_status.value
om_id = kwargs.get("id")
if isinstance(om_id, int):
invite = OrganizationMemberInvite.objects.filter(organization_member_id=om_id).first()
if invite is not None:
raise ResourceDoesNotExist
return OrganizationMember.objects.filter(**kwargs).get()
| OrganizationMemberEndpoint |
python | django-guardian__django-guardian | guardian/testapp/migrations/0001_initial.py | {
"start": 291,
"end": 10120
} | class ____(migrations.Migration):
initial = True
dependencies = [
("auth", "0001_initial"),
]
operations = [
migrations.CreateModel(
name="CustomUser",
fields=[
("password", models.CharField(max_length=128, verbose_name="password")),
("last_login", models.DateTimeField(blank=True, null=True, verbose_name="last login")),
(
"is_superuser",
models.BooleanField(
default=False,
help_text="Designates that this user has all permissions without explicitly assigning them.",
verbose_name="superuser status",
),
),
(
"username",
models.CharField(
error_messages={"unique": "A user with that username already exists."},
help_text="Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only.",
max_length=30,
unique=True,
validators=[
django.core.validators.RegexValidator(
"^[\\w.@+-]+$",
"Enter a valid username. This value may contain only letters, numbers and @/./+/-/_ characters.",
)
],
verbose_name="username",
),
),
("first_name", models.CharField(blank=True, max_length=30, verbose_name="first name")),
("last_name", models.CharField(blank=True, max_length=30, verbose_name="last name")),
("email", models.EmailField(blank=True, max_length=254, verbose_name="email address")),
(
"is_staff",
models.BooleanField(
default=False,
help_text="Designates whether the user can log into this admin site.",
verbose_name="staff status",
),
),
(
"is_active",
models.BooleanField(
default=True,
help_text="Designates whether this user should be treated as active. Unselect this instead of deleting accounts.",
verbose_name="active",
),
),
("date_joined", models.DateTimeField(default=django.utils.timezone.now, verbose_name="date joined")),
("custom_id", models.AutoField(primary_key=True, serialize=False)),
(
"groups",
models.ManyToManyField(
blank=True,
help_text="The groups this user belongs to. A user will get all permissions granted to each of their groups.",
related_name="user_set",
related_query_name="user",
to="auth.Group",
verbose_name="groups",
),
),
(
"user_permissions",
models.ManyToManyField(
blank=True,
help_text="Specific permissions for this user.",
related_name="user_set",
related_query_name="user",
to="auth.Permission",
verbose_name="user permissions",
),
),
],
options={
"abstract": False,
"verbose_name": "user",
"verbose_name_plural": "users",
},
bases=(models.Model, guardian.mixins.GuardianUserMixin),
managers=[
("objects", django.contrib.auth.models.UserManager()),
],
),
migrations.CreateModel(
name="CustomUsernameUser",
fields=[
("id", models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
("password", models.CharField(max_length=128, verbose_name="password")),
("last_login", models.DateTimeField(blank=True, null=True, verbose_name="last login")),
("email", models.EmailField(max_length=100, unique=True)),
],
options={
"abstract": False,
},
bases=(models.Model, guardian.mixins.GuardianUserMixin),
),
migrations.CreateModel(
name="Mixed",
fields=[
("id", models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
("name", models.CharField(max_length=128, unique=True)),
],
),
migrations.CreateModel(
name="MixedGroupObjectPermission",
fields=[
("id", models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
("content_object", models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="testapp.Mixed")),
("group", models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="auth.Group")),
("permission", models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="auth.Permission")),
],
options={
"abstract": False,
},
),
migrations.CreateModel(
name="CharPKModel",
fields=[
("char_pk", models.CharField(max_length=128, primary_key=True, serialize=False)),
],
),
migrations.CreateModel(
name="Post",
fields=[
("id", models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
("title", models.CharField(max_length=64, verbose_name="title")),
],
),
migrations.CreateModel(
name="Project",
fields=[
("id", models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
("name", models.CharField(max_length=128, unique=True)),
("created_at", models.DateTimeField(default=datetime.datetime.now)),
],
options={
"get_latest_by": "created_at",
},
),
migrations.CreateModel(
name="ProjectGroupObjectPermission",
fields=[
("id", models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
(
"content_object",
models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="testapp.Project"),
),
("group", models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="auth.Group")),
("permission", models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="auth.Permission")),
],
options={
"abstract": False,
},
),
migrations.CreateModel(
name="ProjectUserObjectPermission",
fields=[
("id", models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
(
"content_object",
models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="testapp.Project"),
),
("permission", models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="auth.Permission")),
("user", models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
"abstract": False,
},
),
migrations.CreateModel(
name="ReverseMixed",
fields=[
("id", models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
("name", models.CharField(max_length=128, unique=True)),
],
),
migrations.CreateModel(
name="ReverseMixedUserObjectPermission",
fields=[
("id", models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
(
"content_object",
models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="testapp.ReverseMixed"),
),
("permission", models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="auth.Permission")),
("user", models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
"abstract": False,
},
),
migrations.AlterUniqueTogether(
name="reversemixeduserobjectpermission",
unique_together={("user", "permission", "content_object")},
),
migrations.AlterUniqueTogether(
name="projectuserobjectpermission",
unique_together={("user", "permission", "content_object")},
),
migrations.AlterUniqueTogether(
name="projectgroupobjectpermission",
unique_together={("group", "permission", "content_object")},
),
migrations.AlterUniqueTogether(
name="mixedgroupobjectpermission",
unique_together={("group", "permission", "content_object")},
),
]
| Migration |
python | mlflow__mlflow | mlflow/types/llm.py | {
"start": 11019,
"end": 12021
} | class ____(_BaseDataclass):
"""
A tool parameter definition.
Args:
properties (Dict[str, :py:class:`ParamProperty`]): A mapping of parameter names to
their definitions.
type (str): The type of the parameter. Currently only "object" is supported.
required (List[str]): A list of required parameter names. **Optional**, defaults to ``None``
additionalProperties (bool): Whether additional properties are allowed in the object.
**Optional**, defaults to ``None``
"""
properties: dict[str, ParamProperty]
type: Literal["object"] = "object"
required: list[str] | None = None
additionalProperties: bool | None = None
def __post_init__(self):
self._convert_dataclass_map("properties", ParamProperty, True)
self._validate_literal("type", ["object"], True)
self._validate_list("required", str, False)
self._validate_field("additionalProperties", bool, False)
@dataclass
| ToolParamsSchema |
python | getsentry__sentry | src/sentry/seer/models.py | {
"start": 1061,
"end": 1148
} | class ____(BaseModel):
explanation: str
span_id: str
span_op: str
| SpanInsight |
python | pennersr__django-allauth | allauth/socialaccount/providers/instagram/provider.py | {
"start": 225,
"end": 417
} | class ____(ProviderAccount):
PROFILE_URL = "https://instagram.com/"
def get_profile_url(self):
return self.PROFILE_URL + self.account.extra_data.get("username")
| InstagramAccount |
python | automl__auto-sklearn | autosklearn/pipeline/components/feature_preprocessing/kitchen_sinks.py | {
"start": 462,
"end": 2777
} | class ____(AutoSklearnPreprocessingAlgorithm):
def __init__(
self,
gamma: float,
n_components: int,
random_state: Optional[Union[int, RandomState]] = None,
) -> None:
"""
Parameters
----------
gamma: float
Parameter of the rbf kernel to be approximated exp(-gamma * x^2)
n_components: int
Number of components (output dimensionality) used to approximate the kernel
random_state: Optional[int | RandomState]
The random state to pass to the underlying estimator
"""
self.gamma = gamma
self.n_components = n_components
self.random_state = random_state
def fit(self, X, Y=None):
import sklearn.kernel_approximation
self.n_components = int(self.n_components)
self.gamma = float(self.gamma)
self.preprocessor = sklearn.kernel_approximation.RBFSampler(
gamma=self.gamma,
n_components=self.n_components,
random_state=self.random_state,
)
self.preprocessor.fit(X)
return self
def transform(self, X):
if self.preprocessor is None:
raise NotImplementedError()
return self.preprocessor.transform(X)
@staticmethod
def get_properties(dataset_properties=None):
return {
"shortname": "KitchenSink",
"name": "Random Kitchen Sinks",
"handles_regression": True,
"handles_classification": True,
"handles_multiclass": True,
"handles_multilabel": True,
"handles_multioutput": True,
"is_deterministic": True,
"input": (SPARSE, DENSE, UNSIGNED_DATA),
"output": (INPUT, UNSIGNED_DATA),
}
@staticmethod
def get_hyperparameter_search_space(
feat_type: Optional[FEAT_TYPE_TYPE] = None, dataset_properties=None
):
gamma = UniformFloatHyperparameter(
"gamma", 3.0517578125e-05, 8, default_value=1.0, log=True
)
n_components = UniformIntegerHyperparameter(
"n_components", 50, 10000, default_value=100, log=True
)
cs = ConfigurationSpace()
cs.add_hyperparameters([gamma, n_components])
return cs
| RandomKitchenSinks |
python | huggingface__transformers | tests/models/audioflamingo3/test_modeling_audioflamingo3.py | {
"start": 1280,
"end": 5355
} | class ____:
"""
Builds a tiny AudioFlamingo3 config and synthetic inputs that respect AF3's
post-pool token accounting: num <sound> tokens per sample == post-pool frame count.
"""
def __init__(
self,
parent,
audio_token_id=0,
seq_length=25,
feat_seq_length=60,
text_config=None,
audio_config=None,
is_training=True,
):
self.parent = parent
self.audio_token_id = audio_token_id
self.seq_length = seq_length
self.feat_seq_length = feat_seq_length
self.is_training = is_training
# Small text backbone (Qwen2-ish)
if text_config is None:
text_config = {
"model_type": "qwen2",
"intermediate_size": 36,
"initializer_range": 0.02,
"hidden_size": 32,
"max_position_embeddings": 52,
"num_hidden_layers": 2,
"num_attention_heads": 4,
"num_key_value_heads": 2,
"use_labels": True,
"use_mrope": False,
"vocab_size": 99,
"pad_token_id": 1, # Ensure pad token != audio token
}
# Small audio encoder (AF3 Whisper-style)
if audio_config is None:
audio_config = {
"model_type": "audioflamingo3_encoder",
"hidden_size": 16,
"num_attention_heads": 4,
"intermediate_size": 16,
"num_hidden_layers": 2,
"num_mel_bins": 80,
"max_source_positions": 30,
"initializer_range": 0.02,
}
self.text_config = text_config
self.audio_config = audio_config
self.batch_size = 3
self.vocab_size = text_config["vocab_size"]
self.hidden_size = text_config["hidden_size"]
self.num_attention_heads = text_config["num_attention_heads"]
self.num_hidden_layers = text_config["num_hidden_layers"]
self.encoder_seq_length = seq_length
def get_config(self):
return AudioFlamingo3Config(
text_config=self.text_config,
audio_config=self.audio_config,
audio_token_id=self.audio_token_id,
)
def prepare_config_and_inputs(self):
# (#windows == batch_size, n_mels, T_mel)
input_features_values = floats_tensor(
[self.batch_size, self.audio_config["num_mel_bins"], self.feat_seq_length]
)
config = self.get_config()
# Per-window mel validity (all ones => full length)
input_features_mask = torch.ones([self.batch_size, self.feat_seq_length], dtype=torch.bool).to(torch_device)
return config, input_features_values, input_features_mask
def _post_pool_tokens_per_window(self, T_mel):
# Mirror AF3 processor math:
pre = (T_mel - 1) // 2 + 1
post = (pre - 2) // 2 + 1
return post
def prepare_config_and_inputs_for_common(self):
config, input_features_values, input_features_mask = self.prepare_config_and_inputs()
# Every window has same T_mel here
num_audio_tokens_per_sample = self._post_pool_tokens_per_window(input_features_values.shape[-1])
# Build token ids with valid range and K <sound> tokens
input_ids = ids_tensor([self.batch_size, self.seq_length], config.text_config.vocab_size - 2) + 2
attention_mask = torch.ones_like(input_ids, dtype=torch.long, device=torch_device)
attention_mask[:, :1] = 0 # left padding sentinel
# Fill first K positions (after padding) with the audio token id, for each sample
input_ids[:, 1 : 1 + num_audio_tokens_per_sample] = config.audio_token_id
inputs_dict = {
"input_features": input_features_values,
"input_features_mask": input_features_mask,
"input_ids": input_ids,
"attention_mask": attention_mask,
}
return config, inputs_dict
@require_torch
| AudioFlamingo3ModelTester |
python | streamlit__streamlit | lib/tests/streamlit/elements/checkbox_test.py | {
"start": 1191,
"end": 13701
} | class ____(DeltaGeneratorTestCase):
"""Test ability to marshall checkbox protos."""
def test_just_label(self):
"""Test that it can be called with no value."""
st.checkbox("the label")
c = self.get_delta_from_queue().new_element.checkbox
assert c.label == "the label"
assert not c.default
assert not c.disabled
assert (
c.label_visibility.value
== LabelVisibilityMessage.LabelVisibilityOptions.VISIBLE
)
assert c.type == CheckboxProto.StyleType.DEFAULT
def test_just_disabled(self):
"""Test that it can be called with disabled param."""
st.checkbox("the label", disabled=True)
c = self.get_delta_from_queue(0).new_element.checkbox
assert c.disabled
@parameterized.expand(
[
("some str", True),
(123, True),
(0, False),
(None, False),
({}, False),
(SomeObj(), True),
]
)
def test_value_types(self, arg_value, proto_value):
"""Test that it supports different types of values."""
st.checkbox("the label", arg_value)
c = self.get_delta_from_queue().new_element.checkbox
assert c.label == "the label"
assert c.default == proto_value
def test_outside_form(self):
"""Test that form id is marshalled correctly outside of a form."""
st.checkbox("foo")
proto = self.get_delta_from_queue().new_element.checkbox
assert proto.form_id == ""
@patch("streamlit.runtime.Runtime.exists", MagicMock(return_value=True))
def test_inside_form(self):
"""Test that form id is marshalled correctly inside of a form."""
with st.form("form"):
st.checkbox("foo")
# 2 elements will be created: a block and a checkbox
assert len(self.get_all_deltas_from_queue()) == 2
form_proto = self.get_delta_from_queue(0).add_block.form
checkbox_proto = self.get_delta_from_queue(1).new_element.checkbox
assert checkbox_proto.form_id == form_proto.form_id
def test_checkbox_help_dedents(self):
"""Test that the checkbox help properly dedents in order to avoid code blocks"""
st.checkbox(
"Checkbox label",
value=True,
help="""\
hello
world
""",
)
c = self.get_delta_from_queue(0).new_element.checkbox
assert c.label == "Checkbox label"
assert c.default
assert c.help == "hello\n world\n"
@parameterized.expand(
[
("visible", LabelVisibilityMessage.LabelVisibilityOptions.VISIBLE),
("hidden", LabelVisibilityMessage.LabelVisibilityOptions.HIDDEN),
("collapsed", LabelVisibilityMessage.LabelVisibilityOptions.COLLAPSED),
]
)
def test_label_visibility(self, label_visibility_value, proto_value):
"""Test that it can be called with label_visibility param."""
st.checkbox("the label", label_visibility=label_visibility_value)
c = self.get_delta_from_queue().new_element.checkbox
assert c.label == "the label"
assert c.label_visibility.value == proto_value
def test_label_visibility_wrong_value(self):
with pytest.raises(StreamlitAPIException) as e:
st.checkbox("the label", label_visibility="wrong_value")
assert (
str(e.value)
== "Unsupported label_visibility option 'wrong_value'. Valid values are 'visible', 'hidden' or 'collapsed'."
)
def test_empty_label_warning(self):
"""Test that a warning is logged if st.checkbox was called with empty label."""
with self.assertLogs(_LOGGER) as logs:
st.checkbox(label="")
assert (
"`label` got an empty value. This is discouraged for accessibility reasons"
in logs.records[0].msg
)
# Check that the stack trace is included in the warning message:
assert logs.records[0].stack_info is not None
def test_toggle_widget(self):
"""Test that the usage of `st.toggle` uses the correct checkbox proto config."""
st.toggle("the label")
c = self.get_delta_from_queue().new_element.checkbox
assert c.label == "the label"
assert not c.default
assert not c.disabled
assert (
c.label_visibility.value
== LabelVisibilityMessage.LabelVisibilityOptions.VISIBLE
)
assert c.type == CheckboxProto.StyleType.TOGGLE
@parameterized.expand(
[
(
"checkbox",
lambda label="Label", **kwargs: st.checkbox(label, **kwargs),
"checkbox",
),
(
"toggle",
lambda label="Label", **kwargs: st.toggle(label, **kwargs),
"checkbox",
),
]
)
def test_stable_id_with_key(self, name, command, attr):
"""Test that the widget ID is stable when a stable key is provided."""
with patch(
"streamlit.elements.lib.utils._register_element_id",
return_value=MagicMock(),
):
# First render with certain params
command(
label="Label 1",
key=f"{name}_key",
value=True,
help="Help 1",
disabled=False,
width="content",
on_change=lambda: None,
args=("arg1", "arg2"),
kwargs={"kwarg1": "kwarg1"},
label_visibility="visible",
)
c1 = getattr(self.get_delta_from_queue().new_element, attr)
id1 = c1.id
# Second render with different params but same key
command(
label="Label 2",
key=f"{name}_key",
value=False,
help="Help 2",
disabled=True,
width="stretch",
on_change=lambda: None,
args=("arg_1", "arg_2"),
kwargs={"kwarg_1": "kwarg_1"},
label_visibility="hidden",
)
c2 = getattr(self.get_delta_from_queue().new_element, attr)
id2 = c2.id
assert id1 == id2
def test_checkbox_shows_cached_widget_replay_warning(self):
"""Test that a warning is shown when this widget is used inside a cached function."""
st.cache_data(lambda: st.checkbox("the label"))()
# The widget itself is still created, so we need to go back one element more:
el = self.get_delta_from_queue(-2).new_element.exception
assert el.type == "CachedWidgetWarning"
assert el.is_warning
def test_toggle_shows_cached_widget_replay_warning(self):
"""Test that a warning is shown when this widget is used inside a cached function."""
st.cache_data(lambda: st.toggle("the label"))()
# The widget itself is still created, so we need to go back one element more:
el = self.get_delta_from_queue(-2).new_element.exception
assert el.type == "CachedWidgetWarning"
assert el.is_warning
def test_checkbox_with_width(self):
"""Test st.checkbox with different width types."""
test_cases = [
(500, WidthConfigFields.PIXEL_WIDTH.value, "pixel_width", 500),
("stretch", WidthConfigFields.USE_STRETCH.value, "use_stretch", True),
("content", WidthConfigFields.USE_CONTENT.value, "use_content", True),
]
for index, (
width_value,
expected_width_spec,
field_name,
field_value,
) in enumerate(test_cases):
with self.subTest(width_value=width_value):
st.checkbox(f"checkbox width test {index}", width=width_value)
el = self.get_delta_from_queue().new_element
assert el.checkbox.label == f"checkbox width test {index}"
assert el.width_config.WhichOneof("width_spec") == expected_width_spec
assert getattr(el.width_config, field_name) == field_value
def test_checkbox_with_invalid_width(self):
"""Test st.checkbox with invalid width values."""
test_cases = [
(
"invalid",
"Invalid width value: 'invalid'. Width must be either an integer (pixels), 'stretch', or 'content'.",
),
(
-100,
"Invalid width value: -100. Width must be either an integer (pixels), 'stretch', or 'content'.",
),
(
0,
"Invalid width value: 0. Width must be either an integer (pixels), 'stretch', or 'content'.",
),
(
100.5,
"Invalid width value: 100.5. Width must be either an integer (pixels), 'stretch', or 'content'.",
),
]
for index, (width_value, expected_error_message) in enumerate(test_cases):
with self.subTest(width_value=width_value):
with pytest.raises(StreamlitAPIException) as exc:
st.checkbox(
f"invalid checkbox width test {index}", width=width_value
)
assert str(exc.value) == expected_error_message
def test_checkbox_default_width(self):
"""Test that st.checkbox defaults to content width."""
st.checkbox("the label")
el = self.get_delta_from_queue().new_element
assert el.checkbox.label == "the label"
assert (
el.width_config.WhichOneof("width_spec")
== WidthConfigFields.USE_CONTENT.value
)
assert el.width_config.use_content is True
def test_toggle_with_width(self):
"""Test st.toggle with different width types."""
test_cases = [
(500, WidthConfigFields.PIXEL_WIDTH.value, "pixel_width", 500),
("stretch", WidthConfigFields.USE_STRETCH.value, "use_stretch", True),
("content", WidthConfigFields.USE_CONTENT.value, "use_content", True),
]
for index, (
width_value,
expected_width_spec,
field_name,
field_value,
) in enumerate(test_cases):
with self.subTest(width_value=width_value):
st.toggle(f"toggle width test {index}", width=width_value)
el = self.get_delta_from_queue().new_element
assert el.checkbox.label == f"toggle width test {index}"
assert el.checkbox.type == CheckboxProto.StyleType.TOGGLE
assert el.width_config.WhichOneof("width_spec") == expected_width_spec
assert getattr(el.width_config, field_name) == field_value
def test_toggle_with_invalid_width(self):
"""Test st.toggle with invalid width values."""
test_cases = [
(
"invalid",
"Invalid width value: 'invalid'. Width must be either an integer (pixels), 'stretch', or 'content'.",
),
(
-100,
"Invalid width value: -100. Width must be either an integer (pixels), 'stretch', or 'content'.",
),
(
0,
"Invalid width value: 0. Width must be either an integer (pixels), 'stretch', or 'content'.",
),
(
100.5,
"Invalid width value: 100.5. Width must be either an integer (pixels), 'stretch', or 'content'.",
),
]
for index, (width_value, expected_error_message) in enumerate(test_cases):
with self.subTest(width_value=width_value):
with pytest.raises(StreamlitAPIException) as exc:
st.toggle(f"invalid toggle test {index}", width=width_value)
assert str(exc.value) == expected_error_message
def test_toggle_default_width(self):
"""Test that st.toggle defaults to content width."""
st.toggle("the label")
el = self.get_delta_from_queue().new_element
assert el.checkbox.label == "the label"
assert el.checkbox.type == CheckboxProto.StyleType.TOGGLE
assert (
el.width_config.WhichOneof("width_spec")
== WidthConfigFields.USE_CONTENT.value
)
assert el.width_config.use_content is True
| CheckboxTest |
python | google__pytype | pytype/pyc/opcodes.py | {
"start": 11698,
"end": 11802
} | class ____(OpcodeWithArg): # Arg: Comparison operator
_FLAGS = HAS_ARGUMENT
__slots__ = ()
| COMPARE_OP |
python | pennersr__django-allauth | allauth/headless/account/inputs.py | {
"start": 9114,
"end": 9180
} | class ____(VerifyPhoneForm, inputs.Input):
pass
| VerifyPhoneInput |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/workspace/workspace.py | {
"start": 1363,
"end": 1677
} | class ____:
"""Slimmer version of WorkspaceLocationEntry, containing the minimum set of information required
to know whether the workspace needs reloading.
"""
location_name: str
load_status: CodeLocationLoadStatus
update_timestamp: float
version_key: str
@record
| CodeLocationStatusEntry |
python | getsentry__sentry | src/sentry/types/grouphash_metadata.py | {
"start": 2427,
"end": 2946
} | class ____(TypedDict):
"""
Data gathered when an event is grouped based on a stacktrace found in an exception, a thread, or
diretly in the event
"""
# Either "in-app" or "system"
stacktrace_type: str
# Where in the event data the stacktrace was found - either "exception", "thread", or
# "top-level"
stacktrace_location: str
# The number of stacktraces used for grouping (will be more than 1 in cases of chained
# exceptions)
num_stacktraces: int
| StacktraceHashingMetadata |
python | wandb__wandb | wandb/vendor/graphql-core-1.1/wandb_graphql/type/definition.py | {
"start": 16511,
"end": 17158
} | class ____(object):
__slots__ = 'type', 'default_value', 'description', 'out_name'
def __init__(self, type, default_value=None, description=None, out_name=None):
self.type = type
self.default_value = default_value
self.description = description
self.out_name = out_name
def __eq__(self, other):
return (
self is other or (
isinstance(other, GraphQLInputObjectField) and
self.type == other.type and
self.description == other.description and
self.out_name == other.out_name
)
)
| GraphQLInputObjectField |
python | getsentry__sentry | tests/sentry/integrations/api/endpoints/test_organization_integration_details.py | {
"start": 865,
"end": 1906
} | class ____(APITestCase):
endpoint = "sentry-api-0-organization-integration-details"
def setUp(self) -> None:
super().setUp()
self.login_as(user=self.user)
self.integration = self.create_provider_integration(
provider="gitlab", name="Gitlab", external_id="gitlab:1"
)
self.identity = Identity.objects.create(
idp=self.create_identity_provider(type="gitlab", config={}, external_id="gitlab:1"),
user=self.user,
external_id="base_id",
data={},
)
self.integration.add_organization(
self.organization, self.user, default_auth_id=self.identity.id
)
with assume_test_silo_mode(SiloMode.REGION):
self.repo = Repository.objects.create(
provider="gitlab",
name="getsentry/sentry",
organization_id=self.organization.id,
integration_id=self.integration.id,
)
@control_silo_test
| OrganizationIntegrationDetailsTest |
python | pypa__hatch | src/hatch/cli/test/core.py | {
"start": 207,
"end": 1936
} | class ____:
def __init__(self, project_root: Path, data_dir: Path) -> None:
self.project_root = project_root
self.data_dir = data_dir
@cached_property
def user_config_path(self) -> Path:
# https://coverage.readthedocs.io/en/7.4.4/config.html#sample-file
return (
dedicated_coverage_file
if (dedicated_coverage_file := self.project_root.joinpath(".coveragerc")).is_file()
else self.project_root.joinpath("pyproject.toml")
)
@cached_property
def internal_config_path(self) -> Path:
return self.data_dir / "coverage" / self.project_root.id / self.user_config_path.name
def write_config_file(self) -> None:
self.internal_config_path.parent.ensure_dir_exists()
if self.internal_config_path.name == ".coveragerc":
from configparser import ConfigParser
cfg = ConfigParser()
cfg.read(str(self.user_config_path))
if "run" not in cfg:
cfg["run"] = {"parallel": "true"}
self._write_ini(cfg)
return
cfg["run"]["parallel"] = "true"
self._write_ini(cfg)
else:
import tomli_w
from hatch.utils.toml import load_toml_data
project_data = load_toml_data(self.user_config_path.read_text())
project_data.setdefault("tool", {}).setdefault("coverage", {}).setdefault("run", {})["parallel"] = True
self.internal_config_path.write_text(tomli_w.dumps(project_data))
def _write_ini(self, cfg: ConfigParser) -> None:
with self.internal_config_path.open("w", encoding="utf-8") as f:
cfg.write(f)
| PatchedCoverageConfig |
python | huggingface__transformers | src/transformers/models/glm4v/modular_glm4v.py | {
"start": 16535,
"end": 16579
} | class ____(Glm4RMSNorm):
pass
| Glm4vRMSNorm |
python | microsoft__pyright | build/generateUnicodeTables.py | {
"start": 257,
"end": 765
} | class ____:
def __init__(self, code: int, category: str, *, end: int | None = None):
self.code = code
self.category = category
self.hasSurrogate = code > 0xFFFF
if self.hasSurrogate:
unicodeChar = chr(code)
utf16 = unicodeChar.encode("utf-16")
rawHex = utf16.hex()
hex = rawHex[4:]
self.highSurrogate = int(hex[2:4] + hex[0:2], base=16)
self.lowSurrogate = int(hex[6:8] + hex[4:6], base=16)
| Character |
python | huggingface__transformers | tests/pipelines/test_pipelines_fill_mask.py | {
"start": 1041,
"end": 17941
} | class ____(unittest.TestCase):
model_mapping = MODEL_FOR_MASKED_LM_MAPPING
def tearDown(self):
super().tearDown()
# clean-up as much as possible GPU memory occupied by PyTorch
gc.collect()
if is_torch_available():
backend_empty_cache(torch_device)
@require_torch
def test_small_model_pt(self):
unmasker = pipeline(task="fill-mask", model="sshleifer/tiny-distilroberta-base", top_k=2)
outputs = unmasker("My name is <mask>")
self.assertEqual(
nested_simplify(outputs, decimals=6),
[
{"sequence": "My name is Maul", "score": 2.2e-05, "token": 35676, "token_str": " Maul"},
{"sequence": "My name isELS", "score": 2.2e-05, "token": 16416, "token_str": "ELS"},
],
)
outputs = unmasker("The largest city in France is <mask>")
self.assertEqual(
nested_simplify(outputs, decimals=6),
[
{
"sequence": "The largest city in France is Maul",
"score": 2.2e-05,
"token": 35676,
"token_str": " Maul",
},
{"sequence": "The largest city in France isELS", "score": 2.2e-05, "token": 16416, "token_str": "ELS"},
],
)
outputs = unmasker("My name is <mask>", targets=[" Patrick", " Clara", " Teven"], top_k=3)
self.assertEqual(
nested_simplify(outputs, decimals=6),
[
{"sequence": "My name is Patrick", "score": 2.1e-05, "token": 3499, "token_str": " Patrick"},
{"sequence": "My name is Te", "score": 2e-05, "token": 2941, "token_str": " Te"},
{"sequence": "My name is Clara", "score": 2e-05, "token": 13606, "token_str": " Clara"},
],
)
outputs = unmasker("My name is <mask> <mask>", top_k=2)
self.assertEqual(
nested_simplify(outputs, decimals=6),
[
[
{
"score": 2.2e-05,
"token": 35676,
"token_str": " Maul",
"sequence": "<s>My name is Maul<mask></s>",
},
{"score": 2.2e-05, "token": 16416, "token_str": "ELS", "sequence": "<s>My name isELS<mask></s>"},
],
[
{
"score": 2.2e-05,
"token": 35676,
"token_str": " Maul",
"sequence": "<s>My name is<mask> Maul</s>",
},
{"score": 2.2e-05, "token": 16416, "token_str": "ELS", "sequence": "<s>My name is<mask>ELS</s>"},
],
],
)
@require_torch_accelerator
def test_fp16_casting(self):
pipe = pipeline(
"fill-mask",
model="hf-internal-testing/tiny-random-distilbert",
device=torch_device,
)
# convert model to fp16
pipe.model.half()
response = pipe("Paris is the [MASK] of France.")
# We actually don't care about the result, we just want to make sure
# it works, meaning the float16 tensor got casted back to float32
# for postprocessing.
self.assertIsInstance(response, list)
@slow
@require_torch
def test_large_model_pt(self):
unmasker = pipeline(task="fill-mask", model="distilbert/distilroberta-base", top_k=2)
self.run_large_test(unmasker)
def run_large_test(self, unmasker):
outputs = unmasker("My name is <mask>")
self.assertEqual(
nested_simplify(outputs),
[
{"sequence": "My name is John", "score": 0.008, "token": 610, "token_str": " John"},
{"sequence": "My name is Chris", "score": 0.007, "token": 1573, "token_str": " Chris"},
],
)
outputs = unmasker("The largest city in France is <mask>")
self.assertEqual(
nested_simplify(outputs),
[
{
"sequence": "The largest city in France is Paris",
"score": 0.251,
"token": 2201,
"token_str": " Paris",
},
{
"sequence": "The largest city in France is Lyon",
"score": 0.214,
"token": 12790,
"token_str": " Lyon",
},
],
)
outputs = unmasker("My name is <mask>", targets=[" Patrick", " Clara", " Teven"], top_k=3)
self.assertEqual(
nested_simplify(outputs),
[
{"sequence": "My name is Patrick", "score": 0.005, "token": 3499, "token_str": " Patrick"},
{"sequence": "My name is Clara", "score": 0.000, "token": 13606, "token_str": " Clara"},
{"sequence": "My name is Te", "score": 0.000, "token": 2941, "token_str": " Te"},
],
)
dummy_str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit," * 100
outputs = unmasker(
"My name is <mask>" + dummy_str,
tokenizer_kwargs={"truncation": True},
)
simplified = nested_simplify(outputs, decimals=4)
self.assertEqual(
[{"sequence": x["sequence"][:100]} for x in simplified],
[
{"sequence": f"My name is,{dummy_str}"[:100]},
{"sequence": f"My name is:,{dummy_str}"[:100]},
],
)
self.assertEqual(
[{k: x[k] for k in x if k != "sequence"} for x in simplified],
[
{"score": 0.2819, "token": 6, "token_str": ","},
{"score": 0.0954, "token": 46686, "token_str": ":,"},
],
)
@require_torch
def test_model_no_pad_pt(self):
unmasker = pipeline(task="fill-mask", model="sshleifer/tiny-distilroberta-base")
unmasker.tokenizer.pad_token_id = None
unmasker.tokenizer.pad_token = None
self.run_pipeline_test(unmasker, [])
def get_test_pipeline(
self,
model,
tokenizer=None,
image_processor=None,
feature_extractor=None,
processor=None,
dtype="float32",
):
if tokenizer is None or tokenizer.mask_token_id is None:
self.skipTest(reason="The provided tokenizer has no mask token, (probably reformer or wav2vec2)")
fill_masker = FillMaskPipeline(
model=model,
tokenizer=tokenizer,
feature_extractor=feature_extractor,
image_processor=image_processor,
processor=processor,
dtype=dtype,
)
examples = [
f"This is another {tokenizer.mask_token} test",
]
return fill_masker, examples
def run_pipeline_test(self, fill_masker, examples):
tokenizer = fill_masker.tokenizer
model = fill_masker.model
outputs = fill_masker(
f"This is a {tokenizer.mask_token}",
)
self.assertEqual(
outputs,
[
{"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)},
{"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)},
{"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)},
{"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)},
{"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)},
],
)
outputs = fill_masker([f"This is a {tokenizer.mask_token}"])
self.assertEqual(
outputs,
[
{"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)},
{"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)},
{"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)},
{"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)},
{"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)},
],
)
outputs = fill_masker([f"This is a {tokenizer.mask_token}", f"Another {tokenizer.mask_token} great test."])
self.assertEqual(
outputs,
[
[
{"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)},
{"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)},
{"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)},
{"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)},
{"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)},
],
[
{"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)},
{"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)},
{"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)},
{"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)},
{"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)},
],
],
)
with self.assertRaises(ValueError):
fill_masker([None])
# No mask_token is not supported
with self.assertRaises(PipelineException):
fill_masker("This is")
self.run_test_top_k(model, tokenizer)
self.run_test_targets(model, tokenizer)
self.run_test_top_k_targets(model, tokenizer)
self.fill_mask_with_duplicate_targets_and_top_k(model, tokenizer)
self.fill_mask_with_multiple_masks(model, tokenizer)
def run_test_targets(self, model, tokenizer):
vocab = tokenizer.get_vocab()
targets = sorted(vocab.keys())[:2]
# Pipeline argument
fill_masker = FillMaskPipeline(model=model, tokenizer=tokenizer, targets=targets)
outputs = fill_masker(f"This is a {tokenizer.mask_token}")
self.assertEqual(
outputs,
[
{"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)},
{"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)},
],
)
target_ids = {vocab[el] for el in targets}
self.assertEqual({el["token"] for el in outputs}, target_ids)
processed_targets = [tokenizer.decode([x]) for x in target_ids]
self.assertEqual({el["token_str"] for el in outputs}, set(processed_targets))
# Call argument
fill_masker = FillMaskPipeline(model=model, tokenizer=tokenizer)
outputs = fill_masker(f"This is a {tokenizer.mask_token}", targets=targets)
self.assertEqual(
outputs,
[
{"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)},
{"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)},
],
)
target_ids = {vocab[el] for el in targets}
self.assertEqual({el["token"] for el in outputs}, target_ids)
processed_targets = [tokenizer.decode([x]) for x in target_ids]
self.assertEqual({el["token_str"] for el in outputs}, set(processed_targets))
# Score equivalence
outputs = fill_masker(f"This is a {tokenizer.mask_token}", targets=targets)
tokens = [top_mask["token_str"] for top_mask in outputs]
scores = [top_mask["score"] for top_mask in outputs]
# For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`.
if set(tokens) == set(targets):
unmasked_targets = fill_masker(f"This is a {tokenizer.mask_token}", targets=tokens)
target_scores = [top_mask["score"] for top_mask in unmasked_targets]
self.assertEqual(nested_simplify(scores), nested_simplify(target_scores))
# Raises with invalid
with self.assertRaises(ValueError):
outputs = fill_masker(f"This is a {tokenizer.mask_token}", targets=[])
# For some tokenizers, `""` is actually in the vocabulary and the expected error won't raised
if "" not in tokenizer.get_vocab():
with self.assertRaises(ValueError):
outputs = fill_masker(f"This is a {tokenizer.mask_token}", targets=[""])
with self.assertRaises(ValueError):
outputs = fill_masker(f"This is a {tokenizer.mask_token}", targets="")
def run_test_top_k(self, model, tokenizer):
fill_masker = FillMaskPipeline(model=model, tokenizer=tokenizer, top_k=2)
outputs = fill_masker(f"This is a {tokenizer.mask_token}")
self.assertEqual(
outputs,
[
{"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)},
{"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)},
],
)
fill_masker = FillMaskPipeline(model=model, tokenizer=tokenizer)
outputs2 = fill_masker(f"This is a {tokenizer.mask_token}", top_k=2)
self.assertEqual(
outputs2,
[
{"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)},
{"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)},
],
)
self.assertEqual(nested_simplify(outputs), nested_simplify(outputs2))
def run_test_top_k_targets(self, model, tokenizer):
vocab = tokenizer.get_vocab()
fill_masker = FillMaskPipeline(model=model, tokenizer=tokenizer)
# top_k=2, ntargets=3
targets = sorted(vocab.keys())[:3]
outputs = fill_masker(f"This is a {tokenizer.mask_token}", top_k=2, targets=targets)
# If we use the most probably targets, and filter differently, we should still
# have the same results
targets2 = [el["token_str"] for el in sorted(outputs, key=lambda x: x["score"], reverse=True)]
# For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`.
if set(targets2).issubset(targets):
outputs2 = fill_masker(f"This is a {tokenizer.mask_token}", top_k=3, targets=targets2)
# They should yield exactly the same result
self.assertEqual(nested_simplify(outputs), nested_simplify(outputs2))
def fill_mask_with_duplicate_targets_and_top_k(self, model, tokenizer):
fill_masker = FillMaskPipeline(model=model, tokenizer=tokenizer)
vocab = tokenizer.get_vocab()
# String duplicates + id duplicates
targets = sorted(vocab.keys())[:3]
targets = [targets[0], targets[1], targets[0], targets[2], targets[1]]
outputs = fill_masker(f"My name is {tokenizer.mask_token}", targets=targets, top_k=10)
# The target list contains duplicates, so we can't output more
# than them
self.assertEqual(len(outputs), 3)
def fill_mask_with_multiple_masks(self, model, tokenizer):
fill_masker = FillMaskPipeline(model=model, tokenizer=tokenizer)
outputs = fill_masker(
f"This is a {tokenizer.mask_token} {tokenizer.mask_token} {tokenizer.mask_token}", top_k=2
)
self.assertEqual(
outputs,
[
[
{"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)},
{"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)},
],
[
{"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)},
{"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)},
],
[
{"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)},
{"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)},
],
],
)
| FillMaskPipelineTests |
python | ethereum__web3.py | web3/middleware/filter.py | {
"start": 17809,
"end": 22031
} | class ____(Web3Middleware):
def __init__(self, w3: Union["Web3", "AsyncWeb3[Any]"]):
self.filters: dict[str, SyncFilter] = {}
self.async_filters: dict[str, AsyncFilter] = {}
self.filter_id_counter = itertools.count()
super().__init__(w3)
def wrap_make_request(self, make_request: MakeRequestFn) -> MakeRequestFn:
def middleware(method: "RPCEndpoint", params: Any) -> "RPCResponse":
if method in NEW_FILTER_METHODS:
_filter: SyncFilter
filter_id = to_hex(next(self.filter_id_counter))
if method == RPC.eth_newFilter:
_filter = RequestLogs(
cast("Web3", self._w3),
**apply_key_map(FILTER_PARAMS_KEY_MAP, params[0])
)
elif method == RPC.eth_newBlockFilter:
_filter = RequestBlocks(cast("Web3", self._w3))
else:
raise NotImplementedError(method)
self.filters[filter_id] = _filter
return _simulate_rpc_response_with_result(filter_id)
elif method in FILTER_CHANGES_METHODS:
_filter_id = params[0]
# Pass through to filters not created by middleware
if _filter_id not in self.filters:
return make_request(method, params)
_filter = self.filters[_filter_id]
if method == RPC.eth_getFilterChanges:
return _simulate_rpc_response_with_result(
next(_filter.filter_changes) # type: ignore
)
elif method == RPC.eth_getFilterLogs:
# type ignored b/c logic prevents RequestBlocks which
# doesn't implement get_logs
return _simulate_rpc_response_with_result(
_filter.get_logs() # type: ignore
)
else:
raise NotImplementedError(method)
else:
return make_request(method, params)
return middleware
# -- async -- #
async def async_wrap_make_request(
self,
make_request: AsyncMakeRequestFn,
) -> AsyncMakeRequestFn:
async def middleware(method: "RPCEndpoint", params: Any) -> "RPCResponse":
if method in NEW_FILTER_METHODS:
_filter: AsyncFilter
filter_id = to_hex(next(self.filter_id_counter))
if method == RPC.eth_newFilter:
_filter = await AsyncRequestLogs(
cast("AsyncWeb3[Any]", self._w3),
**apply_key_map(FILTER_PARAMS_KEY_MAP, params[0])
)
elif method == RPC.eth_newBlockFilter:
_filter = await AsyncRequestBlocks(cast("AsyncWeb3[Any]", self._w3))
else:
raise NotImplementedError(method)
self.async_filters[filter_id] = _filter
return _simulate_rpc_response_with_result(filter_id)
elif method in FILTER_CHANGES_METHODS:
_filter_id = params[0]
# Pass through to filters not created by middleware
if _filter_id not in self.async_filters:
return await make_request(method, params)
_filter = self.async_filters[_filter_id]
if method == RPC.eth_getFilterChanges:
return _simulate_rpc_response_with_result(
await _filter.filter_changes.__anext__() # type: ignore
)
elif method == RPC.eth_getFilterLogs:
# type ignored b/c logic prevents RequestBlocks which
# doesn't implement get_logs
return _simulate_rpc_response_with_result(
await _filter.get_logs() # type: ignore
)
else:
raise NotImplementedError(method)
else:
return await make_request(method, params)
return middleware
| LocalFilterMiddleware |
python | huggingface__transformers | src/transformers/models/qwen2_5_omni/modular_qwen2_5_omni.py | {
"start": 93066,
"end": 94762
} | class ____(Qwen2_5_VLAttention):
def __init__(self, config: Qwen2_5OmniConfig, layer_idx: Optional[int] = None):
nn.Module.__init__(self)
self.config = config
self.layer_idx = layer_idx
if layer_idx is None:
logger.warning_once(
f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
"to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
"when creating this class."
)
self.hidden_size = config.hidden_size
self.num_heads = config.num_attention_heads
self.head_dim = getattr(config, "head_dim", self.hidden_size // self.num_heads)
self.num_key_value_heads = config.num_key_value_heads
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
self.is_causal = True
self.attention_dropout = config.attention_dropout
self.rope_parameters = config.rope_parameters
self.scaling = self.head_dim**-0.5
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
self.layer_type = config.layer_types[layer_idx] if hasattr(config, "layer_types") else None
self.sliding_window = config.sliding_window if self.layer_type == "sliding_attention" else None
| Qwen2_5OmniAttention |
python | dask__distributed | distributed/scheduler.py | {
"start": 30820,
"end": 32492
} | class ____:
"""Abstract collection tracking all tasks
See Also
--------
TaskGroup
TaskPrefix
"""
#: The name of a collection of tasks.
name: str
#: The total number of bytes that tasks belonging to this collection have produced
nbytes_total: int
#: The number of tasks belonging to this collection in each state,
#: like ``{"memory": 10, "processing": 3, "released": 4, ...}``
states: dict[TaskStateState, int]
_all_durations_us: defaultdict[str, int]
_duration_us: int
_size: int
_types: defaultdict[str, int]
__slots__ = tuple(__annotations__)
def __init__(self, name: str):
self.name = name
self._all_durations_us = defaultdict(int)
self._duration_us = 0
self.nbytes_total = 0
self.states = dict.fromkeys(ALL_TASK_STATES, 0)
self._size = 0
self._types = defaultdict(int)
@property
def all_durations(self) -> defaultdict[str, float]:
"""Cumulative duration of all completed actions of tasks belonging to this collection, by action"""
return defaultdict(
float,
{
action: duration_us / 1e6
for action, duration_us in self._all_durations_us.items()
},
)
@property
def duration(self) -> float:
"""The total amount of time spent on all tasks belonging to this collection"""
return self._duration_us / 1e6
@property
def types(self) -> Set[str]:
"""The result types of this collection"""
return self._types.keys()
def __len__(self) -> int:
return self._size
| TaskCollection |
python | pypa__setuptools | setuptools/_vendor/jaraco/collections/__init__.py | {
"start": 19936,
"end": 21954
} | class ____(collections.abc.Mapping, collections.abc.Hashable):
"""
An immutable mapping.
>>> a = FrozenDict(a=1, b=2)
>>> b = FrozenDict(a=1, b=2)
>>> a == b
True
>>> a == dict(a=1, b=2)
True
>>> dict(a=1, b=2) == a
True
>>> 'a' in a
True
>>> type(hash(a)) is type(0)
True
>>> set(iter(a)) == {'a', 'b'}
True
>>> len(a)
2
>>> a['a'] == a.get('a') == 1
True
>>> a['c'] = 3
Traceback (most recent call last):
...
TypeError: 'FrozenDict' object does not support item assignment
>>> a.update(y=3)
Traceback (most recent call last):
...
AttributeError: 'FrozenDict' object has no attribute 'update'
Copies should compare equal
>>> copy.copy(a) == a
True
Copies should be the same type
>>> isinstance(copy.copy(a), FrozenDict)
True
FrozenDict supplies .copy(), even though
collections.abc.Mapping doesn't demand it.
>>> a.copy() == a
True
>>> a.copy() is not a
True
"""
__slots__ = ['__data']
def __new__(cls, *args, **kwargs):
self = super().__new__(cls)
self.__data = dict(*args, **kwargs)
return self
# Container
def __contains__(self, key):
return key in self.__data
# Hashable
def __hash__(self):
return hash(tuple(sorted(self.__data.items())))
# Mapping
def __iter__(self):
return iter(self.__data)
def __len__(self):
return len(self.__data)
def __getitem__(self, key):
return self.__data[key]
# override get for efficiency provided by dict
def get(self, *args, **kwargs):
return self.__data.get(*args, **kwargs)
# override eq to recognize underlying implementation
def __eq__(self, other):
if isinstance(other, FrozenDict):
other = other.__data
return self.__data.__eq__(other)
def copy(self):
"Return a shallow copy of self"
return copy.copy(self)
| FrozenDict |
python | tensorflow__tensorflow | tensorflow/python/distribute/experimental/multi_worker_mirrored_strategy_test.py | {
"start": 2083,
"end": 19231
} | class ____(tf_test.TestCase, parameterized.TestCase):
def setUp(self):
super().setUp()
self.num_client = flags.FLAGS.num_clients
self.num_local_devices = flags.FLAGS.num_local_devices
tf_config = json.loads(os.environ['TF_CONFIG'])
self.client_id = int(tf_config['task']['index'])
def test_strategy_creation_with_default_cluster_resolver(self):
strategy = mwms.MultiWorkerMirroredStrategy()
mesh = strategy.mesh
self.assertIsNotNone(mesh)
self.assertLen(mesh.global_device_ids(),
self.num_client * self.num_local_devices)
self.assertLen(mesh.local_device_ids(), self.num_local_devices)
self.assertIsInstance(strategy._cluster_resolver,
tfconfig_cluster_resolver.TFConfigClusterResolver)
def test_invalid_init_arguments(self):
mesh = object()
cluster_resolver = tfconfig_cluster_resolver.TFConfigClusterResolver()
with self.assertRaisesRegex(
ValueError,
'Mesh and cluster_resolver can not be provided at the same time'):
mwms.MultiWorkerMirroredStrategy(
mesh=mesh,
cluster_resolver=cluster_resolver)
def test_parse_dtensor_env_var_from_cluster_resolver(self):
cluster_resolver = tfconfig_cluster_resolver.TFConfigClusterResolver()
dtensor_env_vars = mwms._parse_dtensor_env_var_from_cluster_resolver(
cluster_resolver)
tf_config = json.loads(os.environ['TF_CONFIG'])
worker_jobs = ','.join(tf_config['cluster']['worker'])
client_id = tf_config['task']['index']
self.assertLen(dtensor_env_vars, 4)
self.assertEqual(dtensor_env_vars['DTENSOR_JOBS'], worker_jobs)
self.assertEqual(dtensor_env_vars['DTENSOR_NUM_CLIENTS'],
str(self.num_client))
self.assertEqual(dtensor_env_vars['DTENSOR_CLIENT_ID'], client_id)
self.assertEqual(dtensor_env_vars['DTENSOR_JOB_NAME'], 'worker')
@parameterized.named_parameters([
('py_floats', lambda: [1.0, 2.0], True),
('np_floats', lambda: np.array([1.0, 2.0]), True),
('tf_const', lambda: constant_op.constant([1.0, 2.0]), True),
('py_floats_callable', lambda: [1.0, 2.0], False),
('np_floats_callable', lambda: np.array([1.0, 2.0]), False),
('tf_const_callable', lambda: constant_op.constant([1.0, 2.0]), False),
])
def test_variable_creation(self, init_value, convert_callable):
if convert_callable:
init_value = init_value()
strategy = mwms.MultiWorkerMirroredStrategy()
with strategy.scope():
v = variables.Variable(init_value)
self.assertIsInstance(v, d_variable.DVariable)
self.assertIsNotNone(v.layout)
self.assertEqual(v.layout, layout.Layout.replicated(strategy.mesh, rank=1))
def test_strategy_extension(self):
strategy = mwms.MultiWorkerMirroredStrategy()
self.assertIsInstance(strategy.extended, distribute_lib.StrategyExtendedV2)
def test_num_replica_in_sync(self):
strategy = mwms.MultiWorkerMirroredStrategy()
self.assertEqual(strategy.num_replicas_in_sync,
self.num_client * self.num_local_devices)
def test_mesh(self):
strategy = mwms.MultiWorkerMirroredStrategy()
self.assertIsNotNone(strategy.mesh)
def test_worker_devices(self):
strategy = mwms.MultiWorkerMirroredStrategy()
worker_devices = strategy.extended.worker_devices
self.assertLen(worker_devices, self.num_local_devices)
self.assertEqual(worker_devices, tuple(strategy.mesh.local_devices()))
def test_parameter_devices(self):
strategy = mwms.MultiWorkerMirroredStrategy()
parameter_devices = strategy.extended.parameter_devices
self.assertLen(parameter_devices, self.num_local_devices)
self.assertEqual(parameter_devices, tuple(strategy.mesh.local_devices()))
def test_variable_created_in_scope(self):
strategy1 = mwms.MultiWorkerMirroredStrategy()
with strategy1.scope():
v1 = variables.Variable(constant_op.constant([1.0, 2.0]))
v2 = variables.Variable(constant_op.constant([1.0, 2.0]))
strategy2 = mwms.MultiWorkerMirroredStrategy()
with strategy2.scope():
v3 = variables.Variable(constant_op.constant([1.0, 2.0]))
self.assertTrue(strategy1.extended.variable_created_in_scope(v1))
self.assertFalse(strategy1.extended.variable_created_in_scope(v2))
self.assertFalse(strategy1.extended.variable_created_in_scope(v3))
self.assertTrue(strategy2.extended.variable_created_in_scope(v3))
def test_colocate_vars_with(self):
strategy = mwms.MultiWorkerMirroredStrategy()
with strategy.scope():
v1 = variables.Variable(constant_op.constant([1.0, 2.0]))
with strategy.extended.colocate_vars_with(v1):
v2 = variables.Variable(constant_op.constant([2.0, 3.0]))
# We assert the layout for the variable, and make sure they are same.
self.assertEqual(v1.layout, v2.layout)
def test_in_multi_worker_mode(self):
strategy = mwms.MultiWorkerMirroredStrategy()
self.assertTrue(strategy.extended._in_multi_worker_mode())
def test_run_with_distribute_value_input(self):
strategy = mwms.MultiWorkerMirroredStrategy()
def value_fn(value_context):
return value_context.replica_id_in_sync_group
distributed_values = (
strategy.experimental_distribute_values_from_function(
value_fn))
@def_function.function
def replica_fn(inputs):
return inputs * 2
result = strategy.run(replica_fn, args=(distributed_values,))
self.assertIsInstance(result, dtensor_util.DTensorDistributedValue)
self.assertLen(result.values, self.num_local_devices)
# Note that the scalar value from
# experimental_distribute_values_from_function will be up rank to 1D since
# batched shared dtensor need at least be 1D.
for i in range(self.num_local_devices):
self.assertAllClose(
result.values[i],
constant_op.constant(
[(self.client_id * self.num_local_devices + i) * 2]))
def test_nested_structure_output(self):
strategy = mwms.MultiWorkerMirroredStrategy()
def value_fn(ctx):
value = float(ctx.num_replicas_in_sync)
return {'a': value,
'b': constant_op.constant([value + 1.0, value + 2.0])}
distributed_values = (
strategy.experimental_distribute_values_from_function(
value_fn))
@def_function.function
def replica_fn(inputs):
result = {}
for key in inputs:
result[key] = inputs[key] * 2.0
return result
result = strategy.run(replica_fn, args=(distributed_values,))
self.assertLen(result.keys(), 2)
self.assertIsInstance(result['a'], dtensor_util.DTensorDistributedValue)
self.assertLen(result['a'].values, self.num_local_devices)
for i in range(self.num_local_devices):
self.assertAllClose(
result['a'].values[i],
constant_op.constant([strategy.num_replicas_in_sync * 2.0]))
self.assertIsInstance(result['b'], dtensor_util.DTensorDistributedValue)
self.assertLen(result['b'].values, self.num_local_devices)
for i in range(self.num_local_devices):
self.assertAllClose(
result['b'].values[i],
constant_op.constant([(strategy.num_replicas_in_sync + 1.0) * 2.0,
(strategy.num_replicas_in_sync + 2.0) * 2.0]))
def test_inputs_with_dtensor_distribute_values(self):
@def_function.function
def replica_fn_1(inputs):
return inputs * 2.0
@def_function.function
def replica_fn_2(inputs):
return inputs + 1.0
strategy = mwms.MultiWorkerMirroredStrategy()
tensor_input = constant_op.constant(3.0)
d_tensor_input = strategy.experimental_distribute_values_from_function(
lambda _: tensor_input)
result_1 = strategy.run(replica_fn_1, args=(d_tensor_input,))
self.assertIsInstance(result_1, dtensor_util.DTensorDistributedValue)
self.assertLen(result_1.values, self.num_local_devices)
for i in range(self.num_local_devices):
self.assertAllClose(result_1.values[i], constant_op.constant([6.0]))
result_2 = strategy.run(replica_fn_2, args=(result_1,))
self.assertIsInstance(result_2, dtensor_util.DTensorDistributedValue)
self.assertLen(result_2.values, self.num_local_devices)
for i in range(self.num_local_devices):
self.assertAllClose(result_2.values[i], constant_op.constant([7.0]))
def test_get_replica_context(self):
strategy = mwms.MultiWorkerMirroredStrategy()
tensor_input = constant_op.constant(3)
d_tensor_input = strategy.experimental_distribute_values_from_function(
lambda _: tensor_input)
@def_function.function
def replica_fn(inputs):
replica_context = distribute_lib.get_replica_context()
self.assertIsInstance(replica_context, dtensor_util.DTensorReplicaContext)
return inputs * replica_context.num_replicas_in_sync
# Default replica context
self.assertIsNotNone(distribute_lib.get_replica_context())
with strategy.scope():
self.assertIsNone(distribute_lib.get_replica_context())
result = strategy.run(replica_fn, args=(d_tensor_input,))
self.assertLen(result.values, self.num_local_devices)
for i in range(self.num_local_devices):
self.assertAllClose(
result.values[i],
constant_op.constant([3 * strategy.num_replicas_in_sync]))
def test_gather_non_dtensor_value(self):
strategy = mwms.MultiWorkerMirroredStrategy()
tensor_input = constant_op.constant(3.0)
result = strategy.gather(tensor_input, axis=0)
self.assertAllClose(result, tensor_input)
def test_gather_dtensor_value(self):
strategy = mwms.MultiWorkerMirroredStrategy()
stride = self.num_client * self.num_local_devices
def value_fn(value_context):
start = value_context.replica_id_in_sync_group * stride
return array_ops.reshape(
math_ops.range(start=start, limit=start + stride), shape=(1, stride)
)
distribute_result = strategy.experimental_distribute_values_from_function(
value_fn
)
# distribute_result is a DTensorDistributedValue.
# The shape of the global tensor is [stride, stride],
# and each worker gets [stride/2, stride].
result = strategy.gather(distribute_result, axis=0)
start = stride * self.num_local_devices * self.client_id
end = start + stride * self.num_local_devices
self.assertEqual(result.shape, [self.num_local_devices, stride])
self.assertAllClose(
result,
array_ops.reshape(
math_ops.range(start=start, limit=end),
shape=(self.num_local_devices, -1),
),
)
result = strategy.gather(distribute_result, axis=1)
self.assertEqual(result.shape, [1, self.num_local_devices * stride])
self.assertAllClose(
result,
array_ops.reshape(
math_ops.range(start=start, limit=end), shape=(1, -1)
),
)
def test_reduce_mean_non_dtensor_value(self):
strategy = mwms.MultiWorkerMirroredStrategy()
tensor_input = constant_op.constant([[3.0, 4.0], [5.0, 6.0], [7.0, 8.0]])
with self.assertRaisesRegex(
ValueError, 'Unsupported input types for MirroredStrategy.'
):
strategy.reduce(reduce_util.ReduceOp.MEAN, tensor_input, axis=0)
def test_reduce_sum_non_dtensor_value(self):
strategy = mwms.MultiWorkerMirroredStrategy()
tensor_input = constant_op.constant([[3.0, 4.0], [5.0, 6.0], [7.0, 8.0]])
with self.assertRaisesRegex(
ValueError, 'Unsupported input types for MirroredStrategy.'
):
strategy.reduce(reduce_util.ReduceOp.SUM, tensor_input, axis=0)
def test_reduce_mean_distribute_value(self):
strategy = mwms.MultiWorkerMirroredStrategy()
@def_function.function
def value_fn(value_context):
i = value_context.replica_id_in_sync_group
return constant_op.constant([[0.0, 1.0], [2.0, 3.0]]) + i * 4.0
distribute_value = strategy.experimental_distribute_values_from_function(
value_fn
)
# replica 0 has [[0.0, 1.0],[2.0, 3.0]] and
# replica 1 has [[4.0, 5.0],[6.0, 7.0]]. Each worker has 4 replicas.
# For worker 2, it has replica 4 ~ 7.
result = strategy.reduce(
reduce_util.ReduceOp.MEAN, distribute_value, axis=None
)
# This should be a global reduce and each worker should have same value.
# [[14.0, 15.0],[16.0, 17.0]]
final = (self.num_local_devices * self.num_client - 1) * 2.0
self.assertAllClose(
result, constant_op.constant([[0.0, 1.0], [2.0, 3.0]]) + final
)
result = strategy.reduce(
reduce_util.ReduceOp.MEAN, distribute_value, axis=0
)
# [15.0, 16.0]
self.assertAllClose(result, constant_op.constant([0.0, 1.0]) + final + 1)
result = strategy.reduce(
reduce_util.ReduceOp.MEAN, distribute_value, axis=1
)
self.assertAllClose(result, constant_op.constant([0.5, 2.5]) + final)
def test_reduce_sum_distribute_value(self):
strategy = mwms.MultiWorkerMirroredStrategy()
@def_function.function
def value_fn(value_context):
i = value_context.replica_id_in_sync_group
return constant_op.constant([[0.0, 1.0], [2.0, 3.0]]) + i * 4.0
distribute_value = strategy.experimental_distribute_values_from_function(
value_fn
)
# replica 0 has [[0.0, 1.0],[2.0, 3.0]] and
# replica 1 has [[4.0, 5.0],[6.0, 7.0]]. Each worker has 4 replicas.
# For worker 2, it has replica 4 ~ 7.
# The shape of the global tensor is [16, 2], and each worker gets [8, 2].
result = strategy.reduce(
reduce_util.ReduceOp.SUM, distribute_value, axis=None
)
self.assertAllClose(result, [[112.0, 120.0], [128.0, 136.0]])
result = strategy.reduce(reduce_util.ReduceOp.SUM, distribute_value, axis=0)
self.assertAllClose(result, constant_op.constant([240.0, 256.0]))
result = strategy.reduce(reduce_util.ReduceOp.SUM, distribute_value, axis=1)
self.assertAllClose(result, constant_op.constant([232.0, 264.0]))
def test_reduce_mean_mirrored_value(self):
strategy = mwms.MultiWorkerMirroredStrategy()
with strategy.scope():
v = variables.Variable(constant_op.constant([[1.0, 2.0], [3.0, 4.0]]))
self.assertIsInstance(v, d_variable.DVariable)
result = strategy.reduce(reduce_util.ReduceOp.MEAN, v, axis=None)
self.assertAllClose(result, constant_op.constant([[1.0, 2.0], [3.0, 4.0]]))
result = strategy.reduce(reduce_util.ReduceOp.MEAN, v, axis=0)
self.assertAllClose(result, constant_op.constant([2.0, 3.0]))
result = strategy.reduce(reduce_util.ReduceOp.MEAN, v, axis=1)
self.assertAllClose(result, constant_op.constant([1.5, 3.5]))
def test_reduce_sum_mirrored_value(self):
strategy = mwms.MultiWorkerMirroredStrategy()
with strategy.scope():
v = variables.Variable(constant_op.constant([[1.0, 2.0], [3.0, 4.0]]))
self.assertIsInstance(v, d_variable.DVariable)
result = strategy.reduce(reduce_util.ReduceOp.SUM, v, axis=None)
self.assertAllClose(result, constant_op.constant([[1.0, 2.0], [3.0, 4.0]]))
result = strategy.reduce(reduce_util.ReduceOp.SUM, v, axis=0)
self.assertAllClose(result, constant_op.constant([4.0, 6.0]))
result = strategy.reduce(reduce_util.ReduceOp.SUM, v, axis=1)
self.assertAllClose(result, constant_op.constant([3.0, 7.0]))
def test_reduce_value_device(self):
strategy = mwms.MultiWorkerMirroredStrategy()
tensor_input = constant_op.constant([[3.0, 4.0], [5.0, 6.0], [7.0, 8.0]])
result = strategy.reduce(reduce_util.ReduceOp.MEAN, tensor_input, axis=None)
self.assertIn('CPU:0', result.device)
def test_experimental_local_results(self):
@def_function.function
def replica_fn():
return constant_op.constant([3.0])
strategy = mwms.MultiWorkerMirroredStrategy()
result = strategy.run(replica_fn)
local_result = strategy.experimental_local_results(result)
self.assertIsInstance(local_result, tuple)
self.assertLen(local_result, self.num_local_devices)
for i in range(self.num_local_devices):
self.assertEqual(local_result[i], constant_op.constant([3.0]))
def test_experimental_local_results_with_inputs(self):
strategy = mwms.MultiWorkerMirroredStrategy()
def value_fn(ctx):
value = float(ctx.num_replicas_in_sync)
return {'a': value, 'b': constant_op.constant([value + 1.0, value + 2.0])}
distributed_values = strategy.experimental_distribute_values_from_function(
value_fn
)
@def_function.function
def replica_fn(inputs):
result = {}
for key in inputs:
result[key] = inputs[key] * 2.0
return result
result = strategy.run(replica_fn, args=(distributed_values,))
local_result = strategy.experimental_local_results(result)
self.assertIsInstance(local_result, tuple)
self.assertLen(local_result, self.num_local_devices)
for i in range(self.num_local_devices):
self.assertDictEqual(
local_result[i],
{
'a': constant_op.constant([16.0]),
'b': constant_op.constant([18.0, 20.0]),
},
)
| MultiWorkerMirroredStrategyTest |
python | google__jax | tests/lax_vmap_test.py | {
"start": 1171,
"end": 33419
} | class ____(jtu.JaxTestCase):
def _CheckBatching(self, op, bdim_size, bdims, shapes, dtypes, rng,
rtol=None, atol=None, multiple_results=False):
batched_shapes = map(partial(lax_test_util.add_bdim, bdim_size), bdims, shapes)
args = [rng(shape, dtype) for shape, dtype in zip(batched_shapes, dtypes)]
args_slice = lax_test_util.args_slicer(args, bdims)
ans = jax.vmap(op, bdims)(*args)
if bdim_size == 0:
args = [rng(shape, dtype) for shape, dtype in zip(shapes, dtypes)]
out = op(*args)
if not multiple_results:
expected = np.zeros((0,) + out.shape, out.dtype)
else:
expected = [np.zeros((0,) + o.shape, o.dtype) for o in out]
else:
outs = [op(*args_slice(i)) for i in range(bdim_size)]
if not multiple_results:
expected = np.stack(outs)
else:
expected = [np.stack(xs) for xs in zip(*outs)]
self.assertAllClose(ans, expected, rtol=rtol, atol=atol)
@jtu.sample_product(
[dict(lhs_shape=lhs_shape, rhs_shape=rhs_shape,
batch_group_count=batch_group_count,
feature_group_count=feature_group_count)
for batch_group_count, feature_group_count in [(1, 1), (2, 1), (1, 2)]
for b, i, j in itertools.product([1, 2], repeat=3)
for lhs_shape in [(b * batch_group_count, i * feature_group_count, 6, 7)]
for rhs_shape in [(j * batch_group_count * feature_group_count, i, 1, 2)]],
[dict(lhs_bdim=lhs_bdim, rhs_bdim=rhs_bdim)
for lhs_bdim in itertools.chain([cast(Union[int, None], None)], range(5))
for rhs_bdim in itertools.chain([cast(Union[int, None], None)], range(5))
if (lhs_bdim, rhs_bdim) != (None, None)
],
[dict(dimension_numbers=dim_nums, perms=perms)
for dim_nums, perms in [
(("NCHW", "OIHW", "NCHW"), ([0, 1, 2, 3], [0, 1, 2, 3])),
(("NHWC", "HWIO", "NHWC"), ([0, 2, 3, 1], [2, 3, 1, 0])),
(("NHWC", "OIHW", "NCHW"), ([0, 2, 3, 1], [0, 1, 2, 3])),
(("HWCN", "HWIO", "HWCN"), ([2, 3, 1, 0], [2, 3, 1, 0])),
]],
strides=[(1, 1), (1, 2), (2, 1)],
padding=[((0, 0), (0, 0)), ((1, 0), (0, 1)), ((0, -1), (0, 0))],
lhs_dil=[(1, 1), (2, 1)],
rhs_dil=[(1, 1), (2, 2)],
bdim_size=list(range(5)),
dtype=[np.float32],
)
def testConvGeneralDilatedBatching(
self, lhs_shape, rhs_shape, dtype, strides, padding, lhs_dil, rhs_dil,
dimension_numbers, perms, feature_group_count, batch_group_count,
lhs_bdim, rhs_bdim, bdim_size):
rng = jtu.rand_default(self.rng())
tol = 1e-1 if dtypes.finfo(dtype).bits <= 32 else 1e-3
# permute shapes to match dim_spec, scale by feature_group_count
lhs_perm, rhs_perm = perms
lhs_shape = list(np.take(lhs_shape, lhs_perm))
rhs_shape = list(np.take(rhs_shape, rhs_perm))
conv = partial(lax.conv_general_dilated, window_strides=strides,
padding=padding, lhs_dilation=lhs_dil, rhs_dilation=rhs_dil,
dimension_numbers=dimension_numbers,
feature_group_count=feature_group_count,
batch_group_count=batch_group_count,
precision=lax.Precision.HIGHEST)
self._CheckBatching(conv, bdim_size, (lhs_bdim, rhs_bdim),
(lhs_shape, rhs_shape), (dtype, dtype), rng, rtol=tol,
atol=tol)
@jtu.sample_product(
[dict(from_dtype=f, to_dtype=t)
for f, t in itertools.product([np.float32, np.int32, "float32", "int32"],
repeat=2)
],
[dict(shape=shape, bdims=bdims)
for shape in [(2, 3)] for bdims in lax_test_util.all_bdims(shape)]
)
def testConvertElementType(self, shape, from_dtype, to_dtype, bdims):
rng = jtu.rand_default(self.rng())
op = lambda x: lax.convert_element_type(x, to_dtype)
self._CheckBatching(op, 10, bdims, (shape,), (from_dtype,), rng)
@jtu.sample_product(
[dict(shape=shape, bdims=bdims)
for shape in [(2, 4)] for bdims in lax_test_util.all_bdims(shape)],
dtype=lax_test_util.float_dtypes,
nexp=[1, 3, 5],
nmant=[0, 2, 4],
)
def testReducePrecision(self, shape, dtype, nmant, nexp, bdims):
rng = jtu.rand_default(self.rng())
op = lambda x: lax.reduce_precision(x, exponent_bits=nexp, mantissa_bits=nmant)
self._CheckBatching(op, 10, bdims, (shape,), (dtype,), rng)
@jtu.sample_product(
[dict(from_dtype=f, to_dtype=t)
for f, t in itertools.product([np.float32, np.int32, "float32", "int32"],
repeat=2)
],
[dict(shape=shape, bdims=bdims)
for shape in [(2, 3)] for bdims in lax_test_util.all_bdims(shape)]
)
def testBitcastElementType(self, shape, from_dtype, to_dtype, bdims,):
rng = jtu.rand_default(self.rng())
op = lambda x: lax.bitcast_convert_type(x, to_dtype)
self._CheckBatching(op, 10, bdims, (shape,), (from_dtype,), rng)
@jtu.sample_product(
[dict(min_shape=min_shape, operand_shape=operand_shape, max_shape=max_shape,
bdims=bdims)
for min_shape, operand_shape, max_shape in [
[(), (2, 3), ()],
[(2, 3), (2, 3), ()],
[(), (2, 3), (2, 3)],
[(2, 3), (2, 3), (2, 3)],
]
for bdims in lax_test_util.all_bdims(min_shape, operand_shape, max_shape)
],
dtype=lax_test_util.default_dtypes,
)
def testClamp(self, min_shape, operand_shape, max_shape, dtype, bdims):
rng = jtu.rand_default(self.rng())
shapes = [min_shape, operand_shape, max_shape]
self._CheckBatching(lax.clamp, 10, bdims, shapes, [dtype] * 3, rng)
@jtu.sample_product(
[dict(lhs_shape=lhs_shape, rhs_shape=rhs_shape, bdims=bdims)
for lhs_shape in [(3,), (4, 3)] for rhs_shape in [(3,), (3, 6)]
for bdims in lax_test_util.all_bdims(lhs_shape, rhs_shape)],
dtype=lax_test_util.default_dtypes,
)
def testDot(self, lhs_shape, rhs_shape, dtype, bdims):
rng = jtu.rand_default(self.rng())
op = partial(lax.dot, precision=lax.Precision.HIGHEST)
self._CheckBatching(op, 5, bdims, (lhs_shape, rhs_shape), (dtype, dtype),
rng, rtol={np.float16: 5e-2, np.float64: 5e-14})
@jtu.sample_product(
[dict(bdims=bdims, lhs_shape=lhs_shape, rhs_shape=rhs_shape,
lhs_contracting=lhs_contracting, rhs_contracting=rhs_contracting)
for lhs_shape, rhs_shape, lhs_contracting, rhs_contracting in [
[(5,), (5,), [0], [0]],
[(5, 7), (5,), [0], [0]],
[(7, 5), (5,), [1], [0]],
[(3, 5), (2, 5), [1], [1]],
[(5, 3), (5, 2), [0], [0]],
[(5, 3, 2), (5, 2, 4), [0], [0]],
[(5, 3, 2), (5, 2, 4), [0,2], [0,1]],
[(5, 3, 2), (3, 5, 2, 4), [0,2], [1,2]],
[(1, 2, 2, 3), (1, 2, 3, 1), [1], [1]],
[(3, 2), (2, 4), [1], [0]],
]
for bdims in lax_test_util.all_bdims(lhs_shape, rhs_shape)],
dtype=lax_test_util.default_dtypes,
)
def testDotGeneralContractOnly(self, lhs_shape, rhs_shape, dtype,
lhs_contracting, rhs_contracting, bdims):
rng = jtu.rand_small(self.rng())
dimension_numbers = ((lhs_contracting, rhs_contracting), ([], []))
dot = partial(lax.dot_general, dimension_numbers=dimension_numbers)
self._CheckBatching(dot, 5, bdims, (lhs_shape, rhs_shape), (dtype, dtype),
rng)
@jtu.sample_product(
[dict(lhs_shape=lhs_shape, rhs_shape=rhs_shape,
dimension_numbers=dimension_numbers, bdims=bdims)
for lhs_shape, rhs_shape, dimension_numbers in [
((3, 3, 2), (3, 2, 4), (([2], [1]), ([0], [0]))),
((3, 3, 2), (2, 3, 4), (([2], [0]), ([0], [1]))),
((3, 4, 2, 4), (3, 4, 3, 2), (([2], [3]), ([0, 1], [0, 1]))),
]
for bdims in lax_test_util.all_bdims(lhs_shape, rhs_shape)],
dtype=lax_test_util.default_dtypes)
def testDotGeneralContractAndBatch(self, lhs_shape, rhs_shape, dtype,
dimension_numbers, bdims):
rng = jtu.rand_small(self.rng())
dot = partial(lax.dot_general, dimension_numbers=dimension_numbers)
self._CheckBatching(dot, 5, bdims, (lhs_shape, rhs_shape), (dtype, dtype),
rng)
# Checks that batching didn't introduce any transposes or broadcasts.
jaxpr = jax.make_jaxpr(dot)(np.zeros(lhs_shape, dtype),
np.zeros(rhs_shape, dtype))
for eqn in jtu.iter_eqns(jaxpr.jaxpr):
self.assertFalse(eqn.primitive in ["transpose", "broadcast"])
@jtu.sample_product(
[dict(shape=shape, bdims=bdims)
for shape in [(), (2, 3)] for bdims in lax_test_util.all_bdims(shape)],
dtype=lax_test_util.default_dtypes,
broadcast_sizes=[(), (2,), (1, 2)],
)
def testBroadcast(self, shape, dtype, broadcast_sizes, bdims):
rng = jtu.rand_default(self.rng())
op = lambda x: lax.broadcast(x, broadcast_sizes)
self._CheckBatching(op, 5, bdims, (shape,), (dtype,), rng)
@jtu.sample_product(
[dict(inshape=inshape, outshape=outshape,
broadcast_dimensions=broadcast_dimensions, bdims=bdims)
for inshape, outshape, broadcast_dimensions in [
([2], [2, 2], [0]),
([2], [2, 2], [1]),
([2], [2, 3], [0]),
([], [2, 3], []),
]
for bdims in lax_test_util.all_bdims(inshape)],
dtype=lax_test_util.default_dtypes,
)
@unittest.skip("this test has failures in some cases") # TODO(mattjj)
def testBroadcastInDim(self, inshape, dtype, outshape, dimensions, bdims):
rng = jtu.rand_default(self.rng())
op = lambda x: lax.broadcast_in_dim(x, outshape, dimensions)
self._CheckBatching(op, 5, bdims, (inshape,), (dtype,), rng)
@jtu.sample_product(
[dict(arg_shape=arg_shape, dimensions=dimensions, bdims=bdims)
for arg_shape, dimensions in [
[(1,), (0,)],
[(1,), (-1,)],
[(2, 1, 4), (1,)],
[(2, 1, 4), (-2,)],
[(2, 1, 3, 1), (1,)],
[(2, 1, 3, 1), (1, 3)],
[(2, 1, 3, 1), (3,)],
[(2, 1, 3, 1), (1, -1)],
]
for bdims in lax_test_util.all_bdims(arg_shape)],
)
def testSqueeze(self, arg_shape, dimensions, bdims):
dtype = np.float32
rng = jtu.rand_default(self.rng())
op = lambda x: lax.squeeze(x, dimensions)
self._CheckBatching(op, 10, bdims, (arg_shape,), (dtype,), rng)
@jtu.sample_product(
[dict(arg_shape=arg_shape, out_shape=out_shape, dimensions=dimensions,
bdims=bdims)
for arg_shape, dimensions, out_shape in [
[(3, 4), None, (12,)],
[(2, 1, 4), None, (8,)],
[(2, 2, 4), None, (2, 8)],
[(2, 2, 4), (0, 1, 2), (2, 8)],
[(2, 2, 4), (1, 0, 2), (8, 2)],
[(2, 2, 4), (2, 1, 0), (4, 2, 2)]
]
for bdims in lax_test_util.all_bdims(arg_shape)],
dtype=lax_test_util.default_dtypes,
)
def testReshape(self, arg_shape, out_shape, dtype, dimensions, bdims):
rng = jtu.rand_default(self.rng())
op = lambda x: lax.reshape(x, out_shape, dimensions=dimensions)
self._CheckBatching(op, 10, bdims, (arg_shape,), (dtype,), rng)
@jtu.sample_product(
[dict(shape=shape, bdims=bdims)
for shape in [(2, 3)] for bdims in lax_test_util.all_bdims(shape, ())],
dtype=lax_test_util.default_dtypes,
pads=[[(1, 2, 1), (0, 1, 0)]],
)
def testPad(self, shape, dtype, pads, bdims):
rng = jtu.rand_small(self.rng())
fun = lambda operand, padding: lax.pad(operand, padding, pads)
self._CheckBatching(fun, 5, bdims, (shape, ()), (dtype, dtype), rng)
@jtu.sample_product(
[dict(arg_shape=arg_shape, pred_shape=pred_shape, bdims=bdims)
for arg_shape in [(), (3,), (2, 3)]
for pred_shape in ([(), arg_shape] if arg_shape else [()])
for bdims in lax_test_util.all_bdims(pred_shape, arg_shape, arg_shape)],
arg_dtype=lax_test_util.default_dtypes,
)
def testSelect(self, pred_shape, arg_shape, arg_dtype, bdims):
rng = jtu.rand_default(self.rng())
op = lambda c, x, y: lax.select(c < 0, x, y)
self._CheckBatching(op, 5, bdims, (pred_shape, arg_shape, arg_shape,),
(arg_dtype, arg_dtype, arg_dtype), rng)
@jtu.sample_product(
[dict(shape=shape, starts=start_indices, limits=limit_indices,
strides=strides, bdims=bdims)
for shape, start_indices, limit_indices, strides in [
[(3,), (1,), (2,), None],
[(7,), (4,), (7,), None],
[(5,), (1,), (5,), (2,)],
[(8,), (1,), (6,), (2,)],
[(5, 3), (1, 1), (3, 2), None],
[(5, 3), (1, 1), (3, 1), None],
[(7, 5, 3), (4, 0, 1), (7, 1, 3), None],
[(5, 3), (1, 1), (2, 1), (1, 1)],
[(5, 3), (1, 1), (5, 3), (2, 1)],
]
for bdims in lax_test_util.all_bdims(shape)
],
dtype=lax_test_util.default_dtypes,
)
def testSlice(self, shape, dtype, starts, limits, strides, bdims):
rng = jtu.rand_default(self.rng())
op = lambda x: lax.slice(x, starts, limits, strides)
self._CheckBatching(op, 5, bdims, (shape,), (dtype,), rng)
@jtu.sample_product(
[dict(base_shape=base_shape, axis=axis, bdims=bdims)
for base_shape in [(4,), (3, 4), (2, 3, 4)]
for axis in range(len(base_shape))
for bdims in lax_test_util.all_bdims(base_shape)
],
num_pieces=range(3),
dtype=lax_test_util.default_dtypes,
)
def testSplit(self, base_shape, dtype, num_pieces, axis, bdims):
sizes = jtu.rand_int(self.rng(), 5)((num_pieces + 1,), np.int64)
shape = list(base_shape)
shape[axis] = np.sum(sizes)
rng = jtu.rand_default(self.rng())
op = lambda x: lax.split(x, sizes, axis)
self._CheckBatching(op, 5, bdims, (shape,), (dtype,), rng,
multiple_results=True)
@jtu.sample_product(
[dict(shape=shape, perm=perm, bdims=bdims)
for shape, perm in [
[(3, 4), (1, 0)],
[(3, 4), (0, 1)],
[(3, 4, 5), (2, 1, 0)],
[(3, 4, 5), (1, 0, 2)],
]
for bdims in lax_test_util.all_bdims(shape)
],
dtype=lax_test_util.default_dtypes,
)
def testTranspose(self, shape, dtype, perm, bdims):
rng = jtu.rand_default(self.rng())
op = lambda x: lax.transpose(x, perm)
self._CheckBatching(op, 5, bdims, (shape,), (dtype,), rng)
@jtu.sample_product(
[dict(init_val=init_val, op=op, dtype=dtype)
for init_val, op, dtypes in [
(0, lax.add, lax_test_util.default_dtypes),
(1, lax.mul, lax_test_util.default_dtypes),
# non-monoidal for everything except unsigned integers
(0, lax.max, lax_test_util.all_dtypes),
(-np.inf, lax.max, lax_test_util.float_dtypes),
(dtypes.iinfo(np.int32).min, lax.max, [np.int32]),
(dtypes.iinfo(np.int64).min, lax.max, [np.int64]),
(np.inf, lax.min, lax_test_util.float_dtypes),
(dtypes.iinfo(np.int32).max, lax.min, [np.int32]),
(dtypes.iinfo(np.int64).max, lax.min, [np.int64]),
(dtypes.iinfo(np.uint32).max, lax.min, [np.uint32]),
(dtypes.iinfo(np.uint64).max, lax.min, [np.uint64]),
]
for dtype in dtypes],
[dict(shape=shape, dims=dims, bdims=bdims)
for shape, dims in [
[(3, 4, 5), (0,)], [(3, 4, 5), (1, 2)],
[(3, 4, 5), (0, 2)], [(3, 4, 5), (0, 1, 2)]
]
for bdims in lax_test_util.all_bdims(shape)],
)
def testReduce(self, op, init_val, shape, dtype, dims, bdims):
rng = jtu.rand_small(self.rng())
init_val = np.asarray(init_val, dtype=dtype)
fun = lambda operand: lax.reduce(operand, init_val, op, dims)
self._CheckBatching(fun, 5, bdims, (shape,), (dtype,), rng)
@jtu.sample_product(
[dict(shape=shape, dims=dims, bdims=bdims)
for shape, dims in [
[(3, 4, 5), (0,)], [(3, 4, 5), (1, 2)],
[(3, 4, 5), (0, 2)], [(3, 4, 5), (0, 1, 2)]
]
for bdims in lax_test_util.all_bdims(shape, shape)],
dtype=lax_test_util.default_dtypes,
)
def testVariadicReduce(self, shape, dtype, dims, bdims):
def op(a, b):
x1, y1 = a
x2, y2 = b
return x1 + x2, y1 * y2
rng = jtu.rand_small(self.rng())
init_val = tuple(np.asarray([0, 1], dtype=dtype))
fun = lambda x, y: lax.reduce((x, y), init_val, op, dims)
self._CheckBatching(fun, 5, bdims, (shape, shape), (dtype, dtype), rng,
multiple_results=True)
@jtu.sample_product(
[dict(shape=shape, bdims=bdims, dim=dim)
for shape in [(3, 4, 5)]
for bdims in lax_test_util.all_bdims(shape)
for dim in range(len(shape))],
op=[lax.argmin, lax.argmax],
dtype=lax_test_util.default_dtypes,
)
def testArgminmax(self, op, shape, dtype, dim, bdims):
rng = jtu.rand_default(self.rng())
fun = lambda operand: op(operand, dim, np.int32)
self._CheckBatching(fun, 5, bdims, (shape,), (dtype,), rng)
@jtu.sample_product(
[dict(init_val=init_val, op=op, dtype=dtype)
for init_val, op, dtypes in [
(0, lax.add, [np.float32]),
(-np.inf, lax.max, [np.float32]),
(np.inf, lax.min, [np.float32]),
]
for dtype in dtypes],
[dict(shape=shape, dims=dims, strides=strides, padding=padding,
base_dilation=base_dilation, window_dilation=window_dilation)
for shape, dims, strides, padding, base_dilation, window_dilation in (
itertools.chain(
itertools.product(
[(4, 6)],
[(2, 1), (1, 2)],
[(1, 1), (2, 1), (1, 2)],
["VALID", "SAME", [(0, 3), (1, 2)]],
[(1, 1), (2, 3)],
[(1, 1), (1, 2)]),
itertools.product(
[(3, 2, 4, 6)], [(1, 1, 2, 1), (2, 1, 2, 1)],
[(1, 2, 2, 1), (1, 1, 1, 1)],
["VALID", "SAME", [(0, 1), (1, 0), (2, 3), (0, 2)]],
[(1, 1, 1, 1), (2, 1, 3, 2)],
[(1, 1, 1, 1), (1, 2, 2, 1)])))
],
)
def testReduceWindow(self, op, init_val, dtype, shape, dims, strides, padding,
base_dilation, window_dilation):
rng = jtu.rand_small(self.rng())
init_val = np.asarray(init_val, dtype=dtype)
def fun(operand):
return lax.reduce_window(operand, init_val, op, dims, strides, padding,
base_dilation, window_dilation)
for bdims in lax_test_util.all_bdims(shape):
self._CheckBatching(fun, 3, bdims, (shape,), (dtype,), rng)
@jtu.sample_product(
[dict(op=op, dtype=dtype)
for op, types in [
(lax.cumsum, [np.float32, np.float64]),
(lax.cumprod, [np.float32, np.float64]),
]
for dtype in types],
[dict(shape=shape, bdims=bdims, axis=axis)
for shape in [[10], [3, 4, 5]]
for axis in range(len(shape))
for bdims in lax_test_util.all_bdims(shape)],
reverse=[False, True],
)
def testCumulativeReduce(self, op, shape, dtype, axis, bdims, reverse):
rng_factory = (jtu.rand_default if dtypes.issubdtype(dtype, np.integer)
else jtu.rand_small)
rng = rng_factory(self.rng())
self._CheckBatching(partial(op, axis=axis, reverse=reverse), 7, bdims,
(shape,), (dtype,), rng)
@jtu.sample_product(
[dict(shape=shape, dims=dims, strides=strides, bdims=bdims)
for shape, dims, strides in itertools.chain(
itertools.product(
[(4, 6)],
[(2, 1), (1, 2)],
[(1, 1), (2, 1), (1, 2)]),
itertools.product(
[(3, 2, 4, 6)], [(1, 1, 2, 1), (2, 1, 2, 1)],
[(1, 2, 2, 1), (1, 1, 1, 1)]))
for bdims in lax_test_util.all_bdims(shape, shape)
],
dtype=lax_test_util.float_dtypes,
padding=["VALID", "SAME"]
)
@jtu.ignore_warning(message="Using reduced precision for gradient.*")
def testSelectAndGatherAdd(self, dtype, padding, shape, dims, strides, bdims):
rng = jtu.rand_small(self.rng())
def fun(operand, tangents):
pads = lax.padtype_to_pads(operand.shape, dims, strides, padding)
ones = (1,) * len(operand.shape)
return lax_windowed_reductions._select_and_gather_add(
operand, tangents, lax.ge_p, dims, strides, pads, ones, ones)
self._CheckBatching(fun, 3, bdims, (shape, shape), (dtype, dtype), rng)
@jtu.sample_product(
dtype=lax_test_util.float_dtypes,
padding=["VALID", "SAME"],
shape=[(3, 2, 4, 6)],
dims=[(1, 1, 2, 1)],
strides=[(1, 2, 2, 1), (1, 1, 1, 1)],
)
def testSelectAndScatterAdd(self, dtype, padding, shape, dims, strides):
rng = jtu.rand_small(self.rng())
pads = lax.padtype_to_pads(shape, dims, strides, padding)
def fun(operand, cotangents):
return lax_windowed_reductions._select_and_scatter_add(
operand, cotangents, lax.ge_p, dims, strides, pads)
ones = (1,) * len(shape)
cotangent_shape = jax.eval_shape(
lambda x: lax_windowed_reductions._select_and_gather_add(
x, x, lax.ge_p, dims, strides, pads, ones, ones),
np.ones(shape, dtype)).shape
for bdims in lax_test_util.all_bdims(cotangent_shape, shape):
self._CheckBatching(fun, 3, bdims, (cotangent_shape, shape),
(dtype, dtype), rng)
@jtu.sample_product(
[dict(shape=shape, fft_ndims=fft_ndims, bdims=bdims)
for shape in [(5,), (3, 4, 5), (2, 3, 4, 5)]
for bdims in lax_test_util.all_bdims(shape)
for fft_ndims in range(0, min(3, len(shape)) + 1)],
)
def testFft(self, fft_ndims, shape, bdims):
rng = jtu.rand_default(self.rng())
ndims = len(shape)
axes = range(ndims - fft_ndims, ndims)
fft_lengths = tuple(shape[axis] for axis in axes)
op = lambda x: lax.fft(x, lax.FftType.FFT, fft_lengths)
self._CheckBatching(op, 5, bdims, [shape], [np.complex64], rng,
rtol=1e-5)
@jtu.sample_product(
[dict(shape=shape, idxs=idxs, dnums=dnums, slice_sizes=slice_sizes,
bdims=bdims)
for shape, idxs, dnums, slice_sizes in [
((5,), np.array([[0], [2]]), lax.GatherDimensionNumbers(
offset_dims=(), collapsed_slice_dims=(0,), start_index_map=(0,)),
(1,)),
((10,), np.array([[0], [0], [0]]), lax.GatherDimensionNumbers(
offset_dims=(1,), collapsed_slice_dims=(), start_index_map=(0,)),
(2,)),
((10, 5,), np.array([[0], [2], [1]]), lax.GatherDimensionNumbers(
offset_dims=(1,), collapsed_slice_dims=(0,), start_index_map=(0,)),
(1, 3)),
((10, 5), np.array([[0, 2], [1, 0]]), lax.GatherDimensionNumbers(
offset_dims=(1,), collapsed_slice_dims=(0,), start_index_map=(0, 1)),
(1, 3)),
((2, 5), np.array([[[0], [2]], [[1], [1]]]),
lax.GatherDimensionNumbers(
offset_dims=(), collapsed_slice_dims=(1,),
start_index_map=(1,), operand_batching_dims=(0,),
start_indices_batching_dims=(0,)),
(1, 1)),
((2, 3, 10), np.array([[[0], [1]], [[2], [3]], [[4], [5]]]),
lax.GatherDimensionNumbers(
offset_dims=(2,), collapsed_slice_dims=(),
start_index_map=(2,), operand_batching_dims=(0, 1),
start_indices_batching_dims=(1, 0)),
(1, 1, 3))
]
for bdims in lax_test_util.all_bdims(shape, idxs.shape)],
dtype=lax_test_util.all_dtypes
)
def testGather(self, shape, dtype, idxs, dnums, slice_sizes, bdims):
fun = partial(lax.gather, dimension_numbers=dnums, slice_sizes=slice_sizes)
self._CheckBatching(fun, 0, bdims, [shape, idxs.shape], [dtype, idxs.dtype],
jtu.rand_default(self.rng()))
self._CheckBatching(fun, 5, bdims, [shape, idxs.shape], [dtype, idxs.dtype],
jtu.rand_default(self.rng()))
@jtu.sample_product(
[dict(arg_shape=arg_shape, idxs=idxs, update_shape=update_shape,
dnums=dnums, bdims=bdims)
for arg_shape, idxs, update_shape, dnums in [
((5,), np.array([[0], [2]]), (2,), lax.ScatterDimensionNumbers(
update_window_dims=(), inserted_window_dims=(0,),
scatter_dims_to_operand_dims=(0,))),
((10,), np.array([[0], [0], [0]]), (3, 2), lax.ScatterDimensionNumbers(
update_window_dims=(1,), inserted_window_dims=(),
scatter_dims_to_operand_dims=(0,))),
((10, 5,), np.array([[0], [2], [1]]), (3, 3), lax.ScatterDimensionNumbers(
update_window_dims=(1,), inserted_window_dims=(0,),
scatter_dims_to_operand_dims=(0,))),
((2, 5), np.array([[[0], [2]], [[1], [1]]]), (2, 2),
lax.ScatterDimensionNumbers(
update_window_dims=(), inserted_window_dims=(1,),
scatter_dims_to_operand_dims=(1,), operand_batching_dims=(0,),
scatter_indices_batching_dims=(0,))),
((2, 3, 10), np.array([[[0], [1]], [[2], [3]], [[4], [5]]]),
(3, 2, 3), lax.ScatterDimensionNumbers(
update_window_dims=(2,), inserted_window_dims=(),
scatter_dims_to_operand_dims=(2,), operand_batching_dims=(0, 1),
scatter_indices_batching_dims=(1, 0)))
]
for bdims in lax_test_util.all_bdims(arg_shape, idxs.shape, update_shape)],
dtype=lax_test_util.float_dtypes
)
def testScatterAdd(self, arg_shape, dtype, idxs, update_shape, dnums, bdims):
fun = partial(lax.scatter_add, dimension_numbers=dnums)
self._CheckBatching(fun, 5, bdims, [arg_shape, idxs.shape, update_shape],
[dtype, idxs.dtype, dtype], jtu.rand_default(self.rng()),
rtol={np.float16: 5e-3, dtypes.bfloat16: 7e-2})
@jtu.sample_product(
[dict(arg_shape=arg_shape, idxs=idxs, update_shape=update_shape,
dnums=dnums, bdims=bdims)
for arg_shape, idxs, update_shape, dnums in [
((5,), np.array([[0], [2]]), (2,), lax.ScatterDimensionNumbers(
update_window_dims=(), inserted_window_dims=(0,),
scatter_dims_to_operand_dims=(0,))),
((10,), np.array([[0], [0], [0]]), (3, 2), lax.ScatterDimensionNumbers(
update_window_dims=(1,), inserted_window_dims=(),
scatter_dims_to_operand_dims=(0,))),
((10, 5,), np.array([[0], [2], [1]]), (3, 3), lax.ScatterDimensionNumbers(
update_window_dims=(1,), inserted_window_dims=(0,),
scatter_dims_to_operand_dims=(0,))),
((2, 5), np.array([[[0], [2]], [[1], [1]]]), (2, 2),
lax.ScatterDimensionNumbers(
update_window_dims=(), inserted_window_dims=(1,),
scatter_dims_to_operand_dims=(1,), operand_batching_dims=(0,),
scatter_indices_batching_dims=(0,))),
((2, 3, 10), np.array([[[0], [1]], [[2], [3]], [[4], [5]]]),
(3, 2, 3), lax.ScatterDimensionNumbers(
update_window_dims=(2,), inserted_window_dims=(),
scatter_dims_to_operand_dims=(2,), operand_batching_dims=(0, 1),
scatter_indices_batching_dims=(1, 0)))
]
for bdims in lax_test_util.all_bdims(arg_shape, idxs.shape)],
dtype=lax_test_util.float_dtypes,
)
def testScatterApply(self, arg_shape, dtype, idxs, update_shape, dnums, bdims):
fun = partial(lax.scatter_apply, func=jnp.sin, update_shape=update_shape, dimension_numbers=dnums)
self._CheckBatching(fun, 5, bdims, [arg_shape, idxs.shape],
[dtype, idxs.dtype], jtu.rand_default(self.rng()),
rtol={np.float16: 5e-3, dtypes.bfloat16: 7e-2})
def testShapeUsesBuiltinInt(self):
x = lax.iota(np.int32, 3) + 1
self.assertIsInstance(x.shape[0], int) # not np.int64
def testBroadcastShapesReturnsPythonInts(self):
shape1, shape2 = (1, 2, 3), (2, 3)
out_shape = lax.broadcast_shapes(shape1, shape2)
self.assertTrue(all(type(s) is int for s in out_shape))
def testBroadcastShapesFaultyInputs(self):
err_shape1, err_shape2 = (-1,), "hello"
# negative inputs should fail while informing about illegal negative indices...
with self.assertRaisesRegex(TypeError, "Only non-negative indices are allowed.*"):
lax.broadcast_shapes(err_shape1)
# ... while non-integers should error earlier, in the canonicalize_shape machinery.
with self.assertRaisesRegex(TypeError, "Shapes must be 1D sequences.*"):
lax.broadcast_shapes(err_shape2) # pytype: disable=wrong-arg-types
@jtu.sample_product(
[dict(shape=shape, bdims=bdims)
for shape in [(4,), (3, 5, 3)]
for bdims in lax_test_util.all_bdims(shape)],
k=[1, 3],
axis=[0, -1],
dtype=lax_test_util.default_dtypes,
)
# The top_k indices for integer arrays with identical entries won't match between
# vmap'd version and manual reference, so only test unique integer arrays for int_dtypes.
# Note also that we chose 3 * 5 * 3 * 5 such that it fits in the range of
# values a bfloat16 can represent exactly to avoid ties.
def testTopK(self, shape, dtype, k, bdims, axis):
rng = jtu.rand_int(self.rng(), high=math.prod(shape))
# _CheckBatching doesn't work with tuple outputs, so test outputs separately.
op1 = lambda x: lax.top_k(x, k=k, axis=axis)[0]
self._CheckBatching(op1, 5, bdims, (shape,), (dtype,), rng)
op2 = lambda x: lax.top_k(x, k=k, axis=axis)[1]
self._CheckBatching(op2, 5, bdims, (shape,), (dtype,), rng)
@jtu.sample_product(
[dict(shape=shape, bdims=bdims)
for shape in [(8,), (3, 4, 5)]
for bdims in lax_test_util.all_bdims(shape)],
dtype=lax_test_util.default_dtypes,
)
def test_optimization_barrier_vmap(self, shape, dtype, bdims):
rng = jtu.rand_small(self.rng())
self._CheckBatching(lax.optimization_barrier, 5, bdims, (shape,), (dtype,),
rng)
def test_optimization_barrier_vmap_out_axes(self):
x = jnp.arange(8)
y = x.reshape(1, 8)
out = jax.vmap(lax.optimization_barrier, in_axes=((0, 1),),
out_axes=(0, 1))((x, y))
self.assertArraysEqual(out[0], x)
self.assertArraysEqual(out[1], y)
@jtu.sample_product(
[dict(shape=shape, bdims=bdims, dimension=dimension, arity=arity)
for shape in [(2, 3)]
for dimension in [0, 1]
for arity in range(3)
for bdims in lax_test_util.all_bdims(*((shape,) * arity))
],
is_stable=[False, True]
)
def testSort(self, shape, dimension, arity, bdims, is_stable):
rng = jtu.rand_default(self.rng())
if arity == 1:
fun = partial(lax.sort, dimension=dimension)
self._CheckBatching(fun, 5, bdims, (shape,) * arity, (np.float32,) * arity,
rng)
else:
for i in range(arity):
fun = lambda *args, i=i: lax.sort(args,
dimension=dimension,
is_stable=is_stable)[i]
self._CheckBatching(fun, 5, bdims, (shape,) * arity,
(np.float32,) * arity, rng)
# TODO Concatenate
# TODO Reverse
# TODO DynamicSlice
# TODO DynamicUpdateSlice
# TODO Collapse
# TODO Scatter
# TODO(b/183233858): variadic reduce-window is not implemented on XLA:GPU
@jtu.skip_on_devices("gpu")
def test_variadic_reduce_window(self):
# https://github.com/jax-ml/jax/discussions/9818 and
# https://github.com/jax-ml/jax/issues/9837
def normpool(x):
norms = jnp.linalg.norm(x, axis=-1)
idxs = jnp.arange(x.shape[0])
def g(a, b):
an, ai = a
bn, bi = b
which = an >= bn
return (jnp.where(which, an, bn), jnp.where(which, ai, bi))
inf = jnp.array(np.inf, dtype=norms.dtype)
one = jnp.array(1, dtype=idxs.dtype)
_, idxs = lax.reduce_window((norms, idxs), (-inf, -one), g,
window_dimensions=(2,), window_strides=(2,),
padding=((0, 0),))
return x[idxs]
inpt = jnp.array([
[1.0, 0.0, 1.0],
[2.0, 2.0, 0.0],
[3.0, 0.0, 1.0],
[0.0, 1.0, 1.0],
])
output = jax.vmap(normpool)(inpt[None, ...]) # doesn't crash
expected = jnp.array([[[2.0, 2.0, 0.0], [3.0, 0.0, 1.0]]])
self.assertAllClose(output, expected, check_dtypes=False)
if __name__ == '__main__':
absltest.main(testLoader=jtu.JaxTestLoader())
| LaxVmapTest |
python | PrefectHQ__prefect | tests/server/orchestration/test_core_policy.py | {
"start": 17471,
"end": 21669
} | class ____:
async def test_retries(
self,
session,
initialize_orchestration,
monkeypatch,
frozen_time,
):
failed_task_runs = [
mock.Mock(id="task_run_001"),
mock.Mock(id="task_run_002"),
]
read_task_runs = AsyncMock(side_effect=lambda *args, **kwargs: failed_task_runs)
monkeypatch.setattr(
"prefect.server.models.task_runs.read_task_runs", read_task_runs
)
set_task_run_state = AsyncMock()
monkeypatch.setattr(
"prefect.server.models.task_runs.set_task_run_state", set_task_run_state
)
retry_policy = [RetryFailedFlows]
initial_state_type = states.StateType.RUNNING
proposed_state_type = states.StateType.FAILED
intended_transition = (initial_state_type, proposed_state_type)
ctx = await initialize_orchestration(
session,
"flow",
*intended_transition,
)
ctx.run.run_count = 1
ctx.run_settings.retries = 1
async with contextlib.AsyncExitStack() as stack:
for rule in retry_policy:
ctx = await stack.enter_async_context(rule(ctx, *intended_transition))
await ctx.validate_proposed_state()
# When retrying a flow any failed tasks should be set to AwaitingRetry
assert ctx.response_status == SetStateStatus.REJECT
assert ctx.validated_state_type == states.StateType.SCHEDULED
async def test_stops_retrying_eventually(
self,
session,
initialize_orchestration,
):
retry_policy = [RetryFailedFlows]
initial_state_type = states.StateType.RUNNING
proposed_state_type = states.StateType.FAILED
intended_transition = (initial_state_type, proposed_state_type)
ctx = await initialize_orchestration(
session,
"flow",
*intended_transition,
)
ctx.run.run_count = 2
ctx.run_settings.retries = 1
async with contextlib.AsyncExitStack() as stack:
for rule in retry_policy:
ctx = await stack.enter_async_context(rule(ctx, *intended_transition))
await ctx.validate_proposed_state()
assert ctx.response_status == SetStateStatus.ACCEPT
assert ctx.validated_state_type == states.StateType.FAILED
async def test_sets_retry_type(
self,
session,
initialize_orchestration,
):
retry_policy = [RetryFailedFlows]
initial_state_type = states.StateType.RUNNING
proposed_state_type = states.StateType.FAILED
intended_transition = (initial_state_type, proposed_state_type)
ctx = await initialize_orchestration(
session,
"flow",
*intended_transition,
)
ctx.run.run_count = 2
ctx.run_settings.retries = 3
async with contextlib.AsyncExitStack() as stack:
for rule in retry_policy:
ctx = await stack.enter_async_context(rule(ctx, *intended_transition))
await ctx.validate_proposed_state()
assert ctx.run.empirical_policy.retry_type == "in_process"
async def test_clears_retry_type_on_exhausted_retries(
self,
session,
initialize_orchestration,
):
"""
Regression test for https://github.com/PrefectHQ/prefect/issues/17913
"""
retry_policy = [RetryFailedFlows]
initial_state_type = states.StateType.RUNNING
proposed_state_type = states.StateType.FAILED
intended_transition = (initial_state_type, proposed_state_type)
ctx = await initialize_orchestration(
session,
"flow",
*intended_transition,
)
ctx.run.run_count = 2
ctx.run_settings.retries = 1
async with contextlib.AsyncExitStack() as stack:
for rule in retry_policy:
ctx = await stack.enter_async_context(rule(ctx, *intended_transition))
await ctx.validate_proposed_state()
assert ctx.run.empirical_policy.retry_type is None
| TestFlowRetryingRule |
python | pypa__hatch | src/hatch/cli/application.py | {
"start": 559,
"end": 7699
} | class ____(Terminal):
def __init__(self, exit_func, *args, **kwargs):
super().__init__(*args, **kwargs)
self.platform = Platform(self.output)
self.__exit_func = exit_func
self.config_file = ConfigFile()
self.quiet = self.verbosity < 0
self.verbose = self.verbosity > 0
# Lazily set these as we acquire more knowledge about the environment
self.data_dir = cast(Path, None)
self.cache_dir = cast(Path, None)
self.project = cast(Project, None)
self.env = cast(str, None)
self.env_active = cast(str, None)
@property
def plugins(self):
return self.project.plugin_manager
@property
def config(self) -> RootConfig:
return self.config_file.model
def get_environment(self, env_name: str | None = None) -> EnvironmentInterface:
return self.project.get_environment(env_name)
def prepare_environment(self, environment: EnvironmentInterface):
self.project.prepare_environment(environment)
def run_shell_commands(self, context: ExecutionContext) -> None:
with context.env.command_context():
try:
resolved_commands = list(context.env.resolve_commands(context.shell_commands))
except Exception as e: # noqa: BLE001
self.abort(str(e))
first_error_code = None
should_display_command = not context.hide_commands and (self.verbose or len(resolved_commands) > 1)
for i, raw_command in enumerate(resolved_commands, 1):
if should_display_command:
self.display_info(f"{context.source} [{i}] | {raw_command}")
command = raw_command
continue_on_error = context.force_continue
if raw_command.startswith("- "):
continue_on_error = True
command = command[2:]
process = context.env.run_shell_command(command)
sys.stdout.flush()
sys.stderr.flush()
if process.returncode:
first_error_code = first_error_code or process.returncode
if continue_on_error:
continue
if context.show_code_on_error:
self.abort(f"Failed with exit code: {process.returncode}", code=process.returncode)
else:
self.abort(code=process.returncode)
if first_error_code and context.force_continue:
self.abort(code=first_error_code)
def runner_context(
self,
environments: list[str],
*,
ignore_compat: bool = False,
display_header: bool = False,
) -> Generator[ExecutionContext, None, None]:
if self.verbose or len(environments) > 1:
display_header = True
any_compatible = False
incompatible = {}
with self.project.ensure_cwd():
for env_name in environments:
environment = self.get_environment(env_name)
if not environment.exists():
try:
environment.check_compatibility()
except Exception as e: # noqa: BLE001
if ignore_compat:
incompatible[environment.name] = str(e)
continue
self.abort(f"Environment `{env_name}` is incompatible: {e}")
any_compatible = True
if display_header:
self.display_header(environment.name)
context = ExecutionContext(environment)
yield context
self.prepare_environment(environment)
self.execute_context(context)
if incompatible:
num_incompatible = len(incompatible)
padding = "\n" if any_compatible else ""
self.display_warning(
f"{padding}Skipped {num_incompatible} incompatible environment{'s' if num_incompatible > 1 else ''}:"
)
for env_name, reason in incompatible.items():
self.display_warning(f"{env_name} -> {reason}")
def execute_context(self, context: ExecutionContext) -> None:
from hatch.utils.structures import EnvVars
with EnvVars(context.env_vars):
self.run_shell_commands(context)
def ensure_environment_plugin_dependencies(self) -> None:
self.ensure_plugin_dependencies(
self.project.config.env_requires_complex, wait_message="Syncing environment plugin requirements"
)
def ensure_plugin_dependencies(self, dependencies: list[Dependency], *, wait_message: str) -> None:
if not dependencies:
return
from hatch.dep.sync import InstalledDistributions
from hatch.env.utils import add_verbosity_flag
if app_path := os.environ.get("PYAPP"):
from hatch.utils.env import PythonInfo
management_command = os.environ["PYAPP_COMMAND_NAME"]
executable = self.platform.check_command_output([app_path, management_command, "python-path"]).strip()
python_info = PythonInfo(self.platform, executable=executable)
distributions = InstalledDistributions(sys_path=python_info.sys_path)
if distributions.dependencies_in_sync(dependencies):
return
pip_command = [app_path, management_command, "pip"]
else:
distributions = InstalledDistributions()
if distributions.dependencies_in_sync(dependencies):
return
pip_command = [sys.executable, "-u", "-m", "pip"]
pip_command.extend(["install", "--disable-pip-version-check"])
# Default to -1 verbosity
add_verbosity_flag(pip_command, self.verbosity, adjustment=-1)
pip_command.extend(str(dependency) for dependency in dependencies)
with self.status(wait_message):
self.platform.check_command(pip_command)
def get_env_directory(self, environment_type):
directories = self.config.dirs.env
if environment_type in directories:
path = Path(directories[environment_type]).expand()
if os.path.isabs(path):
return path
return self.project.location / path
return self.data_dir / "env" / environment_type
def get_python_manager(self, directory: str | None = None):
from hatch.python.core import PythonManager
configured_dir = directory or self.config.dirs.python
if configured_dir == "isolated":
return PythonManager(self.data_dir / "pythons")
return PythonManager(Path(configured_dir).expand())
@cached_property
def shell_data(self) -> tuple[str, str]:
from hatch.utils.shells import detect_shell
return detect_shell(self.platform)
def abort(self, text="", code=1, **kwargs):
if text:
self.display_error(text, **kwargs)
self.__exit_func(code)
| Application |
python | huggingface__transformers | src/transformers/models/sew_d/modeling_sew_d.py | {
"start": 56184,
"end": 62835
} | class ____(SEWDPreTrainedModel):
def __init__(self, config, target_lang: Optional[str] = None):
r"""
target_lang (`str`, *optional*):
Language id of adapter weights. Adapter weights are stored in the format adapter.<lang>.safetensors or
adapter.<lang>.bin. Only relevant when using an instance of [`SEWDForCTC`] with adapters. Uses 'eng' by
default.
"""
super().__init__(config)
self.sew_d = SEWDModel(config)
self.dropout = nn.Dropout(config.final_dropout)
self.target_lang = target_lang
if config.vocab_size is None:
raise ValueError(
f"You are trying to instantiate {self.__class__} with a configuration that "
"does not define the vocabulary size of the language model head. Please "
"instantiate the model as follows: `SEWDForCTC.from_pretrained(..., vocab_size=vocab_size)`. "
"or define `vocab_size` of your model's configuration."
)
output_hidden_size = (
config.output_hidden_size if hasattr(config, "add_adapter") and config.add_adapter else config.hidden_size
)
self.lm_head = nn.Linear(output_hidden_size, config.vocab_size)
# Initialize weights and apply final processing
self.post_init()
def tie_weights(self, **kwargs):
"""
This method overwrites [`~PreTrainedModel.tie_weights`] so that adapter weights can be correctly loaded when
passing `target_lang=...` to `from_pretrained(...)`.
This method is **not** supposed to be called by the user and is prone to be changed in the future.
"""
# Note that `tie_weights` is usually used to tie input and output embedding weights. The method is re-purposed to
# correctly load adapter layers for SEWD so that we do not have to introduce a new API to
# [`PreTrainedModel`]. While slightly hacky, SEWD never has to tie input and output embeddings, so that it is
# ok to repurpose this function here.
target_lang = self.target_lang
if target_lang is not None and getattr(self.config, "adapter_attn_dim", None) is None:
raise ValueError(f"Cannot pass `target_lang`: {target_lang} if `config.adapter_attn_dim` is not defined.")
elif target_lang is None and getattr(self.config, "adapter_attn_dim", None) is not None:
logger.info("By default `target_lang` is set to 'eng'.")
elif target_lang is not None:
self.load_adapter(target_lang, force_load=True)
def freeze_feature_encoder(self):
"""
Calling this function will disable the gradient computation for the feature encoder so that its parameter will
not be updated during training.
"""
self.sew_d.feature_extractor._freeze_parameters()
def freeze_base_model(self):
"""
Calling this function will disable the gradient computation for the base model so that its parameters will not
be updated during training. Only the classification head will be updated.
"""
for param in self.sew_d.parameters():
param.requires_grad = False
@auto_docstring
def forward(
self,
input_values: Optional[torch.Tensor],
attention_mask: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
labels: Optional[torch.Tensor] = None,
) -> Union[tuple, CausalLMOutput]:
r"""
labels (`torch.LongTensor` of shape `(batch_size, target_length)`, *optional*):
Labels for connectionist temporal classification. Note that `target_length` has to be smaller or equal to
the sequence length of the output logits. Indices are selected in `[-100, 0, ..., config.vocab_size - 1]`.
All labels set to `-100` are ignored (masked), the loss is only computed for labels in `[0, ...,
config.vocab_size - 1]`.
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
if labels is not None and labels.max() >= self.config.vocab_size:
raise ValueError(f"Label values must be <= vocab_size: {self.config.vocab_size}")
outputs = self.sew_d(
input_values,
attention_mask=attention_mask,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
hidden_states = outputs[0]
hidden_states = self.dropout(hidden_states)
logits = self.lm_head(hidden_states)
loss = None
if labels is not None:
# retrieve loss input_lengths from attention_mask
attention_mask = (
attention_mask if attention_mask is not None else torch.ones_like(input_values, dtype=torch.long)
)
input_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(-1)).to(torch.long)
# assuming that padded tokens are filled with -100
# when not being attended to
labels_mask = labels >= 0
target_lengths = labels_mask.sum(-1)
flattened_targets = labels.masked_select(labels_mask)
# ctc_loss doesn't support fp16
log_probs = nn.functional.log_softmax(logits, dim=-1, dtype=torch.float32).transpose(0, 1)
with torch.backends.cudnn.flags(enabled=False):
loss = nn.functional.ctc_loss(
log_probs,
flattened_targets,
input_lengths,
target_lengths,
blank=self.config.pad_token_id,
reduction=self.config.ctc_loss_reduction,
zero_infinity=self.config.ctc_zero_infinity,
)
if not return_dict:
output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
return ((loss,) + output) if loss is not None else output
return CausalLMOutput(
loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions
)
@auto_docstring(
custom_intro="""
SEWD Model with a sequence classification head on top (a linear layer over the pooled output) for tasks like SUPERB
Keyword Spotting.
"""
)
# Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForSequenceClassification with Wav2Vec2->SEWD, wav2vec2->sew_d, WAV2VEC2->SEWD
| SEWDForCTC |
python | tensorflow__tensorflow | tensorflow/python/training/basic_session_run_hooks_test.py | {
"start": 53425,
"end": 55602
} | class ____(test.TestCase):
def test_final_ops_is_scalar_tensor(self):
with ops.Graph().as_default():
expected_value = 4
final_ops = constant_op.constant(expected_value)
hook = basic_session_run_hooks.FinalOpsHook(final_ops)
hook.begin()
with session_lib.Session() as session:
hook.end(session)
self.assertEqual(expected_value,
hook.final_ops_values)
def test_final_ops_is_tensor(self):
with ops.Graph().as_default():
expected_values = [1, 6, 3, 5, 2, 4]
final_ops = constant_op.constant(expected_values)
hook = basic_session_run_hooks.FinalOpsHook(final_ops)
hook.begin()
with session_lib.Session() as session:
hook.end(session)
self.assertListEqual(expected_values,
hook.final_ops_values.tolist())
def test_final_ops_triggers_out_of_range_error(self):
with ops.Graph().as_default():
dataset = dataset_ops.Dataset.range(1)
iterator = dataset_ops.make_one_shot_iterator(dataset)
read_ops = iterator.get_next()
final_ops = read_ops
hook = basic_session_run_hooks.FinalOpsHook(final_ops)
hook.begin()
with session_lib.Session() as session:
session.run(read_ops)
with test.mock.patch.object(tf_logging, 'warning') as mock_log:
with self.assertRaisesRegex(errors.OutOfRangeError,
'End of sequence'):
hook.end(session)
self.assertRegex(
str(mock_log.call_args), 'dependency back to some input source')
def test_final_ops_with_dictionary(self):
with ops.Graph().as_default():
expected_values = [4, -3]
final_ops = array_ops.placeholder(dtype=dtypes.float32)
final_ops_feed_dict = {final_ops: expected_values}
hook = basic_session_run_hooks.FinalOpsHook(
final_ops, final_ops_feed_dict)
hook.begin()
with session_lib.Session() as session:
hook.end(session)
self.assertListEqual(expected_values,
hook.final_ops_values.tolist())
@test_util.run_deprecated_v1
| FinalOpsHookTest |
python | wandb__wandb | wandb/sdk/artifacts/_generated/input_types.py | {
"start": 2139,
"end": 2288
} | class ____(GQLInput):
name: str = Field(max_length=128, pattern="^[-\\w]+([ ]*[-.\\w]+)*$")
description: Optional[str] = None
| ArtifactTypeInput |
python | mlflow__mlflow | mlflow/entities/run_tag.py | {
"start": 119,
"end": 890
} | class ____(_MlflowObject):
"""Tag object associated with a run."""
def __init__(self, key, value):
self._key = key
self._value = value
def __eq__(self, other):
if type(other) is type(self):
# TODO deep equality here?
return self.__dict__ == other.__dict__
return False
@property
def key(self):
"""String name of the tag."""
return self._key
@property
def value(self):
"""String value of the tag."""
return self._value
def to_proto(self):
param = ProtoRunTag()
param.key = self.key
param.value = self.value
return param
@classmethod
def from_proto(cls, proto):
return cls(proto.key, proto.value)
| RunTag |
python | Textualize__textual | src/textual/demo/game.py | {
"start": 17904,
"end": 19438
} | class ____(PageScreen):
"""The screen containing the game."""
DEFAULT_CSS = """
GameScreen{
#container {
align: center middle;
layers: instructions game;
}
}
"""
BINDINGS = [("n", "new_game", "New Game")]
def compose(self) -> ComposeResult:
with containers.Vertical(id="container"):
yield GameInstructions()
yield Game("\n" * 100, "", dimensions=(4, 4), tile_size=(16, 8))
yield Footer()
def action_shuffle(self) -> None:
self.query_one(Game).shuffle()
def action_new_game(self) -> None:
self.app.push_screen(GameDialogScreen(), callback=self.new_game)
async def new_game(self, new_game: NewGame | None) -> None:
if new_game is None:
return
self.query_one(GameInstructions).display = False
game = self.query_one(Game)
game.state = "waiting"
game.code = new_game.code
game.language = new_game.language
game.dimensions = Size(*new_game.size)
await game.recompose()
game.focus()
def check_action(self, action: str, parameters: tuple[object, ...]) -> bool | None:
if action == "shuffle" and self.query_one(Game).state == "waiting":
return None
return True
if __name__ == "__main__":
from textual.app import App
class GameApp(App):
def get_default_screen(self) -> Screen:
return GameScreen()
app = GameApp()
app.run()
| GameScreen |
python | optuna__optuna | optuna/storages/_rdb/alembic/versions/v2.4.0.a.py | {
"start": 1672,
"end": 2070
} | class ____(BaseModel):
__tablename__ = "trial_values"
__table_args__: Any = (UniqueConstraint("trial_id", "objective"),)
trial_value_id = Column(Integer, primary_key=True)
trial_id = Column(Integer, ForeignKey("trials.trial_id"), nullable=False)
objective = Column(Integer, nullable=False)
value = Column(Float, nullable=False)
step = sa.Column(sa.Integer)
| TrialValueModel |
python | allegroai__clearml | clearml/binding/click_bind.py | {
"start": 440,
"end": 6930
} | class ____:
_args = {}
_args_desc = {}
_args_type = {}
_num_commands = 0
_command_type = "click.Command"
_section_name = "Args"
_current_task = None
__remote_task_params = None
__remote_task_params_dict = {}
__patched = False
@classmethod
def patch(cls, task: Optional["Task"] = None) -> None:
if Command is None:
return
cls._current_task = task
if task:
PatchClick._update_task_args()
if not cls.__patched:
cls.__patched = True
Command.__init__ = _patched_call(Command.__init__, PatchClick._command_init)
Command.parse_args = _patched_call(Command.parse_args, PatchClick._parse_args)
Context.__init__ = _patched_call(Context.__init__, PatchClick._context_init)
@classmethod
def args(
cls,
) -> Tuple[Dict[str, Any], Dict[str, Any], Dict[str, Any]]:
# ignore None keys
cls._args = {k: v for k, v in cls._args.items() if k is not None}
# remove prefix and main command
if cls._num_commands == 1:
cmd = sorted(cls._args.keys())[0]
skip = len(cmd) + 1
else:
skip = 0
_args = {cls._section_name + "/" + k[skip:]: v for k, v in cls._args.items() if k[skip:]}
_args_type = {cls._section_name + "/" + k[skip:]: v for k, v in cls._args_type.items() if k[skip:]}
_args_desc = {cls._section_name + "/" + k[skip:]: v for k, v in cls._args_desc.items() if k[skip:]}
return _args, _args_type, _args_desc
@classmethod
def _update_task_args(cls) -> None:
if running_remotely() or not cls._current_task or not cls._args:
return
param_val, param_types, param_desc = cls.args()
# noinspection PyProtectedMember
cls._current_task._set_parameters(
param_val,
__update=True,
__parameters_descriptions=param_desc,
__parameters_types=param_types,
)
@staticmethod
def _command_init(original_fn: Callable, self: Any, *args: Any, **kwargs: Any) -> Any:
if isinstance(self, (Command, Group)) and "name" in kwargs:
if isinstance(self, Command):
PatchClick._num_commands += 1
if not running_remotely():
name = kwargs["name"]
if name:
PatchClick._args[name] = False
if isinstance(self, Command):
PatchClick._args_type[name] = PatchClick._command_type
# maybe we should take it post initialization
if kwargs.get("help"):
PatchClick._args_desc[name] = str(kwargs.get("help"))
for option in kwargs.get("params") or []:
if (
not option
or not isinstance(option, (Option, Argument))
or not getattr(option, "expose_value", True)
):
continue
# store default value
PatchClick._args[name + "/" + option.name] = str(option.default or "")
# store value type
if option.type is not None:
PatchClick._args_type[name + "/" + option.name] = str(option.type)
# store value help
if getattr(option, "help", None):
PatchClick._args_desc[name + "/" + option.name] = str(option.help)
return original_fn(self, *args, **kwargs)
@staticmethod
def _parse_args(original_fn: Callable, self: Any, *args: Any, **kwargs: Any) -> Any:
if running_remotely() and isinstance(self, Command) and isinstance(self, Group):
command = PatchClick._load_task_params()
if command:
init_args = kwargs["args"] if "args" in kwargs else args[1]
init_args = [command] + (init_args[1:] if init_args else [])
if "args" in kwargs:
kwargs["args"] = init_args
else:
args = (args[0], init_args) + args[2:]
ret = original_fn(self, *args, **kwargs)
if isinstance(self, Command):
ctx = kwargs.get("ctx") or args[0]
if running_remotely():
PatchClick._load_task_params()
for p in self.params:
name = "{}/{}".format(self.name, p.name) if PatchClick._num_commands > 1 else p.name
value = PatchClick.__remote_task_params_dict.get(name)
ctx.params[p.name] = p.process_value(
ctx,
cast_str_to_bool(value, strip=True) if isinstance(p.type, BoolParamType) else value,
)
else:
if not isinstance(self, Group):
PatchClick._args[self.name] = True
for k, v in ctx.params.items():
# store passed value
PatchClick._args[self.name + "/" + str(k)] = str(v or "")
PatchClick._update_task_args()
return ret
@staticmethod
def _context_init(original_fn: Callable, self: Any, *args: Any, **kwargs: Any) -> None:
if running_remotely():
kwargs["resilient_parsing"] = True
return original_fn(self, *args, **kwargs)
@staticmethod
def _load_task_params() -> Optional[str]:
if not PatchClick.__remote_task_params:
from clearml import Task
t = Task.get_task(task_id=get_remote_task_id())
# noinspection PyProtectedMember
PatchClick.__remote_task_params = t._get_task_property("hyperparams") or {}
params_dict = t.get_parameters(backwards_compatibility=False)
skip = len(PatchClick._section_name) + 1
PatchClick.__remote_task_params_dict = {
k[skip:]: v for k, v in params_dict.items() if k.startswith(PatchClick._section_name + "/")
}
params = PatchClick.__remote_task_params
if not params:
return None
command = [
p.name
for p in params["Args"].values()
if p.type == PatchClick._command_type and cast_str_to_bool(p.value, strip=True)
]
return command[0] if command else None
# patch click before anything
PatchClick.patch()
| PatchClick |
python | spyder-ide__spyder | spyder/plugins/ipythonconsole/widgets/status.py | {
"start": 850,
"end": 5959
} | class ____(ShellConnectStatusBarWidget):
"""Status bar widget for current Matplotlib backend."""
ID = "matplotlib_status"
CONF_SECTION = 'ipython_console'
INTERACT_ON_CLICK = True
def __init__(self, parent):
super().__init__(parent)
self._gui = None
self._interactive_gui = None
# Signals
self.sig_clicked.connect(self.toggle_matplotlib)
# ---- StatusBarWidget API
# -------------------------------------------------------------------------
def get_tooltip(self):
"""Return localized tooltip for widget."""
msg = _(
"Click to toggle between inline and interactive Matplotlib "
"plotting"
)
msg = '\n'.join(textwrap.wrap(msg, width=40))
return msg
def get_icon(self):
return self.create_icon('plot')
# ---- Public API
# -------------------------------------------------------------------------
def toggle_matplotlib(self):
"""Toggle matplotlib interactive backend."""
if self.current_shellwidget is None or self._gui is None:
return
if self._gui != "inline":
# Switch to inline for any backend that is not inline
backend = "inline"
self._interactive_gui = self._gui
else:
if self._interactive_gui is None:
# Use the auto backend in case the interactive backend hasn't
# been set yet
backend = "auto"
else:
# Always use the interactive backend otherwise
backend = self._interactive_gui
sw = self.current_shellwidget
sw.execute("%matplotlib " + backend)
is_spyder_kernel = sw.is_spyder_kernel
if not is_spyder_kernel:
self.update_matplotlib_gui(backend)
def update_matplotlib_gui(self, gui, shellwidget=None):
"""Update matplotlib interactive."""
if shellwidget is None:
shellwidget = self.current_shellwidget
if shellwidget is None:
return
if shellwidget in self.shellwidget_to_status:
self.shellwidget_to_status[shellwidget] = gui
if shellwidget == self.current_shellwidget:
self.update_status(gui)
# ---- ShellConnectStatusBarWidget API
# -------------------------------------------------------------------------
def update_status(self, gui):
"""Update interactive state."""
logger.debug(f"Setting Matplotlib backend to {gui}")
if self._interactive_gui is None and gui != "inline":
self._interactive_gui = gui
self._gui = gui
if gui == "inline":
text = _("Inline")
elif gui == "auto":
text = _("Automatic")
elif gui == "macosx":
text = "macOS"
else:
text = gui.capitalize()
self.set_value(text)
def config_spyder_kernel(self, shellwidget):
shellwidget.register_kernel_call_handler(
"update_matplotlib_gui",
functools.partial(
self.update_matplotlib_gui, shellwidget=shellwidget
)
)
shellwidget.set_kernel_configuration("update_gui", True)
def on_kernel_start(self, shellwidget):
"""Actions to take when the kernel starts."""
# Reset value of interactive backend
self._interactive_gui = None
# Avoid errors when running our test suite on Mac and Windows.
# On Windows the following error appears:
# `spyder_kernels.comms.commbase.CommError: The comm is not connected.`
if running_in_ci() and not sys.platform.startswith("linux"):
mpl_backend = "inline"
else:
# CommError: Needed when the comm is not connected.
# Fixes spyder-ide/spyder#22194
# TimeoutError: Prevent error that seems to happen sporadically.
# Fixes spyder-ide/spyder#24865
# RuntimeError: A remote console can be closed too quickly, which
# raises a "Kernel is dead" error from comms.
try:
mpl_backend = shellwidget.get_matplotlib_backend()
except (CommError, TimeoutError, RuntimeError):
mpl_backend = None
# Associate detected backend to shellwidget
self.shellwidget_to_status[shellwidget] = mpl_backend
# Hide widget if Matplotlib is not available or failed to import in the
# kernel
if mpl_backend is None:
self.hide()
else:
self.set_shellwidget(shellwidget)
self.show()
# Ask the kernel to update the current backend, in case it has changed
shellwidget.set_kernel_configuration("update_gui", True)
def remove_shellwidget(self, shellwidget):
"""
Overridden method to remove the call handler registered by this widget.
"""
shellwidget.unregister_kernel_call_handler("update_matplotlib_gui")
super().remove_shellwidget(shellwidget)
| MatplotlibStatus |
python | python-attrs__attrs | tests/test_validators.py | {
"start": 6255,
"end": 7386
} | class ____:
def test_in_all(self):
"""
Verify that this validator is in ``__all__``.
"""
assert and_.__name__ in validator_module.__all__
def test_success(self):
"""
Succeeds if all wrapped validators succeed.
"""
v = and_(instance_of(int), always_pass)
v(None, simple_attr("test"), 42)
def test_fail(self):
"""
Fails if any wrapped validator fails.
"""
v = and_(instance_of(int), always_fail)
with pytest.raises(ZeroDivisionError):
v(None, simple_attr("test"), 42)
def test_sugar(self):
"""
`and_(v1, v2, v3)` and `[v1, v2, v3]` are equivalent.
"""
@attr.s
class C:
a1 = attr.ib("a1", validator=and_(instance_of(int)))
a2 = attr.ib("a2", validator=[instance_of(int)])
assert C.__attrs_attrs__[0].validator == C.__attrs_attrs__[1].validator
@pytest.mark.parametrize(
"validator",
[
instance_of(int),
[always_pass, instance_of(int)],
(always_pass, instance_of(int)),
],
)
| TestAnd |
python | RaRe-Technologies__gensim | gensim/test/test_word2vec.py | {
"start": 53068,
"end": 54564
} | class ____(unittest.TestCase):
@unittest.skipIf(POT_EXT is False, "POT not installed")
def test_nonzero(self):
'''Test basic functionality with a test sentence.'''
model = word2vec.Word2Vec(sentences, min_count=2, seed=42, workers=1)
sentence1 = ['human', 'interface', 'computer']
sentence2 = ['survey', 'user', 'computer', 'system', 'response', 'time']
distance = model.wv.wmdistance(sentence1, sentence2)
# Check that distance is non-zero.
self.assertFalse(distance == 0.0)
@unittest.skipIf(POT_EXT is False, "POT not installed")
def test_symmetry(self):
'''Check that distance is symmetric.'''
model = word2vec.Word2Vec(sentences, min_count=2, seed=42, workers=1)
sentence1 = ['human', 'interface', 'computer']
sentence2 = ['survey', 'user', 'computer', 'system', 'response', 'time']
distance1 = model.wv.wmdistance(sentence1, sentence2)
distance2 = model.wv.wmdistance(sentence2, sentence1)
self.assertTrue(np.allclose(distance1, distance2))
@unittest.skipIf(POT_EXT is False, "POT not installed")
def test_identical_sentences(self):
'''Check that the distance from a sentence to itself is zero.'''
model = word2vec.Word2Vec(sentences, min_count=1)
sentence = ['survey', 'user', 'computer', 'system', 'response', 'time']
distance = model.wv.wmdistance(sentence, sentence)
self.assertEqual(0.0, distance)
| TestWMD |
python | dask__distributed | distributed/shuffle/_rechunk.py | {
"start": 31451,
"end": 37675
} | class ____(ShuffleRun[NDIndex, "np.ndarray"]):
"""State for a single active rechunk execution
This object is responsible for splitting, sending, receiving and combining
data shards.
It is entirely agnostic to the distributed system and can perform a rechunk
with other run instances using `rpc``.
The user of this needs to guarantee that only `ArrayRechunkRun`s of the same unique
`ShuffleID` and `run_id` interact.
Parameters
----------
worker_for:
A mapping partition_id -> worker_address.
old:
Existing chunking of the array per dimension.
new:
Desired chunking of the array per dimension.
id:
A unique `ShuffleID` this belongs to.
run_id:
A unique identifier of the specific execution of the shuffle this belongs to.
span_id:
Span identifier; see :doc:`spans`
local_address:
The local address this Shuffle can be contacted by using `rpc`.
directory:
The scratch directory to buffer data in.
executor:
Thread pool to use for offloading compute.
rpc:
A callable returning a PooledRPCCall to contact other Shuffle instances.
Typically a ConnectionPool.
digest_metric:
A callable to ingest a performance metric.
Typically Server.digest_metric.
scheduler:
A PooledRPCCall to contact the scheduler.
memory_limiter_disk:
memory_limiter_comm:
A ``ResourceLimiter`` limiting the total amount of memory used in either
buffer.
"""
def __init__(
self,
worker_for: dict[NDIndex, str],
old: ChunkedAxes,
new: ChunkedAxes,
id: ShuffleId,
run_id: int,
span_id: str | None,
local_address: str,
directory: str,
executor: ThreadPoolExecutor,
rpc: Callable[[str], PooledRPCCall],
digest_metric: Callable[[Hashable, float], None],
scheduler: PooledRPCCall,
memory_limiter_disk: ResourceLimiter,
memory_limiter_comms: ResourceLimiter,
disk: bool,
loop: IOLoop,
):
super().__init__(
id=id,
run_id=run_id,
span_id=span_id,
local_address=local_address,
directory=directory,
executor=executor,
rpc=rpc,
digest_metric=digest_metric,
scheduler=scheduler,
memory_limiter_comms=memory_limiter_comms,
memory_limiter_disk=memory_limiter_disk,
disk=disk,
loop=loop,
)
self.old = old
self.new = new
partitions_of = defaultdict(list)
for part, addr in worker_for.items():
partitions_of[addr].append(part)
self.partitions_of = dict(partitions_of)
self.worker_for = worker_for
self.split_axes = split_axes(old, new)
async def _receive(
self,
data: list[tuple[NDIndex, list[tuple[NDIndex, tuple[NDIndex, np.ndarray]]]]],
) -> None:
self.raise_if_closed()
# Repartition shards and filter out already received ones
shards = defaultdict(list)
for d in data:
id1, payload = d
if id1 in self.received:
continue
self.received.add(id1)
for id2, shard in payload:
shards[id2].append(shard)
self.total_recvd += sizeof(d)
del data
if not shards:
return
try:
await self._write_to_disk(shards)
except Exception as e:
self._exception = e
raise
def _shard_partition(
self, data: np.ndarray, partition_id: NDIndex
) -> dict[str, tuple[NDIndex, list[tuple[NDIndex, tuple[NDIndex, np.ndarray]]]]]:
out: dict[str, list[tuple[NDIndex, tuple[NDIndex, np.ndarray]]]] = defaultdict(
list
)
shards_size = 0
shards_count = 0
ndsplits = product(*(axis[i] for axis, i in zip(self.split_axes, partition_id)))
for ndsplit in ndsplits:
chunk_index, shard_index, ndslice = zip(*ndsplit)
shard = data[ndslice]
# Don't wait until all shards have been transferred over the network
# before data can be released
if shard.base is not None:
shard = shard.copy()
shards_size += shard.nbytes
shards_count += 1
out[self.worker_for[chunk_index]].append(
(chunk_index, (shard_index, shard))
)
context_meter.digest_metric("p2p-shards", shards_size, "bytes")
context_meter.digest_metric("p2p-shards", shards_count, "count")
return {k: (partition_id, v) for k, v in out.items()}
def _get_output_partition(
self, partition_id: NDIndex, key: Key, **kwargs: Any
) -> np.ndarray:
# Quickly read metadata from disk.
# This is a bunch of seek()'s interleaved with short reads.
data = self._read_from_disk(partition_id)
# Copy the memory-mapped buffers from disk into memory.
# This is where we'll spend most time.
return convert_chunk(data)
def deserialize(self, buffer: Any) -> Any:
return buffer
def read(self, path: Path) -> tuple[list[list[tuple[NDIndex, np.ndarray]]], int]:
"""Open a memory-mapped file descriptor to disk, read all metadata, and unpickle
all arrays. This is a fast sequence of short reads interleaved with seeks.
Do not read in memory the actual data; the arrays' buffers will point to the
memory-mapped area.
The file descriptor will be automatically closed by the kernel when all the
returned arrays are dereferenced, which will happen after the call to
concatenate3.
"""
with path.open(mode="r+b") as fh:
buffer = memoryview(mmap.mmap(fh.fileno(), 0))
# The file descriptor has *not* been closed!
shards = list(unpickle_bytestream(buffer))
return shards, buffer.nbytes
def _get_assigned_worker(self, id: NDIndex) -> str:
return self.worker_for[id]
@dataclass(frozen=True)
| ArrayRechunkRun |
python | weaviate__weaviate-python-client | weaviate/connect/event_loop.py | {
"start": 315,
"end": 460
} | class ____(Future, Generic[T]):
def result(self, timeout: Optional[float] = None) -> T:
return cast(T, super().result(timeout))
| _Future |
python | pallets__click | src/click/types.py | {
"start": 5750,
"end": 6436
} | class ____(ParamType):
def __init__(self, func: t.Callable[[t.Any], t.Any]) -> None:
self.name: str = func.__name__
self.func = func
def to_info_dict(self) -> dict[str, t.Any]:
info_dict = super().to_info_dict()
info_dict["func"] = self.func
return info_dict
def convert(
self, value: t.Any, param: Parameter | None, ctx: Context | None
) -> t.Any:
try:
return self.func(value)
except ValueError:
try:
value = str(value)
except UnicodeError:
value = value.decode("utf-8", "replace")
self.fail(value, param, ctx)
| FuncParamType |
python | wireservice__csvkit | csvkit/utilities/csvstack.py | {
"start": 418,
"end": 5598
} | class ____(CSVKitUtility):
description = 'Stack up the rows from multiple CSV files, optionally adding a grouping value.'
# Override 'f' because the utility accepts multiple files.
override_flags = ['f', 'L', 'I']
def add_arguments(self):
self.argparser.add_argument(
metavar='FILE', nargs='*', dest='input_paths', default=['-'],
help='The CSV file(s) to operate on. If omitted, will accept input as piped data via STDIN.')
self.argparser.add_argument(
'-g', '--groups', dest='groups',
help='A comma-separated list of values to add as "grouping factors", one per CSV being stacked. These are '
'added to the output as a new column. You may specify a name for the new column using the -n flag.')
self.argparser.add_argument(
'-n', '--group-name', dest='group_name',
help='A name for the grouping column, e.g. "year". Only used when also specifying -g.')
self.argparser.add_argument(
'--filenames', dest='group_by_filenames', action='store_true',
help='Use the filename of each input file as its grouping value. When specified, -g will be ignored.')
def main(self):
if isatty(sys.stdin) and self.args.input_paths == ['-']:
sys.stderr.write('No input file or piped data provided. Waiting for standard input:\n')
has_groups = self.args.groups is not None or self.args.group_by_filenames
if self.args.groups is not None and not self.args.group_by_filenames:
groups = self.args.groups.split(',')
if len(groups) != len(self.args.input_paths):
self.argparser.error(
'The number of grouping values must be equal to the number of CSV files being stacked.')
else:
groups = None
group_name = self.args.group_name if self.args.group_name else 'group'
use_fieldnames = not self.args.no_header_row
if use_fieldnames:
Reader = agate.csv.DictReader
else:
Reader = agate.csv.reader
headers = []
stdin_fieldnames = []
stdin_first_row = []
for path in self.args.input_paths:
f = self._open_input_file(path)
file_is_stdin = path == '-'
_skip_lines(f, self.args)
rows = Reader(f, **self.reader_kwargs)
if use_fieldnames:
if rows.fieldnames:
for field in rows.fieldnames:
if field not in headers:
headers.append(field)
# If the file is standard input, store the fieldnames so that the rows can be read correctly later.
if file_is_stdin:
stdin_fieldnames = rows.fieldnames
else:
f.close()
else:
row = next(rows, [])
headers = list(make_default_headers(len(row)))
# If the file is standard input, store the row that was used to calculate the number of columns.
if file_is_stdin:
stdin_first_row = row
else:
f.close()
# If we aren't using header rows, we only look at the first file and stack columns in the same order.
break
if has_groups:
headers.insert(0, group_name)
if use_fieldnames:
output = agate.csv.DictWriter(self.output_file, fieldnames=headers, **self.writer_kwargs)
output.writeheader()
else:
output = agate.csv.writer(self.output_file, **self.writer_kwargs)
output.writerow(headers)
for i, path in enumerate(self.args.input_paths):
f = self._open_input_file(path, opened=True)
file_is_stdin = path == '-'
if has_groups:
if groups:
group = groups[i]
else:
group = os.path.basename(f.name)
# If the file is standard input, we've already skipped any lines above, to find its header row.
if not file_is_stdin:
_skip_lines(f, self.args)
# If the file is standard input, we've already read the header row, so we need to provide it here.
kwargs = {}
if file_is_stdin and use_fieldnames:
kwargs['fieldnames'] = stdin_fieldnames
rows = Reader(f, **self.reader_kwargs, **kwargs)
# If the file is standard input, we need to add back the row we used to calculate the number of columns.
if file_is_stdin and stdin_first_row:
output.writerow(stdin_first_row)
for row in rows:
if has_groups:
if use_fieldnames:
row[group_name] = group
else:
row.insert(0, group)
output.writerow(row)
f.close()
def launch_new_instance():
utility = CSVStack()
utility.run()
if __name__ == '__main__':
launch_new_instance()
| CSVStack |
python | django__django | django/contrib/gis/db/backends/utils.py | {
"start": 85,
"end": 789
} | class ____:
"""
Class encapsulating the behavior specific to a GIS operation (used by
lookups).
"""
sql_template = None
def __init__(self, op=None, func=None):
self.op = op
self.func = func
@property
def default_template(self):
if self.func:
return "%(func)s(%(lhs)s, %(rhs)s)"
else:
return "%(lhs)s %(op)s %(rhs)s"
def as_sql(self, connection, lookup, template_params, sql_params):
sql_template = self.sql_template or lookup.sql_template or self.default_template
template_params.update({"op": self.op, "func": self.func})
return sql_template % template_params, sql_params
| SpatialOperator |
python | doocs__leetcode | lcof2/剑指 Offer II 091. 粉刷房子/Solution.py | {
"start": 0,
"end": 298
} | class ____:
def minCost(self, costs: List[List[int]]) -> int:
r, g, b = 0, 0, 0
for cost in costs:
_r, _g, _b = r, g, b
r = min(_g, _b) + cost[0]
g = min(_r, _b) + cost[1]
b = min(_r, _g) + cost[2]
return min(r, g, b)
| Solution |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-paieas/llama_index/llms/paieas/base.py | {
"start": 163,
"end": 1047
} | class ____(OpenAILike):
"""
PaiEas is a thin wrapper around the OpenAILike model that makes it compatible with
Aliyun PAI-EAS(Elastic Algorithm Service) that provide effective llm services.
"""
def __init__(
self,
model: str = DEFAULT_MODEL_NAME,
api_key: Optional[str] = None,
api_base: Optional[str] = None,
is_chat_model: bool = True,
**kwargs: Any,
) -> None:
api_key = api_key or os.environ.get("PAIEAS_API_KEY", None)
api_base = api_base or os.environ.get("PAIEAS_API_BASE", None)
super().__init__(
model=model,
api_key=api_key,
api_base=urljoin(api_base, "v1"),
is_chat_model=is_chat_model,
**kwargs,
)
@classmethod
def class_name(cls) -> str:
"""Get class name."""
return "PaiEasLLM"
| PaiEas |
python | ray-project__ray | rllib/connectors/learner/add_infos_from_episodes_to_train_batch.py | {
"start": 374,
"end": 1850
} | class ____(ConnectorV2):
"""Adds the infos column to th train batch.
If provided with `episodes` data, this connector piece makes sure that the final
train batch going into the RLModule for updating (`forward_train()` call) contains
an `infos` column.
If the user wants to customize their own data under the given keys (e.g. obs,
actions, ...), they can extract from the episodes or recompute from `data`
their own data and store it in `data` under those keys. In this case, the default
connector will not change the data under these keys and simply act as a
pass-through.
"""
@override(ConnectorV2)
def __call__(
self,
*,
rl_module: RLModule,
batch: Optional[Dict[str, Any]],
episodes: List[EpisodeType],
explore: Optional[bool] = None,
shared_data: Optional[dict] = None,
**kwargs,
) -> Any:
# Infos.
if Columns.INFOS not in batch:
for sa_episode in self.single_agent_episode_iterator(
episodes,
agents_that_stepped_only=False,
):
self.add_n_batch_items(
batch,
Columns.INFOS,
items_to_add=sa_episode.get_infos(slice(0, len(sa_episode))),
num_items=len(sa_episode),
single_agent_episode=sa_episode,
)
return batch
| AddInfosFromEpisodesToTrainBatch |
python | walkccc__LeetCode | solutions/643. Maximum Average Subarray I/643.py | {
"start": 0,
"end": 236
} | class ____:
def findMaxAverage(self, nums: list[int], k: int) -> float:
summ = sum(nums[:k])
ans = summ
for i in range(k, len(nums)):
summ += nums[i] - nums[i - k]
ans = max(ans, summ)
return ans / k
| Solution |
python | spyder-ide__spyder | spyder/widgets/reporterror.py | {
"start": 1770,
"end": 4062
} | class ____(SimpleCodeEditor, SpyderFontsMixin):
"""Widget to enter error description."""
def __init__(self, parent=None):
super().__init__(parent)
# Editor options
self.setup_editor(
language='md',
font=self.get_font(
SpyderFontType.MonospaceInterface, font_size_delta=1
),
wrap=True,
linenumbers=False,
highlight_current_line=False,
)
# Header
self.header = (
"### What steps will reproduce the problem?\n\n"
"<!--- You can use Markdown here --->\n\n"
)
self.set_text(self.header)
self.move_cursor(len(self.header))
self.header_end_pos = self.get_position('eof')
def remove_text(self):
"""Remove text."""
self.truncate_selection(self.header_end_pos)
self.remove_selected_text()
def cut(self):
"""Cut text"""
self.truncate_selection(self.header_end_pos)
if self.has_selected_text():
super().cut()
def keyPressEvent(self, event):
"""Reimplemented Qt Method to avoid removing the header."""
event, text, key, ctrl, shift = restore_keyevent(event)
cursor_position = self.get_position('cursor')
if cursor_position < self.header_end_pos:
self.restrict_cursor_position(self.header_end_pos, 'eof')
elif key == Qt.Key_Backspace:
if self.has_selected_text():
self.remove_text()
elif self.header_end_pos == cursor_position:
return
else:
self.stdkey_backspace()
elif key == Qt.Key_X and ctrl:
self.cut()
else:
super().keyPressEvent(event)
def delete(self):
"""Reimplemented to avoid removing the header."""
cursor_position = self.get_position('cursor')
if cursor_position < self.header_end_pos:
self.restrict_cursor_position(self.header_end_pos, 'eof')
elif self.has_selected_text():
self.remove_text()
else:
self.stdkey_clear()
def contextMenuEvent(self, event):
"""Reimplemented Qt Method to not show the context menu."""
pass
| DescriptionWidget |
python | pallets__jinja | src/jinja2/bccache.py | {
"start": 3128,
"end": 6065
} | class ____:
"""To implement your own bytecode cache you have to subclass this class
and override :meth:`load_bytecode` and :meth:`dump_bytecode`. Both of
these methods are passed a :class:`~jinja2.bccache.Bucket`.
A very basic bytecode cache that saves the bytecode on the file system::
from os import path
class MyCache(BytecodeCache):
def __init__(self, directory):
self.directory = directory
def load_bytecode(self, bucket):
filename = path.join(self.directory, bucket.key)
if path.exists(filename):
with open(filename, 'rb') as f:
bucket.load_bytecode(f)
def dump_bytecode(self, bucket):
filename = path.join(self.directory, bucket.key)
with open(filename, 'wb') as f:
bucket.write_bytecode(f)
A more advanced version of a filesystem based bytecode cache is part of
Jinja.
"""
def load_bytecode(self, bucket: Bucket) -> None:
"""Subclasses have to override this method to load bytecode into a
bucket. If they are not able to find code in the cache for the
bucket, it must not do anything.
"""
raise NotImplementedError()
def dump_bytecode(self, bucket: Bucket) -> None:
"""Subclasses have to override this method to write the bytecode
from a bucket back to the cache. If it unable to do so it must not
fail silently but raise an exception.
"""
raise NotImplementedError()
def clear(self) -> None:
"""Clears the cache. This method is not used by Jinja but should be
implemented to allow applications to clear the bytecode cache used
by a particular environment.
"""
def get_cache_key(self, name: str, filename: str | None = None) -> str:
"""Returns the unique hash key for this template name."""
hash = sha1(name.encode("utf-8"))
if filename is not None:
hash.update(f"|{filename}".encode())
return hash.hexdigest()
def get_source_checksum(self, source: str) -> str:
"""Returns a checksum for the source."""
return sha1(source.encode("utf-8")).hexdigest()
def get_bucket(
self,
environment: "Environment",
name: str,
filename: str | None,
source: str,
) -> Bucket:
"""Return a cache bucket for the given template. All arguments are
mandatory but filename may be `None`.
"""
key = self.get_cache_key(name, filename)
checksum = self.get_source_checksum(source)
bucket = Bucket(environment, key, checksum)
self.load_bytecode(bucket)
return bucket
def set_bucket(self, bucket: Bucket) -> None:
"""Put the bucket into the cache."""
self.dump_bytecode(bucket)
| BytecodeCache |
python | mlflow__mlflow | mlflow/telemetry/events.py | {
"start": 8463,
"end": 8936
} | class ____(Event):
name: str = "invoke_custom_judge_model"
@classmethod
def parse(cls, arguments: dict[str, Any]) -> dict[str, Any] | None:
from mlflow.metrics.genai.model_utils import _parse_model_uri
model_uri = arguments.get("model_uri")
if not model_uri:
return {"model_provider": None}
model_provider, _ = _parse_model_uri(model_uri)
return {"model_provider": model_provider}
| InvokeCustomJudgeModelEvent |
python | apache__airflow | airflow-core/src/airflow/dag_processing/processor.py | {
"start": 16117,
"end": 23151
} | class ____(WatchedSubprocess):
"""
Parses dags with Task SDK API.
This class provides a wrapper and management around a subprocess to parse a specific DAG file.
Since DAGs are written with the Task SDK, we need to parse them in a task SDK process such that
we can use the Task SDK definitions when serializing. This prevents potential conflicts with classes
in core Airflow.
"""
logger_filehandle: BinaryIO
parsing_result: DagFileParsingResult | None = None
decoder: ClassVar[TypeAdapter[ToManager]] = TypeAdapter[ToManager](ToManager)
had_callbacks: bool = False # Track if this process was started with callbacks to prevent stale DAG detection false positives
client: Client
"""The HTTP client to use for communication with the API server."""
@classmethod
def start( # type: ignore[override]
cls,
*,
path: str | os.PathLike[str],
bundle_path: Path,
bundle_name: str,
callbacks: list[CallbackRequest],
target: Callable[[], None] = _parse_file_entrypoint,
client: Client,
**kwargs,
) -> Self:
logger = kwargs["logger"]
_pre_import_airflow_modules(os.fspath(path), logger)
proc: Self = super().start(target=target, client=client, **kwargs)
proc.had_callbacks = bool(callbacks) # Track if this process had callbacks
proc._on_child_started(callbacks, path, bundle_path, bundle_name)
return proc
def _on_child_started(
self,
callbacks: list[CallbackRequest],
path: str | os.PathLike[str],
bundle_path: Path,
bundle_name: str,
) -> None:
msg = DagFileParseRequest(
file=os.fspath(path),
bundle_path=bundle_path,
bundle_name=bundle_name,
callback_requests=callbacks,
)
self.send_msg(msg, request_id=0)
def _handle_request(self, msg: ToManager, log: FilteringBoundLogger, req_id: int) -> None:
from airflow.sdk.api.datamodels._generated import (
ConnectionResponse,
TaskStatesResponse,
VariableResponse,
XComSequenceIndexResponse,
)
resp: BaseModel | None = None
dump_opts = {}
if isinstance(msg, DagFileParsingResult):
self.parsing_result = msg
elif isinstance(msg, GetConnection):
conn = self.client.connections.get(msg.conn_id)
if isinstance(conn, ConnectionResponse):
conn_result = ConnectionResult.from_conn_response(conn)
resp = conn_result
dump_opts = {"exclude_unset": True, "by_alias": True}
else:
resp = conn
elif isinstance(msg, GetVariable):
var = self.client.variables.get(msg.key)
if isinstance(var, VariableResponse):
var_result = VariableResult.from_variable_response(var)
resp = var_result
dump_opts = {"exclude_unset": True}
else:
resp = var
elif isinstance(msg, PutVariable):
self.client.variables.set(msg.key, msg.value, msg.description)
elif isinstance(msg, DeleteVariable):
resp = self.client.variables.delete(msg.key)
elif isinstance(msg, GetPreviousDagRun):
resp = self.client.dag_runs.get_previous(
dag_id=msg.dag_id,
logical_date=msg.logical_date,
state=msg.state,
)
elif isinstance(msg, GetPrevSuccessfulDagRun):
dagrun_resp = self.client.task_instances.get_previous_successful_dagrun(self.id)
dagrun_result = PrevSuccessfulDagRunResult.from_dagrun_response(dagrun_resp)
resp = dagrun_result
dump_opts = {"exclude_unset": True}
elif isinstance(msg, GetXCom):
xcom = self.client.xcoms.get(
msg.dag_id, msg.run_id, msg.task_id, msg.key, msg.map_index, msg.include_prior_dates
)
xcom_result = XComResult.from_xcom_response(xcom)
resp = xcom_result
elif isinstance(msg, GetXComCount):
resp = self.client.xcoms.head(msg.dag_id, msg.run_id, msg.task_id, msg.key)
elif isinstance(msg, GetXComSequenceItem):
xcom = self.client.xcoms.get_sequence_item(
msg.dag_id, msg.run_id, msg.task_id, msg.key, msg.offset
)
if isinstance(xcom, XComSequenceIndexResponse):
resp = XComSequenceIndexResult.from_response(xcom)
else:
resp = xcom
elif isinstance(msg, GetXComSequenceSlice):
xcoms = self.client.xcoms.get_sequence_slice(
msg.dag_id,
msg.run_id,
msg.task_id,
msg.key,
msg.start,
msg.stop,
msg.step,
msg.include_prior_dates,
)
resp = XComSequenceSliceResult.from_response(xcoms)
elif isinstance(msg, MaskSecret):
# Use sdk masker in dag processor and triggerer because those use the task sdk machinery
from airflow.sdk.log import mask_secret
mask_secret(msg.value, msg.name)
elif isinstance(msg, GetTICount):
resp = self.client.task_instances.get_count(
dag_id=msg.dag_id,
map_index=msg.map_index,
task_ids=msg.task_ids,
task_group_id=msg.task_group_id,
logical_dates=msg.logical_dates,
run_ids=msg.run_ids,
states=msg.states,
)
elif isinstance(msg, GetTaskStates):
task_states_map = self.client.task_instances.get_task_states(
dag_id=msg.dag_id,
map_index=msg.map_index,
task_ids=msg.task_ids,
task_group_id=msg.task_group_id,
logical_dates=msg.logical_dates,
run_ids=msg.run_ids,
)
if isinstance(task_states_map, TaskStatesResponse):
resp = TaskStatesResult.from_api_response(task_states_map)
else:
resp = task_states_map
else:
log.error("Unhandled request", msg=msg)
self.send_msg(
None,
request_id=req_id,
error=ErrorResponse(
detail={"status_code": 400, "message": "Unhandled request"},
),
)
return
self.send_msg(resp, request_id=req_id, error=None, **dump_opts)
@property
def is_ready(self) -> bool:
if self._check_subprocess_exit() is None:
# Process still alive, def can't be finished yet
return False
return not self._open_sockets
def wait(self) -> int:
raise NotImplementedError(f"Don't call wait on {type(self).__name__} objects")
| DagFileProcessorProcess |
python | getsentry__sentry | tests/acceptance/test_organization_releases.py | {
"start": 243,
"end": 2998
} | class ____(AcceptanceTestCase):
release_date = datetime(2020, 5, 18, 15, 13, 58, 132928, tzinfo=UTC)
def setUp(self) -> None:
super().setUp()
self.user = self.create_user("foo@example.com")
self.org = self.create_organization(owner=self.user, name="Rowdy Tiger")
self.team = self.create_team(
organization=self.org, name="Mariachi Band", members=[self.user]
)
self.project = self.create_project(organization=self.org, teams=[self.team], name="Bengal")
self.project2 = self.create_project(
organization=self.org, teams=[self.team], name="Bengal 2"
)
self.create_project(organization=self.org, teams=[self.team], name="Bengal 3")
self.login_as(self.user)
self.path = f"/organizations/{self.org.slug}/releases/"
self.project.update(first_event=timezone.now())
def test_list(self) -> None:
self.create_release(project=self.project, version="1.0", date_added=self.release_date)
self.browser.get(self.path)
self.browser.wait_until_not(".loading")
# TODO(releases): add health data
def test_detail(self) -> None:
release = self.create_release(
project=self.project, version="1.0", date_added=self.release_date
)
self.browser.get(self.path + release.version)
self.browser.wait_until_not(".loading")
self.browser.wait_until_test_id("release-wrapper")
self.browser.wait_until_not('[data-test-id="loading-placeholder"]')
# TODO(releases): add health data
def test_detail_pick_project(self) -> None:
release = self.create_release(
project=self.project,
additional_projects=[self.project2],
version="1.0",
date_added=self.release_date,
)
self.browser.get(self.path + release.version)
self.browser.wait_until_not(".loading")
assert "Select a project to continue" in self.browser.element("[role='dialog'] header").text
# This is snapshotting features that are enable through the discover and performance features.
def test_detail_with_discover_and_performance(self) -> None:
with self.feature(["organizations:discover-basic", "organizations:performance-view"]):
release = self.create_release(
project=self.project, version="1.0", date_added=self.release_date
)
self.browser.get(self.path + release.version)
self.browser.wait_until_not(".loading")
self.browser.wait_until_test_id("release-wrapper")
self.browser.wait_until_not('[data-test-id="loading-placeholder"]')
# TODO(releases): add health data
| OrganizationReleasesTest |
python | django__django | django/contrib/postgres/constraints.py | {
"start": 664,
"end": 9453
} | class ____(CheckPostgresInstalledMixin, BaseConstraint):
template = (
"CONSTRAINT %(name)s EXCLUDE USING %(index_type)s "
"(%(expressions)s)%(include)s%(where)s%(deferrable)s"
)
def __init__(
self,
*,
name,
expressions,
index_type=None,
condition=None,
deferrable=None,
include=None,
violation_error_code=None,
violation_error_message=None,
):
if index_type and index_type.lower() not in {"gist", "spgist"}:
raise ValueError(
"Exclusion constraints only support GiST or SP-GiST indexes."
)
if not expressions:
raise ValueError(
"At least one expression is required to define an exclusion "
"constraint."
)
if not all(
isinstance(expr, (list, tuple)) and len(expr) == 2 for expr in expressions
):
raise ValueError("The expressions must be a list of 2-tuples.")
if not isinstance(condition, (NoneType, Q)):
raise ValueError("ExclusionConstraint.condition must be a Q instance.")
if not isinstance(deferrable, (NoneType, Deferrable)):
raise ValueError(
"ExclusionConstraint.deferrable must be a Deferrable instance."
)
if not isinstance(include, (NoneType, list, tuple)):
raise ValueError("ExclusionConstraint.include must be a list or tuple.")
self.expressions = expressions
self.index_type = index_type or "GIST"
self.condition = condition
self.deferrable = deferrable
self.include = tuple(include) if include else ()
super().__init__(
name=name,
violation_error_code=violation_error_code,
violation_error_message=violation_error_message,
)
def _get_expressions(self, schema_editor, query):
expressions = []
for idx, (expression, operator) in enumerate(self.expressions):
if isinstance(expression, str):
expression = F(expression)
expression = ExclusionConstraintExpression(expression, operator=operator)
expression.set_wrapper_classes(schema_editor.connection)
expressions.append(expression)
return ExpressionList(*expressions).resolve_expression(query)
def check(self, model, connection):
errors = super().check(model, connection)
references = set()
for expr, _ in self.expressions:
if isinstance(expr, str):
expr = F(expr)
references.update(model._get_expr_references(expr))
errors.extend(self._check_references(model, references))
return errors
def _get_condition_sql(self, compiler, schema_editor, query):
if self.condition is None:
return None
where = query.build_where(self.condition)
sql, params = where.as_sql(compiler, schema_editor.connection)
return sql % tuple(schema_editor.quote_value(p) for p in params)
def constraint_sql(self, model, schema_editor):
query = Query(model, alias_cols=False)
compiler = query.get_compiler(connection=schema_editor.connection)
expressions = self._get_expressions(schema_editor, query)
table = model._meta.db_table
condition = self._get_condition_sql(compiler, schema_editor, query)
include = [
model._meta.get_field(field_name).column for field_name in self.include
]
return Statement(
self.template,
table=Table(table, schema_editor.quote_name),
name=schema_editor.quote_name(self.name),
index_type=self.index_type,
expressions=Expressions(
table, expressions, compiler, schema_editor.quote_value
),
where=" WHERE (%s)" % condition if condition else "",
include=schema_editor._index_include_sql(model, include),
deferrable=schema_editor._deferrable_constraint_sql(self.deferrable),
)
def create_sql(self, model, schema_editor):
return Statement(
"ALTER TABLE %(table)s ADD %(constraint)s",
table=Table(model._meta.db_table, schema_editor.quote_name),
constraint=self.constraint_sql(model, schema_editor),
)
def remove_sql(self, model, schema_editor):
return schema_editor._delete_constraint_sql(
schema_editor.sql_delete_check,
model,
schema_editor.quote_name(self.name),
)
def deconstruct(self):
path, args, kwargs = super().deconstruct()
kwargs["expressions"] = self.expressions
if self.condition is not None:
kwargs["condition"] = self.condition
if self.index_type.lower() != "gist":
kwargs["index_type"] = self.index_type
if self.deferrable:
kwargs["deferrable"] = self.deferrable
if self.include:
kwargs["include"] = self.include
return path, args, kwargs
def __eq__(self, other):
if isinstance(other, self.__class__):
return (
self.name == other.name
and self.index_type == other.index_type
and self.expressions == other.expressions
and self.condition == other.condition
and self.deferrable == other.deferrable
and self.include == other.include
and self.violation_error_code == other.violation_error_code
and self.violation_error_message == other.violation_error_message
)
return super().__eq__(other)
def __repr__(self):
return "<%s: index_type=%s expressions=%s name=%s%s%s%s%s%s>" % (
self.__class__.__qualname__,
repr(self.index_type),
repr(self.expressions),
repr(self.name),
"" if self.condition is None else " condition=%s" % self.condition,
"" if self.deferrable is None else " deferrable=%r" % self.deferrable,
"" if not self.include else " include=%s" % repr(self.include),
(
""
if self.violation_error_code is None
else " violation_error_code=%r" % self.violation_error_code
),
(
""
if self.violation_error_message is None
or self.violation_error_message == self.default_violation_error_message
else " violation_error_message=%r" % self.violation_error_message
),
)
def validate(self, model, instance, exclude=None, using=DEFAULT_DB_ALIAS):
queryset = model._default_manager.using(using)
replacement_map = instance._get_field_expression_map(
meta=model._meta, exclude=exclude
)
replacements = {F(field): value for field, value in replacement_map.items()}
lookups = []
for expression, operator in self.expressions:
if isinstance(expression, str):
expression = F(expression)
if exclude and self._expression_refs_exclude(model, expression, exclude):
return
rhs_expression = expression.replace_expressions(replacements)
if hasattr(expression, "get_expression_for_validation"):
expression = expression.get_expression_for_validation()
if hasattr(rhs_expression, "get_expression_for_validation"):
rhs_expression = rhs_expression.get_expression_for_validation()
lookup = PostgresOperatorLookup(lhs=expression, rhs=rhs_expression)
lookup.postgres_operator = operator
lookups.append(lookup)
queryset = queryset.filter(*lookups)
model_class_pk = instance._get_pk_val(model._meta)
if not instance._state.adding and instance._is_pk_set(model._meta):
queryset = queryset.exclude(pk=model_class_pk)
if not self.condition:
if queryset.exists():
raise ValidationError(
self.get_violation_error_message(), code=self.violation_error_code
)
else:
# Ignore constraints with excluded fields in condition.
if exclude and self._expression_refs_exclude(
model, self.condition, exclude
):
return
if (self.condition & Exists(queryset.filter(self.condition))).check(
replacement_map, using=using
):
raise ValidationError(
self.get_violation_error_message(), code=self.violation_error_code
)
| ExclusionConstraint |
python | pytorch__pytorch | test/distributed/test_multi_threaded_pg.py | {
"start": 732,
"end": 4865
} | class ____(TestCase):
@spawn_threads_and_init_comms(world_size=4)
def test_broadcast_object_list(self):
val = 99 if dist.get_rank() == 0 else None
object_list = [val] * dist.get_world_size()
dist.broadcast_object_list(object_list=object_list)
self.assertEqual(99, object_list[0])
def test_collective_error_on_rank_zero(self):
@spawn_threads_and_init_comms(world_size=4)
def _test_method(self):
input_tensor = torch.ones(3, 3) * dist.get_rank() # perform 1st all gather
output_tensors = [
torch.empty_like(input_tensor) for _ in range(dist.get_world_size())
]
dist.all_gather(output_tensors, input_tensor)
if dist.get_rank() == 0:
raise AssertionError("Mimic real test failure.") # fail on rank 0
dist.all_gather(output_tensors, input_tensor) # perform 2nd all gather
with self.assertRaises(RuntimeError):
_test_method(self)
def test_collective_error_on_rank_non_zero(self):
@spawn_threads_and_init_comms(world_size=4)
def _test_method(self):
input_tensor = torch.ones(3, 3) * dist.get_rank() # perform 1st all gather
output_tensors = [
torch.empty_like(input_tensor) for _ in range(dist.get_world_size())
]
dist.all_gather(output_tensors, input_tensor)
if dist.get_rank() == 1:
raise AssertionError("Mimic real test failure.") # fail on rank 1
dist.all_gather(output_tensors, input_tensor) # perform 2nd all gather
with self.assertRaises(RuntimeError):
_test_method(self)
def test_collective_error_on_rank_non_zero_all(self):
@spawn_threads_and_init_comms(world_size=4)
def _test_method(self):
input_tensor = torch.ones(3, 3) * dist.get_rank() # perform 1st all gather
output_tensors = [
torch.empty_like(input_tensor) for _ in range(dist.get_world_size())
]
dist.all_gather(output_tensors, input_tensor)
if dist.get_rank() > 0:
raise AssertionError(
"Mimic real test failure."
) # fail on all non-zero rank
dist.all_gather(output_tensors, input_tensor) # perform 2nd all gather
with self.assertRaises(RuntimeError):
_test_method(self)
def test_skip(self):
@spawn_threads_and_init_comms(world_size=4)
@skip("check if skip exception can be captured correctly.")
def _test_method(self):
pass
if not IS_SANDCASTLE:
with self.assertRaises(SkipTest):
_test_method(self)
@spawn_threads_and_init_comms(world_size=4)
def test_all_to_all_single_tensor(self):
rank = dist.get_rank()
world_size = dist.get_world_size()
send = torch.full((world_size, 2), rank)
sizes = torch.ones(world_size, dtype=torch.int64)
out = torch.zeros(world_size, 2, dtype=send.dtype)
dist.all_to_all_single(out, send, sizes, sizes)
self.assertEqual(out.tolist(), list(zip(range(world_size), range(world_size))))
@spawn_threads_and_init_comms(world_size=4)
def test_all_to_all_single_list(self):
rank = dist.get_rank()
world_size = dist.get_world_size()
send = torch.full((world_size, 2), rank)
sizes = [1] * world_size
out = torch.zeros(world_size, 2, dtype=send.dtype)
dist.all_to_all_single(out, send, sizes, sizes)
self.assertEqual(out.tolist(), list(zip(range(world_size), range(world_size))))
@spawn_threads_and_init_comms(world_size=4)
def test_all_to_all_single_none(self):
rank = dist.get_rank()
world_size = dist.get_world_size()
send = torch.full((world_size, 2), rank)
out = torch.zeros(world_size, 2, dtype=send.dtype)
dist.all_to_all_single(out, send)
self.assertEqual(out.tolist(), list(zip(range(world_size), range(world_size))))
| TestCollectivesWithWrapper |
python | ray-project__ray | python/ray/experimental/shuffle.py | {
"start": 1426,
"end": 2278
} | class ____:
"""This class is used to stream shuffle map outputs to the object store.
It can be subclassed to optimize writing (e.g., batching together small
records into larger objects). This will be performance critical if your
input records are small (the example shuffle uses very large records, so
the naive strategy works well).
"""
def __init__(self):
self.results = []
def add(self, item: InType) -> None:
"""Queue a single item to be written to the object store.
This base implementation immediately writes each given item to the
object store as a standalone object.
"""
self.results.append(ray.put(item))
def finish(self) -> List[ObjectRef]:
"""Return list of object refs representing written items."""
return self.results
| ObjectStoreWriter |
python | tornadoweb__tornado | tornado/test/web_test.py | {
"start": 15457,
"end": 15791
} | class ____(RequestHandler):
def initialize(self, login_url):
self.login_url = login_url
def get_login_url(self):
return self.login_url
@authenticated
def get(self):
# we'll never actually get here because the test doesn't follow redirects
self.send_error(500)
| AuthRedirectRequestHandler |
python | getsentry__sentry | tests/sentry/integrations/jira_server/test_integration.py | {
"start": 51095,
"end": 56754
} | class ____(APITestCase):
@cached_property
def integration(self):
integration = self.create_integration(
organization=self.organization,
external_id="jira_server:1",
provider="jira_server",
name="Jira Server",
metadata={
"oauth_client_id": "oauth-client-id",
"shared_secret": "a-super-secret-key-from-atlassian",
"base_url": "https://example.atlassian.net",
"domain_name": "example.atlassian.net",
},
)
return integration
def setUp(self) -> None:
super().setUp()
self.plugin = JiraPlugin()
self.plugin.set_option("enabled", True, self.project)
self.plugin.set_option("default_project", "SEN", self.project)
self.plugin.set_option("instance_url", "https://example.atlassian.net", self.project)
self.plugin.set_option("ignored_fields", "hellboy, meow", self.project)
installation = self.integration.get_installation(self.organization.id)
assert isinstance(installation, JiraServerIntegration)
self.installation = installation
self.login_as(self.user)
def test_migrate_plugin(self) -> None:
"""Test that 2 projects with the Jira plugin enabled that each have an issue created
from the plugin are migrated along with the ignored fields
"""
project2 = self.create_project(
name="hellbar", organization=self.organization, teams=[self.team]
)
plugin2 = JiraPlugin()
plugin2.set_option("enabled", True, project2)
plugin2.set_option("default_project", "BAR", project2)
plugin2.set_option("instance_url", "https://example.atlassian.net", project2)
group = self.create_group(message="Hello world", culprit="foo.bar")
plugin_issue = GroupMeta.objects.create(
key=f"{self.plugin.slug}:tid", group_id=group.id, value="SEN-1"
)
group2 = self.create_group(message="Hello world", culprit="foo.bar")
plugin2_issue = GroupMeta.objects.create(
key=f"{self.plugin.slug}:tid", group_id=group2.id, value="BAR-1"
)
with assume_test_silo_mode(SiloMode.CONTROL):
org_integration = OrganizationIntegration.objects.get(
integration_id=self.integration.id
)
with unguarded_write(router.db_for_write(OrganizationIntegration)):
org_integration.config.update({"issues_ignored_fields": ["reporter", "test"]})
org_integration.save()
with self.tasks():
self.installation.migrate_issues()
assert ExternalIssue.objects.filter(
organization_id=self.organization.id,
integration_id=self.integration.id,
key=plugin_issue.value,
).exists()
assert ExternalIssue.objects.filter(
organization_id=self.organization.id,
integration_id=self.integration.id,
key=plugin2_issue.value,
).exists()
assert not GroupMeta.objects.filter(
key=f"{self.plugin.slug}:tid", group_id=group.id, value="SEN-1"
).exists()
assert not GroupMeta.objects.filter(
key=f"{self.plugin.slug}:tid", group_id=group.id, value="BAR-1"
).exists()
with assume_test_silo_mode(SiloMode.CONTROL):
oi = OrganizationIntegration.objects.get(integration_id=self.integration.id)
assert len(oi.config["issues_ignored_fields"]) == 4
assert self.plugin.get_option("enabled", self.project) is False
assert plugin2.get_option("enabled", project2) is False
def test_instance_url_mismatch(self) -> None:
"""Test that if the plugin's instance URL does not match the integration's base URL, we don't migrate the issues"""
self.plugin.set_option("instance_url", "https://hellboy.atlassian.net", self.project)
group = self.create_group(message="Hello world", culprit="foo.bar")
plugin_issue = GroupMeta.objects.create(
key=f"{self.plugin.slug}:tid", group_id=group.id, value="SEN-1"
)
with self.tasks():
self.installation.migrate_issues()
assert not ExternalIssue.objects.filter(
organization_id=self.organization.id,
integration_id=self.integration.id,
key=plugin_issue.value,
).exists()
assert GroupMeta.objects.filter(
key=f"{self.plugin.slug}:tid", group_id=group.id, value="SEN-1"
).exists()
def test_external_issue_already_exists(self) -> None:
"""Test that if an issue already exists during migration, we continue with no issue"""
group = self.create_group(message="Hello world", culprit="foo.bar")
GroupMeta.objects.create(key=f"{self.plugin.slug}:tid", group_id=group.id, value="SEN-1")
group2 = self.create_group(message="Hello world", culprit="foo.bar")
GroupMeta.objects.create(key=f"{self.plugin.slug}:tid", group_id=group2.id, value="BAR-1")
integration_issue = ExternalIssue.objects.create(
organization_id=self.organization.id,
integration_id=self.integration.id,
key="BAR-1",
)
GroupLink.objects.create(
group_id=group2.id,
project_id=self.project.id,
linked_type=GroupLink.LinkedType.issue,
linked_id=integration_issue.id,
relationship=GroupLink.Relationship.references,
)
with self.tasks():
self.installation.migrate_issues()
| JiraMigrationIntegrationTest |
python | getsentry__sentry | src/sentry/monitors/grouptype.py | {
"start": 420,
"end": 1002
} | class ____(GroupType):
type_id = 4001
slug = "monitor_check_in_failure"
description = "Crons Monitor Failed"
category = GroupCategory.CRON.value
category_v2 = GroupCategory.OUTAGE.value
released = True
creation_quota = Quota(3600, 60, 60_000) # 60,000 per hour, sliding window of 60 seconds
default_priority = PriorityLevel.HIGH
notification_config = NotificationConfig(context=[])
detector_settings = DetectorSettings(
handler=None,
validator=MonitorIncidentDetectorValidator,
config_schema={},
)
| MonitorIncidentType |
python | ansible__ansible | test/units/module_utils/facts/test_facts.py | {
"start": 3741,
"end": 3911
} | class ____(BaseTestFactsPlatform):
platform_id = 'AIX'
fact_class = hardware.aix.AIXHardware
collector_class = hardware.aix.AIXHardwareCollector
| TestAIXHardware |
python | pytorch__pytorch | test/fx/test_fx_traceback.py | {
"start": 345,
"end": 10625
} | class ____(TestCase):
def test_node_source(self):
node_source = NodeSource(
node=None, pass_name="test_pass", action=NodeSourceAction.CREATE
)
self.assertExpectedInline(
node_source.print_readable().strip(),
"""(name=, pass_name=test_pass, action=create, graph_id=-1)""",
)
dummy_source_dict = {
"name": "",
"target": "",
"pass_name": "test_pass",
"action": CREATE_STR,
"graph_id": -1,
"from_node": [],
}
self.assertEqual(
node_source.to_dict(),
dummy_source_dict,
)
self.assertEqual(node_source, NodeSource._from_dict(node_source.to_dict()))
# Dummy node
node = torch.fx.Node(
graph=torch.fx.Graph(),
name="add",
op="call_function",
target=torch.ops.aten.add.Tensor, # type: ignore[attr-defined]
args=(torch.tensor(3), torch.tensor(4)),
kwargs={},
)
node.meta["from_node"] = [node_source]
graph_id = id(node.graph)
node_source = NodeSource(
node=node, pass_name="test_pass", action=NodeSourceAction.CREATE
)
self.assertExpectedInline(
node_source.print_readable().strip(),
f"""\
(name=add, pass_name=test_pass, action=create, graph_id={graph_id})
(name=, pass_name=test_pass, action=create, graph_id=-1)""",
)
self.assertEqual(
node_source.to_dict(),
{
"name": "add",
"target": "aten.add.Tensor",
"pass_name": "test_pass",
"action": CREATE_STR,
"graph_id": graph_id,
"from_node": [dummy_source_dict],
},
)
# Test two node sources are same
node_source1 = NodeSource(
node=None, pass_name="test_pass", action=NodeSourceAction.CREATE
)
node_source2 = NodeSource(
node=None, pass_name="test_pass", action=NodeSourceAction.CREATE
)
self.assertEqual(node_source1, node_source2)
# Test hash function - equivalent objects should have same hash
self.assertEqual(hash(node_source1), hash(node_source2))
# Test two node sources are not same
node_source3 = NodeSource(
node=None, pass_name="test_pass_1", action=NodeSourceAction.CREATE
)
node_source4 = NodeSource(
node=None, pass_name="test_pass_2", action=NodeSourceAction.CREATE
)
self.assertNotEqual(node_source3, node_source4)
# Test hash function - different objects should have different hash
self.assertNotEqual(hash(node_source3), hash(node_source4))
# Test that equivalent NodeSource objects can be used in sets and dicts
node_set = {node_source1, node_source2}
self.assertEqual(len(node_set), 1) # Should only contain one unique element
node_dict = {node_source1: "value1", node_source2: "value2"}
self.assertEqual(len(node_dict), 1) # Should only contain one key
self.assertEqual(node_dict[node_source1], "value2") # Last value should win
# Test with more complex NodeSource objects
node_source_with_node = NodeSource(
node=node, pass_name="test_pass", action=NodeSourceAction.CREATE
)
node_source_with_node_copy = NodeSource(
node=node, pass_name="test_pass", action=NodeSourceAction.CREATE
)
# These should be equal and have same hash
self.assertEqual(node_source_with_node, node_source_with_node_copy)
self.assertEqual(hash(node_source_with_node), hash(node_source_with_node_copy))
# Test with different actions
node_source_replace = NodeSource(
node=None, pass_name="test_pass", action=NodeSourceAction.REPLACE
)
node_source_create = NodeSource(
node=None, pass_name="test_pass", action=NodeSourceAction.CREATE
)
# These should be different and have different hashes
self.assertNotEqual(node_source_replace, node_source_create)
self.assertNotEqual(hash(node_source_replace), hash(node_source_create))
def test_graph_provenance(self):
def check_node_source(node_source_dict, name, pass_name, action):
self.assertEqual(node_source_dict["name"], name)
self.assertEqual(node_source_dict["pass_name"], pass_name)
self.assertEqual(node_source_dict["action"], action)
def get_first_node_source_and_check(node_source_dict):
"""
Get the first node source from the from_node list.
"""
self.assertEqual(len(node_source_dict["from_node"]), 1)
return node_source_dict["from_node"][0]
class Model(torch.nn.Module):
def __init__(self):
super().__init__()
self.fc1 = torch.nn.Linear(10, 16)
self.relu = torch.nn.ReLU()
self.fc2 = torch.nn.Linear(16, 1)
self.sigmoid = torch.nn.Sigmoid()
def forward(self, x):
x = self.fc1(x)
x = self.relu(x)
x = self.fc2(x)
x = self.sigmoid(x)
return (x,)
model = Model()
example_inputs = (torch.randn(8, 10),)
ep = torch.export.export(model, example_inputs, strict=True)
decomposed_ep = ep.run_decompositions(default_decompositions())
# node decomposed from same ancestor node should have same from_node info
for node in decomposed_ep.graph.nodes:
if node.op not in {"placeholder", "output"}:
assert "from_node" in node.meta
node_name_to_from_node = {
node.name: node.meta["from_node"]
for node in decomposed_ep.graph.nodes
if node.op not in {"placeholder", "output"}
}
same_ancestor_nodes = {
"permute": "addmm",
"addmm": "permute",
"permute_1": "addmm_1",
"addmm_1": "permute_1",
}
for node_name_1 in node_name_to_from_node:
for node_name_2 in node_name_to_from_node:
if node_name_2 in {
node_name_1,
same_ancestor_nodes.get(node_name_1),
}:
self.assertEqual(
node_name_to_from_node[node_name_1],
node_name_to_from_node[node_name_2],
)
self.assertEqual(
[
NodeSource._from_dict(ns.to_dict())
for ns in node_name_to_from_node[node_name_1]
],
node_name_to_from_node[node_name_2],
)
else:
self.assertNotEqual(
node_name_to_from_node[node_name_1],
node_name_to_from_node[node_name_2],
)
self.assertNotEqual(
[
NodeSource._from_dict(ns.to_dict())
for ns in node_name_to_from_node[node_name_1]
],
node_name_to_from_node[node_name_2],
)
gm = ep.module()
provenance = get_graph_provenance_json(gm.graph)
self.assertEqual(
set(provenance.keys()), {"relu", "linear", "sigmoid", "linear_1"}
)
# Check node "linear" is created from node "x" in PropagateUnbackedSymInts
key_provenance = provenance["linear"][0]["from_node"]
self.assertEqual(len(key_provenance), 1)
key_provenance = key_provenance[0]
check_node_source(
key_provenance,
"x",
"Interpreter_PropagateUnbackedSymInts",
CREATE_STR,
)
# Check node "x" is then created from another node "x" in FlattenInputOutputSignature
key_provenance = get_first_node_source_and_check(key_provenance)
check_node_source(
key_provenance,
"x",
"Interpreter_DynamoGraphTransformer",
CREATE_STR,
)
gm, graph_signature = aot_export_module(
gm,
example_inputs,
trace_joint=False,
)
provenance = get_graph_provenance_json(gm.graph)
self.assertEqual(
set(provenance.keys()), {"t", "addmm", "relu", "t_1", "addmm_1", "sigmoid"}
)
for key in ["t", "addmm"]:
# The node provenance hierarchy should be:
# t -> linear -> x -> x
#
# x -> y means x is created from y
key_provenance = provenance[key]
self.assertEqual(len(key_provenance), 1)
key_provenance = key_provenance[0]
# Check node "t" and "addmm" is created from node "linear" in PropagateUnbackedSymInts
check_node_source(
key_provenance,
"linear",
"Interpreter_PropagateUnbackedSymInts",
CREATE_STR,
)
# Check node "linear" is then created from node "x" in PropagateUnbackedSymInts
key_provenance = get_first_node_source_and_check(key_provenance)[
"from_node"
][0]
check_node_source(
key_provenance,
"x",
"Interpreter_PropagateUnbackedSymInts",
CREATE_STR,
)
# Check node "x" is then created from another node "x" in FlattenInputOutputSignature
key_provenance = get_first_node_source_and_check(key_provenance)
check_node_source(
key_provenance,
"x",
"Interpreter_DynamoGraphTransformer",
CREATE_STR,
)
if __name__ == "__main__":
raise RuntimeError(
"This test is not currently used and should be "
"enabled in discover_tests.py if required."
)
| TestFXNodeSource |
python | huggingface__transformers | src/transformers/models/zamba/modeling_zamba.py | {
"start": 9952,
"end": 13400
} | class ____(nn.Module):
"""
Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
and "Generating Long Sequences with Sparse Transformers".
Adapted from transformers.models.mistral.modeling_mistral.MistralAttention:
The input dimension here is attention_hidden_size = 2 * hidden_size, and head_dim = attention_hidden_size // num_heads.
The extra factor of 2 comes from the input being the concatenation of original_hidden_states with the output of the previous (mamba) layer
(see fig. 2 in https://huggingface.co/papers/2405.16712).
Additionally, replaced
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim) with
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim/2)
"""
def __init__(self, config: ZambaConfig, layer_idx: int):
super().__init__()
self.config = config
self.layer_idx = layer_idx
self.attention_hidden_size = config.attention_hidden_size
self.head_dim = config.attention_head_dim
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
self.max_position_embeddings = config.max_position_embeddings
self.scaling = (self.head_dim / 2) ** -0.5
self.is_causal = True
self.attention_dropout = config.attention_dropout
self.q_proj = nn.Linear(config.attention_hidden_size, config.num_attention_heads * self.head_dim, bias=False)
self.k_proj = nn.Linear(config.attention_hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
self.v_proj = nn.Linear(config.attention_hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
def forward(
self,
hidden_states: torch.Tensor,
layer_idx: int,
attention_mask: Optional[torch.Tensor],
past_key_values: Optional[ZambaHybridDynamicCache] = None,
**kwargs: Unpack[FlashAttentionKwargs],
) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim)
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
if past_key_values is not None:
key_states, value_states = past_key_values.update(key_states, value_states, layer_idx)
attention_interface: Callable = eager_attention_forward
if self.config._attn_implementation != "eager":
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
attn_output, attn_weights = attention_interface(
self,
query_states,
key_states,
value_states,
attention_mask,
dropout=0.0 if not self.training else self.attention_dropout,
scaling=self.scaling,
**kwargs,
)
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
attn_output = self.o_proj(attn_output)
return attn_output, attn_weights
| ZambaAttention |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.