From: Michael Kösel Date: Fri, 15 Mar 2019 18:43:33 +0000 (-0700) Subject: add reverse to list (#17001) X-Git-Tag: accepted/tizen/6.5/unified/20211028.231830~786 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=cd26200d1b01cd66c2c5d641feba836a8f2341d3;p=platform%2Fupstream%2Fpytorch.git add reverse to list (#17001) Summary: Add reverse functionality to list. See https://github.com/pytorch/pytorch/issues/16662 ```python import torch torch.jit.script def foo(): a = [1, 2, 3, 4] a.reverse() return a ``` Pull Request resolved: https://github.com/pytorch/pytorch/pull/17001 Reviewed By: eellison Differential Revision: D14092019 Pulled By: driazati fbshipit-source-id: b353c763677c22312b64dde0db268e2988610ba1 --- diff --git a/test/test_jit.py b/test/test_jit.py index e470bd9..896cc4b 100644 --- a/test/test_jit.py +++ b/test/test_jit.py @@ -4146,6 +4146,30 @@ a") self.assertEqual(foo(), [1, 2, 3, 4]) + def test_mutable_list_reverse_empty(self): + def test_reverse_empty(): + a = [] + a.reverse() + + return a == [] + self.checkScript(test_reverse_empty, ()) + + def test_mutable_list_reverse(self): + def test_reverse(): + a = [1, 2, 3, 4] + a.reverse() + + return a == [4, 3, 2, 1] + self.checkScript(test_reverse, ()) + + def test_mutable_tensor_list_reverse(self): + def test_tensor_reverse(): + a = [torch.tensor(1), torch.tensor(2)] + a.reverse() + + return a == [torch.tensor(2), torch.tensor(1)] + self.checkScript(test_tensor_reverse, ()) + def test_mutable_list_pop_empty(self): @torch.jit.script def test_pop_empty(): diff --git a/torch/csrc/jit/register_prim_ops.cpp b/torch/csrc/jit/register_prim_ops.cpp index 5db825c..0075b08 100644 --- a/torch/csrc/jit/register_prim_ops.cpp +++ b/torch/csrc/jit/register_prim_ops.cpp @@ -991,6 +991,17 @@ int listAppend(Stack& stack) { } template +int listReverse(Stack& stack) { + TList a; + pop(stack, a); + + auto& elements = a->elements(); + std::reverse(elements.begin(), elements.end()); + + return 0; +} + +template int listPop(Stack& stack) { TList list; int64_t idx; @@ -1440,6 +1451,9 @@ RegisterOperators reg2({ "(c) el) -> " decl_type "[](a!)", \ listAppend, c_type::ElemType>), \ Operator( \ + "aten::reverse( " decl_type "[](a!) self) -> ()", \ + listReverse>), \ + Operator( \ "aten::extend(" decl_type "[](a!) self, " decl_type \ " [] other) -> ()", \ listExtend>), \ @@ -1482,6 +1496,9 @@ RegisterOperators reg2({ " el) -> " decl_type "[](a!)", \ listAppend, c_type::ElemType>), \ Operator( \ + "aten::reverse(" decl_type "[](a!) self) -> ()", \ + listReverse>), \ + Operator( \ "aten::extend(" decl_type "[](a!) self, " decl_type \ " [] other) -> ()", \ listExtend>), \ @@ -1524,7 +1541,7 @@ RegisterOperators reg2({ #undef CREATE_MUTABLE_LIST_OPS #define CREATE_LIST_OPS(decl_type, c_type) \ - Operator("aten::len(" decl_type "[] a) -> int", listLen>), \ + Operator("aten::len(" decl_type "[] a) -> int", listLen>), \ Operator( \ "aten::add(" decl_type "[] a, " decl_type "[] b) -> " decl_type \ "[]", \