MCPcopy Create free account
hub / github.com/apache/tvm / test_self_attention

Function test_self_attention

tests/python/relax/test_dataflow_pattern.py:675–722  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

673
674
675def test_self_attention():
676 # The example comes from.
677 # https://developer.nvidia.com/blog/nlu-with-tensorrt-bert/
678 @tvm.script.ir_module
679 class SelfAttention:
680 @R.function
681 def main(
682 x: R.Tensor(("b", "s", "n", "h"), "float32"),
683 wq: R.Tensor(("h", "h"), "float32"),
684 wk: R.Tensor(("h", "h"), "float32"),
685 wv: R.Tensor(("h", "h"), "float32"),
686 ) -> R.Tensor:
687 b, s, n, h = T.int64(), T.int64(), T.int64(), T.int64()
688 with R.dataflow():
689 fcq = R.call_dps_packed("my_fc", (x, wq), R.Tensor((b, s, n, h), dtype="float32"))
690 tpq = R.call_dps_packed(
691 "my_transpose", (fcq,), R.Tensor((b, s, h, n), dtype="float32")
692 )
693
694 fck = R.call_dps_packed("my_fc", (x, wk), R.Tensor((b, s, n, h), dtype="float32"))
695 tpk = R.call_dps_packed(
696 "my_transpose", (fck,), R.Tensor((b, s, h, n), dtype="float32")
697 )
698
699 mul = R.multiply(tpq, tpk)
700 scale = R.multiply(mul, R.const(1.1, "float32"))
701 softmax = R.call_dps_packed(
702 "softmax", (scale,), R.Tensor((b, s, n, h), dtype="float32")
703 )
704
705 fcv = R.call_dps_packed("my_fc", (x, wv), R.Tensor((b, s, n, h), dtype="float32"))
706 tpv = R.call_dps_packed(
707 "my_transpose", (fcv,), R.Tensor((b, s, h, n), dtype="float32")
708 )
709
710 out = R.multiply(softmax, tpv)
711 R.output(out)
712
713 return out
714
715 with PatternContext() as ctx:
716 fc_trans_q = is_call_dps_packed("my_fc") >> is_call_dps_packed("my_transpose")
717 fc_trans_k = fc_trans_q.dup()
718 fc_trans_v = fc_trans_q.dup()
719
720 is_var("x").fork_to(fc_trans_q, fc_trans_k, fc_trans_v)
721 dfb = SelfAttention["main"].body.blocks[0]
722 assert ctx.match_dfb(dfb)
723
724
725def test_nested_diamond():

Callers

nothing calls this directly

Calls 6

PatternContextClass · 0.85
is_call_dps_packedFunction · 0.85
is_varFunction · 0.85
fork_toMethod · 0.80
match_dfbMethod · 0.80
dupMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…