File size: 6,099 Bytes
4dc2dcb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3321047
 
4dc2dcb
 
 
 
321366c
 
4dc2dcb
 
 
 
321366c
4dc2dcb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
321366c
4dc2dcb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3321047
 
 
 
 
 
 
4dc2dcb
 
 
 
 
3321047
 
4dc2dcb
 
 
 
 
 
3321047
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4dc2dcb
3321047
4dc2dcb
3321047
4dc2dcb
 
 
 
 
 
 
 
 
 
321366c
4dc2dcb
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
import inseq
import captum

import gradio as gr
import matplotlib.pyplot as plt


import torch
import os
# import nltk
import argparse
import random
import numpy as np

from argparse import Namespace
from tqdm.notebook import tqdm
from torch.utils.data import DataLoader
from functools import partial

import pandas as pd


model_es = "Helsinki-NLP/opus-mt-en-es"
model_fr = "Helsinki-NLP/opus-mt-en-fr"
model_zh = "Helsinki-NLP/opus-mt-en-zh"
model_sw = "Helsinki-NLP/opus-mt-en-sw"


model_es = inseq.load_model("Helsinki-NLP/opus-mt-en-es", "input_x_gradient")
model_fr = inseq.load_model("Helsinki-NLP/opus-mt-en-fr", "input_x_gradient")
model_zh = inseq.load_model("Helsinki-NLP/opus-mt-en-zh", "input_x_gradient")
model_sw = inseq.load_model("Helsinki-NLP/opus-mt-en-sw", "input_x_gradient")


def saliency_contrastive(input, ref, cont, inseq_model):

    # model = inseq.load_model(dict_models[inseq_model], "input_x_gradient")

    input = input if input != '' else 'example text'

    # out = model.attribute(
    # input_texts=input,
    # attribute_target=True,
    # step_scores=["probability"],
    # )


    out = dict_models[inseq_model].attribute(
        input, # Input
        ref, # Forced target
        attributed_fn="contrast_prob_diff",
        contrast_targets=cont, #contrastive
        attribute_target=True,
        # contrast_targets_alignments="auto",
        step_scores=["contrast_prob_diff"],
    )



    # Visualize the attributions and step scores
    html_out = out.show(return_html=True, display=False)
    return gr.Plot(value=html_out)


def saliency_inseq(input, inseq_model):

    # model = inseq.load_model(dict_models[inseq_model], "input_x_gradient")

    input = input if input != '' else 'example text'

    out = dict_models[inseq_model].attribute(
    input_texts=input,
    attribute_target=True,
    step_scores=["probability"],
    )
    text_out = out.info['generated_texts']

    # Visualize the attributions and step scores
    html_out = out.show(return_html=True, display=False)

    return [gr.Plot(value=html_out), text_out]



def model_generate(input, inseq_model):
    model = inseq.load_model(dict_models[inseq_model], "input_x_gradient")
    output = model.generate(input)

    # Visualize the attributions and step scores
    return output


dict_models = {
	'en-zh': model_zh,
	'en-fr': model_fr,
	'en-es': model_es,
	'en-sw': model_sw
}

saliency_examples = [
	"Peace of Mind: Protection for consumers.",
	"The sustainable development goals report: towards a rescue plan for people and planet",
	"We will leave no stone unturned to hold those responsible to account.",
	"The clock is now ticking on our work to finalise the remaining key legislative proposals presented by this Commission to ensure that citizens and businesses can reap the benefits of our policy actions.",
	"Pumpkins, squash and gourds, fresh or chilled, excluding courgettes",
	"The labour market participation of mothers with infants has even deteriorated over the past two decades, often impacting their career and incomes for years.",
]

contrastive_examples = [
["Peace of Mind: Protection for consumers.",
"Paz mental: protección de los consumidores",
"Paz de la mente: protección de los consumidores"],
["the slaughterer has finished his work.",
"l'abatteur a terminé son travail.",
"l'abatteuse a terminé son travail."],
['A fundamental shift is needed - in commitment, solidarity, financing and action - to put the world on a better path.',
 '需要在承诺、团结、筹资和行动方面进行根本转变,使世界走上更美好的道路。',
 '我们需要从根本上转变承诺、团结、资助和行动,使世界走上更美好的道路。',]
	]


#Load challenge set examples
df_challenge_set = pd.read_csv("challenge_sets.csv")
arr_challenge_set = df_challenge_set.values
arr_challenge_set = [[x[2], x[3], x[4], x[5]] for x in arr_challenge_set]



with gr.Blocks(theme=gr.themes.Default()) as demo:
	gr.Markdown("""
                # MAKE NMT Workshop \t `Inseq`
                """)


			
	with gr.Tab("Saliency"):
		gr.Markdown("""
		### Method: Input X Gradient
		The absolute value of these coefficients can be taken to represent feature importance.
		https://arxiv.org/abs/1312.6034
		""")
		with gr.Row():
			with gr.Column(scale=2):
				gr.Markdown(
					"""
					### Translation
					""")
				text_input = gr.Textbox(label="Source Text")
				text_output_box = gr.Textbox(label="Target Text")
			with gr.Column(scale=4):
				gr.Markdown(
					"""
					### If challenge is selected from the challenge set list bellow
					""")
				challenge_ex  = gr.Textbox(label="Challenge", interactive=False)
				category_minor  = gr.Textbox(label="category_minor", interactive=False)
				category_major  = gr.Textbox(label="category_major", interactive=False)

				with gr.Accordion("Challenge selection:"):
					gr.Examples(arr_challenge_set,[text_input, challenge_ex,category_minor,category_major], label="")
		# gr.Examples(saliency_examples, text_input)
		radio = gr.Radio(choices=['en-zh', 'en-es', 'en-fr', 'en-sw'], value="en-fr",  label= '', container=False)
		text_button = gr.Button("Translate")
		text_output = gr.HTML()

	with gr.Tab("Contrastive "):
		gr.Markdown("""
		### How is this feature X contributing to the prediction of A rather than B?
		https://aclanthology.org/2022.emnlp-main.14.pdf
		""")
		text_input_c = gr.Textbox(label="Source Text")
		text_input_ref = gr.Textbox(label="Reference Text (A)")
		text_input_cont = gr.Textbox(label="Contrastive Text (B)")
		gr.Examples(contrastive_examples,[text_input_c, text_input_ref, text_input_cont])
		text_output_c = gr.HTML()

		radio_c = gr.Radio(choices=['en-zh', 'en-es', 'en-fr', 'en-sw'], value="en-fr", label= '', container=False)
		text_button_c = gr.Button("Translate")

	text_button.click(fn=saliency_inseq, inputs=[text_input, radio], outputs=[text_output, text_output_box])
	text_button_c.click(fn=saliency_contrastive, inputs=[text_input_c, text_input_ref, text_input_cont, radio_c], outputs=text_output_c)



if __name__ == "__main__":   
    demo.launch()