[TensorFlow Seq2seq Library (contrib)] (tf v1.12기준)
https://www.tensorflow.org/api_guides/python/contrib.seq2seq
tensorflow Seq2seq Library는 seq2seq모델과 dynamic decoding을 위한 모듈로써 tf.contrib.rnn 기반으로 만들어졌다.
tensorflow seq2seq library 내 2가지 주요한 컴포넌트
1) attention wrapper (for tf.contrib.rnn.RNNCell)
2) 객체지향 dynamic decoding framework
1. Attention
attention wrapper는 다른 RNNCell을 감싸고 attention을 구현하는 RNNcell 오브젝트이다. attention의 종류는 tf.contrib.seq2seq.AttentionMechanism 하위 클래스(LuongAttention / BahdanauAttention / BahdanauMonotonicAttention / LuongMonotonicAttention)에 의해 결정된다. 이 하위 클래스들은 각기 다른 형태를 가진 attention을 나타낸다. (e.g. Bahdanau: additive (concat) vs. Luong: multiplicative (dot product) ). AttentionMechanism의 인스턴스는 memory tensor로 만들어진다. (lookup keys, values tensors)
1) Attentsion Machnism
기본적인 두가지 attention machanism
tf.contrib.seq2seq.BahdanauAttention (additive attention, ref.)
tf.contrib.seq2seq.LuongAttention (multiplicative attention, ref.)
attention mechanism을 생성하기 위해 memory tensor가 필요하고, 텐서의 shape은 [batch_size, memory_max_time, memory_depth]의 형태를 가져야 한다. (memory tensor : encoder로 사용될 RNNcell로 이해하면 된다.) 추가적으로 memory_sequence_length 벡터도 쓸 수 있는데 그렇게 되면 동적이 아닌 정적으로 진행되며 고정된 길이의 length를 사용하기 위해 memory 텐서의 sequence_length 이후의 rows는 0으로 채워져야한다 (keras의 pad_sequence를 참조하면 이해가 더 쉬울 수 있다).
attention mechanism은 depth 개념도 가지고 있는데 num_units parameter로 설정할 수 있다. 종종 BahdanauAttention 같은 attention은 queries, memory depth 둘다 num_units depth 만큼 projection되야하고, LuongAttention 같은 경우 num_units이 반드시 query(input)의 depth와 일치해야한다. memory tensor는 이 num_units만큼 프로젝션 될것이다. (num_units : RNNcell 하나를 구성할때 필요한 NN의 개수)
2) Attention Wrappers
기본적인 attention wrapper는 tf.contrib.seq2seq.AttentionWrapper 이다. 이 wrapper는 AttentionMechanism의 인스턴스(RNNCell 기반)를 인자로 요구한다. 또한 attention의 depth는 attention_size로 정할수 있고, customising을 하기 위해 여러가지 optional한 인자도 전달 할 수 있다.
매 step 마다, wrapper에 의해 수행되는 기본적인 계산은 다음과 같다. (세부로직)
cell_inputs = concat([inputs, prev_state.attention], -1)
cell_output, next_cell_state = cell(cell_inputs, prev_state.cell_state)
score = attention_mechanism(cell_output)
alignments = softmax(score)
context = matmul(alignments, attention_mechanism.values)
attention = tf.layers.Dense(attention_size)(concat([cell_output, context], 1))
next_state = AttentionWrapperState(
cell_state=next_cell_state,
attention=attention)
output = attention
return output, next_state
여기서 많은 수식들을 상황에 맞게 설정할 수 있다. 예를 들어 처음에 cell_inputs으로 inputs과 prev_state.attention의 concatenation하는게 아니라 다른 방식으로 mixing 할 수 있고, score에서 alignments을 구하는 softmax 함수도 다른 함수로 바꿀 수 있다. wrapper에 의한 마지막으로 산출되는 outputs은 attention 대신에 cell_output 값으로 바꿀 수 있다.
AttentionWrapper를 사용해서 얻게되는 이점은 아래에 설명된 다른 wrapper들과 dynamic decoder와 함께 잘 동작한다는 것이다. 예를 들어 다음과 같이 사용 할 수 있다.
cell = tf.contrib.rnn.DeviceWrapper(LSTMCell(512), "/device:GPU:0")
attention_mechanism = tf.contrib.seq2seq.LuongAttention(512, encoder_outputs)
attn_cell = tf.contrib.seq2seq.AttentionWrapper(
cell, attention_mechanism, attention_size=256)
attn_cell = tf.contrib.rnn.DeviceWrapper(attn_cell, "/device:GPU:1")
top_cell = tf.contrib.rnn.DeviceWrapper(LSTMCell(512), "/device:GPU:1")
multi_cell = MultiRNNCell([attn_cell, top_cell])
multi_rnn cell은 GPU 0에서 bottm layer 계산을 수행되고, attention 계산은 GPU 1에서 수행되서 바로 top layer에 전달되어 GPU 1에서 또한 계산 될것이다. attention은 또한 제 시간에 전달되어 다음 cell 계산을 위해 GPU 0에 전달 될 것이다. (Note : 단순 예시이고 효율적인 partitioning은 아님.)
2. Dynamic Decoding
Example usage:
cell = # instance of RNNCell
if mode == "train":
helper = tf.contrib.seq2seq.TrainingHelper(
input=input_vectors,
sequence_length=input_lengths)
elif mode == "infer":
helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(
embedding=embedding,
start_tokens=tf.tile([GO_SYMBOL], [batch_size]),
end_token=END_SYMBOL)
decoder = tf.contrib.seq2seq.BasicDecoder(
cell=cell,
helper=helper,
initial_state=cell.zero_state(batch_size, tf.float32))
outputs, _ = tf.contrib.seq2seq.dynamic_decode(
decoder=decoder,
output_time_major=False,
impute_finished=True,
maximum_iterations=20)
Decoder base class and functions
tf.contrib.seq2seq.Decoder
tf.contrib.seq2seq.dynamic_decode
Basic Decoder
tf.contrib.seq2seq.BasicDecoderOutput
tf.contrib.seq2seq.BasicDecoder
Decoder Helpers
tf.contrib.seq2seq.Helper
tf.contrib.seq2seq.CustomHelper
tf.contrib.seq2seq.GreedyEmbeddingHelper
tf.contrib.seq2seq.ScheduledEmbeddingTrainingHelper
tf.contrib.seq2seq.ScheduledOutputTrainingHelper
tf.contrib.seq2seq.TrainingHelper
'Data Science > Neural Network' 카테고리의 다른 글
RNN 계열 신경망 모델 (0) | 2021.04.19 |
---|---|
Neural Machine Translation (seq2seq) Tutorial (0) | 2018.12.08 |
Partial Derivative(편미분) and Chain Rule(체인룰) in Neural Network (0) | 2018.05.27 |
ReLU를 사용하는 이유 (0) | 2018.05.24 |