GradientTapeは、損失関数の顕著性を計算します

Dec 14 2020

文を分類し、顕著性を使用して分類の説明を提供するLSTMネットワークを構築しようとしています。このネットワークは、真のクラスとy_true、彼が注意を払うべきではない単語Z(バイナリマスク)から学習する必要があります。

この論文は、損失関数を考え出すきっかけとなりました。損失関数を次のように表示します。

Coût de classification以下のコードのclassification_lossCoût d'explication (saillance)に変換されますsaliency_loss(これは、入力に対する出力の勾配と同じです)。Tensorflowをバックエンドとして、Kerasのカスタムモデルでこれを実装しようとしました:

loss_tracker = metrics.Mean(name="loss")
classification_loss_tracker = metrics.Mean(name="classification_loss")
saliency_loss_tracker = metrics.Mean(name="saliency_loss")
accuracy_tracker = metrics.CategoricalAccuracy(name="accuracy")

class CustomSequentialModel(Sequential):
        
    def _train_test_step(self, data, training):
        # Unpack the data
        X = data[0]["X"]
        Z = data[0]["Z"] # binary mask (1 for important words)
        y_true = data[1]
        
        # gradient tape requires "float32" instead of "int32"
        # X.shape = (None, MAX_SEQUENCE_LENGTH, EMBEDDING_DIM)
        X = tf.cast(X, tf.float32)

        # Persitent=True because we call the `gradient` more than once
        with GradientTape(persistent=True) as tape:
            # The tape will record everything that happens to X
            # for automatic differentiation later on (used to compute saliency)
            tape.watch(X)
            # Forward pass
            y_pred = self(X, training=training) 
            
            # (1) Compute the classification_loss
            classification_loss = K.mean(
                categorical_crossentropy(y_true, y_pred)
            )
 
            # (2) Compute the saliency loss
            # (2.1) Compute the gradient of output wrt the maximum probability
            log_prediction_proba = K.log(K.max(y_pred))
            
        # (2.2) Compute the gradient of the output wrt the input
        # saliency.shape is (None, MAX_SEQUENCE_LENGTH, None)
        # why isn't it (None, MAX_SEQUENCE_LENGTH, EMBEDDING_DIM) ?!
        saliency = tape.gradient(log_prediction_proba, X)
        # (2.3) Sum along the embedding dimension
        saliency = K.sum(saliency, axis=2)
        # (2.4) Sum with the binary mask
        saliency_loss = K.sum(K.square(saliency)*(1-Z))
        # =>  ValueError: No gradients provided for any variable
        loss = classification_loss + saliency_loss 
        
        trainable_vars = self.trainable_variables
        # ValueError caused by the '+ saliency_loss'
        gradients = tape.gradient(loss, trainable_vars) 
        del tape # garbage collection
        
        if training:
            # Update weights
            self.optimizer.apply_gradients(zip(gradients, trainable_vars))
        
        # Update metrics
        saliency_loss_tracker.update_state(saliency_loss)
        classification_loss_tracker.update_state(classification_loss)
        loss_tracker.update_state(loss)
        accuracy_tracker.update_state(y_true, y_pred)
        
        # Return a dict mapping metric names to current value
        return {m.name: m.result() for m in self.metrics}
    
    def train_step(self, data):
        return self._train_test_step(data, True)
    
    def test_step(self, data):
        return self._train_test_step(data, False)
    
    @property
    def metrics(self):
        return [
            loss_tracker,
            classification_loss_tracker,
            saliency_loss_tracker,
            accuracy_tracker
        ]

私は計算するために管理するclassification_lossだけでなくsaliency_loss、私はスカラー値を取得します。ただし、これは機能します:tape.gradient(classification_loss, trainable_vars)tape.gradient(classification_loss + saliency_loss, trainable_vars)しかし、これは機能せず、スローしValueError: No gradients provided for any variableます。

回答

1 xdurch0 Dec 14 2020 at 07:21

(最初のgradient呼び出しの後)テープコンテキストの外部で計算を実行し、その後、さらに勾配を取得しようとしています。これは機能しません。区別するためのすべての操作は、コンテキストマネージャー内で行う必要があります。2つのネストされたテープを使用して、コードを次のように再構築することをお勧めします。

with GradientTape() as loss_tape:
    with GradientTape() as saliency_tape:
        # The tape will record everything that happens to X
        # for automatic differentiation later on (used to compute saliency)
        saliency_tape.watch(X)
        # Forward pass
        y_pred = self(X, training=training) 
        
        # (2) Compute the saliency loss
        # (2.1) Compute the gradient of output wrt the maximum probability
        log_prediction_proba = K.log(K.max(y_pred))
        
    # (2.2) Compute the gradient of the output wrt the input
    # saliency.shape is (None, MAX_SEQUENCE_LENGTH, None)
    # why isn't it (None, MAX_SEQUENCE_LENGTH, EMBEDDING_DIM) ?!
    saliency = saliency_tape.gradient(log_prediction_proba, X)
    # (2.3) Sum along the embedding dimension
    saliency = K.sum(saliency, axis=2)
    # (2.4) Sum with the binary mask
    saliency_loss = K.sum(K.square(saliency)*(1-Z))

    # (1) Compute the classification_loss
    classification_loss = K.mean(
        categorical_crossentropy(y_true, y_pred)
    )

    loss = classification_loss + saliency_loss 
    
trainable_vars = self.trainable_variables
gradients = loss_tape.gradient(loss, trainable_vars)

これで、顕著性の入力に対する勾配の計算を担当するテープが1つあります。我々は持っている他のこれらの操作を追跡し、後で勾配(すなわち勾配顕著性)の勾配を計算することができ、それの周りにテープを。このテープは、分類損失の勾配も計算します。内側のテープは分類損失を必要としないため、外側のテープのコンテキストで分類損失を移動しました。また、2つの損失の加算でさえ、外側のテープのコンテキスト内にあることに注意してください。すべてがそこで発生する必要があります。そうしないと、計算グラフが失われるか不完全になり、勾配を計算できません。

Andrey Dec 14 2020 at 00:31

で飾っtrain_step()てみてください@tf.function