codebert commited on
Commit
5604afd
1 Parent(s): 727b99c

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +189 -147
README.md CHANGED
@@ -25,153 +25,195 @@ UniXcoder is a unified cross-modal pre-trained model that leverages multimodal d
25
 
26
  # Uses
27
 
28
-
29
-
30
- ## Direct Use
31
- Feature Engineering
32
-
33
-
34
- ## Downstream Use [Optional]
35
-
36
- More information needed
37
-
38
- ## Out-of-Scope Use
39
-
40
- More information needed
41
-
42
- # Bias, Risks, and Limitations
43
-
44
- Significant research has explored bias and fairness issues with language models (see, e.g., [Sheng et al. (2021)](https://aclanthology.org/2021.acl-long.330.pdf) and [Bender et al. (2021)](https://dl.acm.org/doi/pdf/10.1145/3442188.3445922)). Predictions generated by the model may include disturbing and harmful stereotypes across protected classes; identity characteristics; and sensitive, social, and occupational groups.
45
-
46
-
47
- ## Recommendations
48
-
49
-
50
- Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
51
-
52
-
53
- # Training Details
54
-
55
- ## Training Data
56
-
57
- More information needed
58
-
59
- ## Training Procedure
60
-
61
- ### Preprocessing
62
-
63
- More information needed
64
-
65
- ### Speeds, Sizes, Times
66
- More information needed
67
-
68
- # Evaluation
69
-
70
-
71
- ## Testing Data, Factors & Metrics
72
-
73
- ### Testing Data
74
- More information needed
75
-
76
- ### Factors
77
-
78
- The model creators note in the [associated paper](https://arxiv.org/abs/2203.03850):
79
-
80
- > UniXcoder has slightly worse BLEU-4 scores on both code summarization and generation tasks. The main reasons may come from two aspects. One is the amount of NL-PL pairs in the pre-training data
81
-
82
- ### Metrics
83
-
84
- The model creators note in the [associated paper](https://arxiv.org/abs/2203.03850):
85
-
86
- > We evaluate UniXcoder on five tasks over nine public datasets, including two understanding tasks, two generation tasks and an autoregressive task. To further evaluate the performance of code fragment embeddings, we also propose a new task called zero-shot code-to-code search.
87
-
88
- ## Results
89
-
90
- The model creators note in the [associated paper](https://arxiv.org/abs/2203.03850):
91
-
92
- >Taking zero-shot code-code search task as an example, after removing contrastive learning, the performance drops from 20.45% to 13.73%.
93
-
94
- # Model Examination
95
-
96
- More information needed
97
-
98
- # Environmental Impact
99
-
100
-
101
-
102
- Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
103
-
104
- - **Hardware Type:** More information needed
105
- - **Hours used:** More information needed
106
- - **Cloud Provider:** More information needed
107
- - **Compute Region:** More information needed
108
- - **Carbon Emitted:** More information needed
109
-
110
- # Technical Specifications [optional]
111
-
112
- ## Model Architecture and Objective
113
-
114
- More information needed
115
-
116
- ## Compute Infrastructure
117
-
118
- More information needed
119
-
120
- ### Hardware
121
-
122
- More information needed
123
-
124
- ### Software
125
-
126
- More information needed
127
-
128
- # Citation
129
-
130
-
131
- **BibTeX:**
132
- ```
133
- @misc{https://doi.org/10.48550/arxiv.2203.03850,
134
- doi = {10.48550/ARXIV.2203.03850},
135
-
136
- url = {https://arxiv.org/abs/2203.03850},
137
-
138
- author = {Guo, Daya and Lu, Shuai and Duan, Nan and Wang, Yanlin and Zhou, Ming and Yin, Jian},
139
-
140
- keywords = {Computation and Language (cs.CL), Programming Languages (cs.PL), Software Engineering (cs.SE), FOS: Computer and information sciences, FOS: Computer and information sciences},
141
-
142
- title = {UniXcoder: Unified Cross-Modal Pre-training for Code
143
  ```
144
-
145
-
146
- # Glossary [optional]
147
-
148
- More information needed
149
-
150
- # More Information [optional]
151
-
152
- More information needed
153
-
154
- # Model Card Authors [optional]
155
-
156
- Microsoft Team in collaboration with Ezi Ozoani and the Hugging Face Team.
157
-
158
- # Model Card Contact
159
-
160
- More information needed
161
-
162
- # How to Get Started with the Model
163
-
164
- Use the code below to get started with the model.
165
-
166
- <details>
167
- <summary> Click to expand </summary>
168
 
169
  ```python
170
- from transformers import AutoTokenizer, AutoModel
171
-
172
- tokenizer = AutoTokenizer.from_pretrained("microsoft/unixcoder-base")
173
-
174
- model = AutoModel.from_pretrained("microsoft/unixcoder-base")
175
-
176
- ```
177
- </details>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
  # Uses
27
 
28
+ ## 1. Dependency
29
+
30
+ - pip install torch
31
+ - pip install transformers
32
+
33
+ ## 2. Quick Tour
34
+ We implement a class to use UniXcoder and you can follow the code to build UniXcoder.
35
+ You can download the class by
36
+ ```shell
37
+ wget https://raw.githubusercontent.com/microsoft/CodeBERT/master/UniXcoder/unixcoder.py
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
  ```python
41
+ import torch
42
+ from unixcoder import UniXcoder
43
+
44
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
45
+ model = UniXcoder("microsoft/unixcoder-base")
46
+ model.to(device)
47
+ ```
48
+
49
+ In the following, we will give zero-shot examples for several tasks under different mode, including **code search (encoder-only)**, **code completion (decoder-only)**, **function name prediction (encoder-decoder)** , **API recommendation (encoder-decoder)**, **code summarization (encoder-decoder)**.
50
+
51
+ ## 3. Encoder-only Mode
52
+
53
+ For encoder-only mode, we give an example of **code search**.
54
+
55
+ ### 1) Code and NL Embeddings
56
+
57
+ Here, we give an example to obtain code fragment embedding from CodeBERT.
58
+
59
+ ```python
60
+ # Encode maximum function
61
+ func = "def f(a,b): if a>b: return a else return b"
62
+ tokens_ids = model.tokenize([func],max_length=512,mode="<encoder-only>")
63
+ source_ids = torch.tensor(tokens_ids).to(device)
64
+ tokens_embeddings,max_func_embedding = model(source_ids)
65
+
66
+ # Encode minimum function
67
+ func = "def f(a,b): if a<b: return a else return b"
68
+ tokens_ids = model.tokenize([func],max_length=512,mode="<encoder-only>")
69
+ source_ids = torch.tensor(tokens_ids).to(device)
70
+ tokens_embeddings,min_func_embedding = model(source_ids)
71
+
72
+ # Encode NL
73
+ nl = "return maximum value"
74
+ tokens_ids = model.tokenize([nl],max_length=512,mode="<encoder-only>")
75
+ source_ids = torch.tensor(tokens_ids).to(device)
76
+ tokens_embeddings,nl_embedding = model(source_ids)
77
+
78
+ print(max_func_embedding.shape)
79
+ print(max_func_embedding)
80
+ ```
81
+
82
+ ```python
83
+ torch.Size([1, 768])
84
+ tensor([[ 8.6533e-01, -1.9796e+00, -8.6849e-01, 4.2652e-01, -5.3696e-01,
85
+ -1.5521e-01, 5.3770e-01, 3.4199e-01, 3.6305e-01, -3.9391e-01,
86
+ -1.1816e+00, 2.6010e+00, -7.7133e-01, 1.8441e+00, 2.3645e+00,
87
+ ...,
88
+ -2.9188e+00, 1.2555e+00, -1.9953e+00, -1.9795e+00, 1.7279e+00,
89
+ 6.4590e-01, -5.2769e-02, 2.4965e-01, 2.3962e-02, 5.9996e-02,
90
+ 2.5659e+00, 3.6533e+00, 2.0301e+00]], device='cuda:0',
91
+ grad_fn=<DivBackward0>)
92
+ ```
93
+
94
+ ### 2) Similarity between code and NL
95
+
96
+ Now, we calculate cosine similarity between NL and two functions. Although the difference of two functions is only a operator (```<``` and ```>```), UniXcoder can distinguish them.
97
+
98
+ ```python
99
+ # Normalize embedding
100
+ norm_max_func_embedding = torch.nn.functional.normalize(max_func_embedding, p=2, dim=1)
101
+ norm_min_func_embedding = torch.nn.functional.normalize(min_func_embedding, p=2, dim=1)
102
+ norm_nl_embedding = torch.nn.functional.normalize(nl_embedding, p=2, dim=1)
103
+
104
+ max_func_nl_similarity = torch.einsum("ac,bc->ab",norm_max_func_embedding,norm_nl_embedding)
105
+ min_func_nl_similarity = torch.einsum("ac,bc->ab",norm_min_func_embedding,norm_nl_embedding)
106
+
107
+ print(max_func_nl_similarity)
108
+ print(min_func_nl_similarity)
109
+ ```
110
+
111
+ ```python
112
+ tensor([[0.3002]], device='cuda:0', grad_fn=<ViewBackward>)
113
+ tensor([[0.1881]], device='cuda:0', grad_fn=<ViewBackward>)
114
+ ```
115
+
116
+ ## 3. Decoder-only Mode
117
+
118
+ For decoder-only mode, we give an example of **code completion**.
119
+
120
+ ```python
121
+ context = """
122
+ def f(data,file_path):
123
+ # write json data into file_path in python language
124
+ """
125
+ tokens_ids = model.tokenize([context],max_length=512,mode="<decoder-only>")
126
+ source_ids = torch.tensor(tokens_ids).to(device)
127
+ prediction_ids = model.generate(source_ids, decoder_only=True, beam_size=3, max_length=128)
128
+ predictions = model.decode(prediction_ids)
129
+ print(context+predictions[0][0])
130
+ ```
131
+
132
+ ```python
133
+ def f(data,file_path):
134
+ # write json data into file_path in python language
135
+ data = json.dumps(data)
136
+ with open(file_path, 'w') as f:
137
+ f.write(data)
138
+ ```
139
+
140
+ ## 4. Encoder-Decoder Mode
141
+
142
+ For encoder-decoder mode, we give two examples including: **function name prediction**, **API recommendation**, **code summarization**.
143
+
144
+ ### 1) **Function Name Prediction**
145
+
146
+ ```python
147
+ context = """
148
+ def <mask0>(data,file_path):
149
+ data = json.dumps(data)
150
+ with open(file_path, 'w') as f:
151
+ f.write(data)
152
+ """
153
+ tokens_ids = model.tokenize([context],max_length=512,mode="<encoder-decoder>")
154
+ source_ids = torch.tensor(tokens_ids).to(device)
155
+ prediction_ids = model.generate(source_ids, decoder_only=False, beam_size=3, max_length=128)
156
+ predictions = model.decode(prediction_ids)
157
+ print([x.replace("<mask0>","").strip() for x in predictions[0]])
158
+ ```
159
+
160
+ ```python
161
+ ['write_json', 'write_file', 'to_json']
162
+ ```
163
+
164
+ ### 2) API Recommendation
165
+
166
+ ```python
167
+ context = """
168
+ def write_json(data,file_path):
169
+ data = <mask0>(data)
170
+ with open(file_path, 'w') as f:
171
+ f.write(data)
172
+ """
173
+ tokens_ids = model.tokenize([context],max_length=512,mode="<encoder-decoder>")
174
+ source_ids = torch.tensor(tokens_ids).to(device)
175
+ prediction_ids = model.generate(source_ids, decoder_only=False, beam_size=3, max_length=128)
176
+ predictions = model.decode(prediction_ids)
177
+ print([x.replace("<mask0>","").strip() for x in predictions[0]])
178
+ ```
179
+
180
+ ```python
181
+ ['json.dumps', 'json.loads', 'str']
182
+ ```
183
+
184
+ ### 3) Code Summarization
185
+
186
+ ```python
187
+ context = """
188
+ # <mask0>
189
+ def write_json(data,file_path):
190
+ data = json.dumps(data)
191
+ with open(file_path, 'w') as f:
192
+ f.write(data)
193
+ """
194
+ tokens_ids = model.tokenize([context],max_length=512,mode="<encoder-decoder>")
195
+ source_ids = torch.tensor(tokens_ids).to(device)
196
+ prediction_ids = model.generate(source_ids, decoder_only=False, beam_size=3, max_length=128)
197
+ predictions = model.decode(prediction_ids)
198
+ print([x.replace("<mask0>","").strip() for x in predictions[0]])
199
+ ```
200
+
201
+ ```python
202
+ ['Write JSON to file', 'Write json to file', 'Write a json file']
203
+ ```
204
+
205
+
206
+
207
+
208
+ # Reference
209
+ If you use this code or UniXcoder, please consider citing us.
210
+
211
+ <pre><code>@article{guo2022unixcoder,
212
+ title={UniXcoder: Unified Cross-Modal Pre-training for Code Representation},
213
+ author={Guo, Daya and Lu, Shuai and Duan, Nan and Wang, Yanlin and Zhou, Ming and Yin, Jian},
214
+ journal={arXiv preprint arXiv:2203.03850},
215
+ year={2022}
216
+ }</code></pre>
217
+
218
+
219
+