Spaces:
Sleeping
Sleeping
first commit, add gitignore
Browse files- .gitignore +3 -0
- app.py +3 -32
- models/modeling_llamask.py +117 -0
- models/tokenizer_utils.py +83 -0
.gitignore
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/__pycache__
|
| 2 |
+
|
| 3 |
+
.pyc
|
app.py
CHANGED
|
@@ -15,29 +15,7 @@ def respond(
|
|
| 15 |
temperature,
|
| 16 |
top_p,
|
| 17 |
):
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
for val in history:
|
| 21 |
-
if val[0]:
|
| 22 |
-
messages.append({"role": "user", "content": val[0]})
|
| 23 |
-
if val[1]:
|
| 24 |
-
messages.append({"role": "assistant", "content": val[1]})
|
| 25 |
-
|
| 26 |
-
messages.append({"role": "user", "content": message})
|
| 27 |
-
|
| 28 |
-
response = ""
|
| 29 |
-
|
| 30 |
-
for message in client.chat_completion(
|
| 31 |
-
messages,
|
| 32 |
-
max_tokens=max_tokens,
|
| 33 |
-
stream=True,
|
| 34 |
-
temperature=temperature,
|
| 35 |
-
top_p=top_p,
|
| 36 |
-
):
|
| 37 |
-
token = message.choices[0].delta.content
|
| 38 |
-
|
| 39 |
-
response += token
|
| 40 |
-
yield response
|
| 41 |
|
| 42 |
"""
|
| 43 |
For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
|
|
@@ -45,16 +23,9 @@ For information on how to customize the ChatInterface, peruse the gradio docs: h
|
|
| 45 |
demo = gr.ChatInterface(
|
| 46 |
respond,
|
| 47 |
additional_inputs=[
|
| 48 |
-
gr.
|
| 49 |
-
gr.Slider(minimum=1, maximum=
|
| 50 |
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
|
| 51 |
-
gr.Slider(
|
| 52 |
-
minimum=0.1,
|
| 53 |
-
maximum=1.0,
|
| 54 |
-
value=0.95,
|
| 55 |
-
step=0.05,
|
| 56 |
-
label="Top-p (nucleus sampling)",
|
| 57 |
-
),
|
| 58 |
],
|
| 59 |
)
|
| 60 |
|
|
|
|
| 15 |
temperature,
|
| 16 |
top_p,
|
| 17 |
):
|
| 18 |
+
return "test", []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
"""
|
| 21 |
For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
|
|
|
|
| 23 |
demo = gr.ChatInterface(
|
| 24 |
respond,
|
| 25 |
additional_inputs=[
|
| 26 |
+
gr.Markdown("Please enter your message. Add privacy tags (<sensitive>...</sensitive>) around the words you want to hide. Only the most recent message submitted will be taken into account (no history is retained)."),
|
| 27 |
+
gr.Slider(minimum=1, maximum=128, value=32, step=1, label="Max new tokens"),
|
| 28 |
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
],
|
| 30 |
)
|
| 31 |
|
models/modeling_llamask.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
| 5 |
+
# and OPT implementations in this library. It has been modified from its
|
| 6 |
+
# original forms to accommodate minor architectural differences compared
|
| 7 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
| 8 |
+
#
|
| 9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 10 |
+
# you may not use this file except in compliance with the License.
|
| 11 |
+
# You may obtain a copy of the License at
|
| 12 |
+
#
|
| 13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
#
|
| 15 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 18 |
+
# See the License for the specific language governing permissions and
|
| 19 |
+
# limitations under the License.
|
| 20 |
+
|
| 21 |
+
from typing import List, Optional, Tuple, Union
|
| 22 |
+
|
| 23 |
+
import torch
|
| 24 |
+
from torch import nn
|
| 25 |
+
|
| 26 |
+
from transformers.cache_utils import Cache
|
| 27 |
+
from transformers.modeling_outputs import CausalLMOutputWithPast
|
| 28 |
+
from transformers.models.llama import LlamaForCausalLM
|
| 29 |
+
|
| 30 |
+
class LlamaskForCausalLM(LlamaForCausalLM):
|
| 31 |
+
def __init__(self, config):
|
| 32 |
+
super().__init__(config)
|
| 33 |
+
self.special_tokens = nn.Embedding(2, config.hidden_size) # 0 -> mask encoding, 1 -> buffer token
|
| 34 |
+
self.post_init()
|
| 35 |
+
|
| 36 |
+
def generate(
|
| 37 |
+
self,
|
| 38 |
+
input_ids: torch.LongTensor = None,
|
| 39 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 40 |
+
max_tokens: int=32,
|
| 41 |
+
temperature: float=1.0,
|
| 42 |
+
):
|
| 43 |
+
eos_token_tensor = torch.tensor(self.config.eos_token_id, device=input_ids.device)
|
| 44 |
+
for _ in range(max_tokens):
|
| 45 |
+
outputs = self.forward(input_ids=input_ids, attention_mask=attention_mask)
|
| 46 |
+
logits = outputs['logits'][:,-1,:]/temperature
|
| 47 |
+
|
| 48 |
+
probs = torch.nn.functional.softmax(logits, dim=-1)
|
| 49 |
+
next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)
|
| 50 |
+
|
| 51 |
+
batch_size, seq_len, _ = attention_mask.shape
|
| 52 |
+
expanded_mask = torch.zeros(batch_size, seq_len + 1, seq_len + 1, dtype=attention_mask.dtype, device=attention_mask.device)
|
| 53 |
+
|
| 54 |
+
# Step 1: Copy the existing attention mask (top-left block of the expanded mask)
|
| 55 |
+
expanded_mask[:, :seq_len, :seq_len] = attention_mask
|
| 56 |
+
|
| 57 |
+
# Step 2: Copy the last row of the original attention mask into the new row (excluding the last position)
|
| 58 |
+
expanded_mask[:, seq_len, :seq_len] = attention_mask[:, -1, :]
|
| 59 |
+
|
| 60 |
+
# Step 3: Set the diagonal of the new token to attend to all previous tokens by setting the new last element to 1
|
| 61 |
+
expanded_mask[:, seq_len, seq_len] = 1
|
| 62 |
+
|
| 63 |
+
next_tokens = next_tokens[:, None]
|
| 64 |
+
|
| 65 |
+
input_ids = torch.cat([input_ids, next_tokens], dim=-1)
|
| 66 |
+
attention_mask = expanded_mask
|
| 67 |
+
if torch.all(torch.any(next_tokens==eos_token_tensor, dim=1)):
|
| 68 |
+
break
|
| 69 |
+
return input_ids
|
| 70 |
+
|
| 71 |
+
def forward(
|
| 72 |
+
self,
|
| 73 |
+
input_ids: torch.LongTensor = None,
|
| 74 |
+
num_buffer_token: Optional[int] = 0,
|
| 75 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 76 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 77 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
| 78 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 79 |
+
labels: Optional[torch.LongTensor] = None,
|
| 80 |
+
use_cache: Optional[bool] = None,
|
| 81 |
+
output_attentions: Optional[bool] = None,
|
| 82 |
+
output_hidden_states: Optional[bool] = None,
|
| 83 |
+
return_dict: Optional[bool] = None,
|
| 84 |
+
cache_position: Optional[torch.LongTensor] = None
|
| 85 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
| 86 |
+
batch_size = input_ids.shape[0]
|
| 87 |
+
|
| 88 |
+
# print("BEWARE PRIVACY TAG DISABLE")
|
| 89 |
+
# privacy_tag = self.special_tokens(torch.tensor([0], device=input_ids.device))
|
| 90 |
+
# buffer_token = self.special_tokens(torch.tensor([0], device=input_ids.device)).unsqueeze(0)
|
| 91 |
+
|
| 92 |
+
inputs_embeds = self.model.embed_tokens(input_ids)
|
| 93 |
+
# buffer_tokens = buffer_token.repeat(batch_size, num_buffer_token, 1)
|
| 94 |
+
# inputs_embeds = torch.cat([inputs_embeds, buffer_tokens], dim=1)
|
| 95 |
+
|
| 96 |
+
# inputs_embeds[attention_mask[:,-1,:]==0] = inputs_embeds[attention_mask[:,-1,:]==0] + privacy_tag
|
| 97 |
+
|
| 98 |
+
attention_mask = attention_mask.unsqueeze(1)
|
| 99 |
+
attention_mask = attention_mask.to(inputs_embeds.dtype)
|
| 100 |
+
attention_mask = attention_mask.masked_fill(attention_mask == 0, -1e9)
|
| 101 |
+
attention_mask = attention_mask.masked_fill(attention_mask == 1, float(0.0))
|
| 102 |
+
|
| 103 |
+
outputs = super().forward(
|
| 104 |
+
input_ids=None,
|
| 105 |
+
attention_mask=attention_mask,
|
| 106 |
+
position_ids=position_ids,
|
| 107 |
+
past_key_values=past_key_values,
|
| 108 |
+
inputs_embeds=inputs_embeds,
|
| 109 |
+
labels=labels,
|
| 110 |
+
use_cache=use_cache,
|
| 111 |
+
output_attentions=output_attentions,
|
| 112 |
+
output_hidden_states=output_hidden_states,
|
| 113 |
+
return_dict=return_dict,
|
| 114 |
+
cache_position=cache_position,
|
| 115 |
+
)
|
| 116 |
+
return outputs
|
| 117 |
+
|
models/tokenizer_utils.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import List
|
| 2 |
+
|
| 3 |
+
from transformers import AutoTokenizer
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
def prepare_tokenizer(tokenizer: AutoTokenizer, token_beg="<sensitive>", token_end="</sensitive>"):
|
| 7 |
+
"""
|
| 8 |
+
Add privacy special tokens
|
| 9 |
+
"""
|
| 10 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 11 |
+
tokenizer.add_special_tokens({"additional_special_tokens": [token_beg, token_end]})
|
| 12 |
+
tokenizer.sensitive_beg_id = tokenizer.encode(token_beg, add_special_tokens=False)[0]
|
| 13 |
+
tokenizer.sensitive_end_id = tokenizer.encode(token_end, add_special_tokens=False)[0]
|
| 14 |
+
|
| 15 |
+
def generate_custom_mask(tokenizer: AutoTokenizer, prompts: List[str], device='cpu', padding_side='left'):
|
| 16 |
+
"""
|
| 17 |
+
Given a prepared tokenizer (i.e. with privacy special tokens), a list of prompts with privacy special tokens,
|
| 18 |
+
tokenize and generate custom masks for a privacy-compatible transformer.
|
| 19 |
+
"""
|
| 20 |
+
input_ids = tokenizer(prompts)['input_ids']
|
| 21 |
+
return generate_custom_mask_input_ids(tokenizer, input_ids, device=device, padding_side='left')[0]
|
| 22 |
+
|
| 23 |
+
def generate_custom_mask_input_ids(tokenizer: AutoTokenizer, input_ids, device='cpu', padding_side="right"):
|
| 24 |
+
"""
|
| 25 |
+
Given a prepared tokenizer (i.e. with privacy special tokens), a list of prompts with privacy special tokens,
|
| 26 |
+
tokenize and generate custom masks for a privacy-compatible transformer.
|
| 27 |
+
"""
|
| 28 |
+
new_input_ids, new_attention_masks, seq_len_list = [], [], []
|
| 29 |
+
max_len = 0
|
| 30 |
+
batch_size = len(input_ids)
|
| 31 |
+
for input_id in input_ids:
|
| 32 |
+
trigger_privacy = False
|
| 33 |
+
new_input_id = []
|
| 34 |
+
mask_pos_list = []
|
| 35 |
+
idx = 0
|
| 36 |
+
for token_id in input_id:
|
| 37 |
+
if token_id == tokenizer.sensitive_beg_id:
|
| 38 |
+
trigger_privacy = True
|
| 39 |
+
elif token_id == tokenizer.sensitive_end_id:
|
| 40 |
+
trigger_privacy = False
|
| 41 |
+
else:
|
| 42 |
+
new_input_id.append(token_id)
|
| 43 |
+
if trigger_privacy:
|
| 44 |
+
mask_pos_list.append(idx)
|
| 45 |
+
idx += 1
|
| 46 |
+
seq_len = len(new_input_id)
|
| 47 |
+
seq_len_list.append(seq_len)
|
| 48 |
+
|
| 49 |
+
attention_mask = torch.tril(torch.ones((seq_len, seq_len)))
|
| 50 |
+
|
| 51 |
+
for idx in mask_pos_list:
|
| 52 |
+
# The last token can access everything.
|
| 53 |
+
attention_mask[idx+1:-1, idx] = 0
|
| 54 |
+
attention_mask[idx,:idx] = 1
|
| 55 |
+
new_attention_masks.append(attention_mask)
|
| 56 |
+
new_input_ids.append(new_input_id)
|
| 57 |
+
|
| 58 |
+
max_len = max(max_len, seq_len)
|
| 59 |
+
|
| 60 |
+
new_full_attention_mask = torch.zeros((batch_size, max_len))
|
| 61 |
+
for batch, seq_len in enumerate(seq_len_list):
|
| 62 |
+
if padding_side == 'left':
|
| 63 |
+
new_full_attention_mask[batch, max_len-seq_len:] = 1
|
| 64 |
+
else:
|
| 65 |
+
new_full_attention_mask[batch, :seq_len] = 1
|
| 66 |
+
|
| 67 |
+
for idx, (input_ids, attention_mask) in enumerate(zip(new_input_ids, new_attention_masks)):
|
| 68 |
+
current_len = len(input_ids)
|
| 69 |
+
new_attention_mask = torch.zeros((max_len, max_len), dtype=torch.long)
|
| 70 |
+
if padding_side == 'left':
|
| 71 |
+
input_ids = [tokenizer.pad_token_id]*(max_len - current_len) + input_ids
|
| 72 |
+
else:
|
| 73 |
+
input_ids = input_ids + [tokenizer.pad_token_id]*(max_len - current_len)
|
| 74 |
+
|
| 75 |
+
if padding_side == 'left':
|
| 76 |
+
new_attention_mask[max_len-current_len:, max_len-current_len:] = attention_mask
|
| 77 |
+
else:
|
| 78 |
+
new_attention_mask[:current_len,:current_len] = attention_mask
|
| 79 |
+
new_input_ids[idx] = torch.tensor(input_ids).unsqueeze(0)
|
| 80 |
+
new_attention_masks[idx] = new_attention_mask.unsqueeze(0)
|
| 81 |
+
input_id = torch.cat(new_input_ids, dim=0)
|
| 82 |
+
attention_mask = torch.cat(new_attention_masks, dim=0)
|
| 83 |
+
return {'input_ids': input_id.to(device), 'attention_mask': attention_mask.to(device)}, new_full_attention_mask.to(device)
|