CNTK icon indicating copy to clipboard operation
CNTK copied to clipboard

Is it possible to slice a sequence "dynamically"?

Open whuala opened this issue 8 years ago • 4 comments

I'm tying to slice a sequence using C.sequence.slice(seq, start, end). Here start and end are both outputs of another layer. So I got this error since start and end are not int.

NotImplementedError: Wrong number or type of arguments for overloaded function 'sequence_slice'.
  Possible C/C++ prototypes are:
    CNTK::Sequence::Slice(CNTK::Variable const &,int,int,std::wstring const &)
    CNTK::Sequence::Slice(CNTK::Variable const &,int,int)

Is there a possible way to do so? Thanks in advance!

whuala avatar Mar 05 '18 13:03 whuala

Slice does not support non-literal inputs. Please use sequence.gather instead.

ke1337 avatar Mar 05 '18 19:03 ke1337

I noticed that the condition in gather(seq, condition, new_sequence_axis_typeinfo=None, name='') take care of the tensor within the sequence. But I only have the information about the "index" of the start and end . How can I correctly write the condition here?

whuala avatar Mar 06 '18 02:03 whuala

Below code is an example to do dynamic slice in sequence using UnfoldFrom and sequence.gather. Note that the negative index is not supported, nor does begin > end, but should be OK as a demonstration:

import cntk as C

@C.Function
def gen_func(xc):
    begin = xc[0] # begin is included
    end = xc[1]   # end is excluded
    step = xc[2]
    value = C.greater((step - begin + 1) * (end - step), 0)
    return C.splice(begin, end, step + 1, value)

x = C.input_variable((2,)) # the begin/end index to slice 
xs = C.sequence.input_variable(()) # the sequence to slice
index = C.layers.UnfoldFrom(gen_func)(C.splice(x, C.constant((0,-1))), xs)
y = C.sequence.gather(xs, index[3])
print(y.eval({x:[[1,3],[2,5]], xs:[[4,3,2,1],[10,20,30,40,50,60]]}))

The output:

[array([3., 2.], dtype=float32), array([30., 40., 50.], dtype=float32)]

ke1337 avatar Mar 06 '18 21:03 ke1337

Thanks! Closing...

whuala avatar Mar 07 '18 12:03 whuala