
得到知识注入的token embedding后,我们通过构建具有layer norm的self-attention网络,构建基于Transformer的GPT模型,过程如下:
在GPT模型的训练阶段,将文本序列和图像序列拼接作为输入,假设文本序列为w, 生成图像的imaga token表示的离散序列概率如下所示:
最后,模型通过最大化图像部分的负对数似然来训练,得到模型参数的值。
在Baseline方面,我们考虑两种情况:zero-shot learning和标准fine-tuning。我们将40亿参数的中文CogView模型作为zero-shot learner,我们也考虑两个模型规模和ARTIST模型规模相当的模型,分别为开源的DALL-E模型和OFA模型。实验数据如下所示:
从上可以看出,我们的模型在参数量很小的情况(202M)下也能获得较好的图文生成效果。为了衡量注入知识的有效性,我们进一步进行了相关评测,将知识模块移除,实验效果如下:
上述结果可以清楚地看出知识注入的作用。
电商场景效果对比
自然风光场景效果对比上图可以看出ARTIST生成图像质量的优越性。我们进一步比较我们先前公开的模型(看这里)和具有丰富知识的ARTIST模型的效果。在第一个示例“手工古风复原款发钗汉服配饰宫廷发簪珍珠头饰发冠”中,原始生成的结果主要突出了珍珠发冠这个物体。在ARTIST模型中,“古风”等词的知识注入过程使得模型生成结果会更偏向于古代中国的珍珠发簪。| 输入:手工古风复原款发钗汉服配饰宫廷发簪珍珠头饰发冠 | |
| 无知识注入模型 | ARTIST |
![]() ![]() | ![]() ![]() |
| 一颗绿色的花椰菜在生长 | |
| 无知识注入模型 | ARTIST |
![]() ![]() | ![]() ![]() |

# in easynlp/appzoo/text2image_generation/model.py
# init
self.transformer = GPT_knowl(self.config)
# forward
x = inputs['image']
c = inputs['text']
words_emb = inputs['words_emb']
x = x.permute(0, 3, 1, 2).to(memory_format=torch.contiguous_format)
# one step to produce the logits
_, z_indices = self.encode_to_z(x)
c_indices = c
cz_indices = torch.cat((c_indices, a_indices), dim=1)
# make the prediction
logits, _ = self.transformer(cz_indices[:, :-1], words_emb, flag=True)
# cut off conditioning outputs - output i corresponds to p(z_i | z_{<i}, c)
logits = logits[:, c_indices.shape[1]-1:]# in easynlp/appzoo/text2image_generation/data.py
# preprocess word_matrix
words_mat = np.zeros([self.entity_num, self.text_len], dtype=np.int)
if len(lex_id) > 0:
ents = lex_id.split(' ')[:self.entity_num]
pos_s = [int(x) for x in pos_s.split(' ')]
pos_e = [int(x) for x in pos_e.split(' ')]
ent_pos_s = pos_s[token_len:token_len+self.entity_num]
ent_pos_e = pos_e[token_len:token_len+self.entity_num]
for i, ent in enumerate(ents):
words_mat[i, ent_pos_s[i]:ent_pos_e[i]+1] = ent
encoding['words_mat'] = words_mat
# in batch_fn
words_mat = torch.LongTensor([example['words_mat'] for example in batch])
words_emb = self.embed(words_mat)64b4109e34a0c3e7310588c00fc9e157 韩国可爱日系袜子女中筒袜春秋薄款纯棉学院风街头卡通兔子长袜潮 iVBORw0KGgoAAAAN...MAAAAASUVORK5CYII=https://atp-modelzoo-sh.oss-cn-shanghai.aliyuncs.com/release/tutorials/artist_text2image/T2I_train.tsv
https://atp-modelzoo-sh.oss-cn-shanghai.aliyuncs.com/release/tutorials/artist_text2image/T2I_val.tsv
https://atp-modelzoo-sh.oss-cn-shanghai.aliyuncs.com/release/tutorials/artist_text2image/T2I_test.tsv# 下载entity to entity_id映射表
wget wget -P ./tmp https://atp-modelzoo-sh.oss-cn-shanghai.aliyuncs.com/release/tutorials/artist_text2image/entity2id.txt
python examples/text2image_generation/preprocess_data_knowl.py \
--input_file ./tmp/T2I_train.tsv \
--entity_map_file ./tmp/entity2id.txt \
--output_file ./tmp/T2I_knowl_train.tsv
python examples/text2image_generation/preprocess_data_knowl.py \
--input_file ./tmp/T2I_val.tsv \
--entity_map_file ./tmp/entity2id.txt \
--output_file ./tmp/T2I_knowl_val.tsv
python examples/text2image_generation/preprocess_data_knowl.py \
--input_file ./tmp/T2I_test.tsv \
--entity_map_file ./tmp/entity2id.txt \
--output_file ./tmp/T2I_knowl_test.tsv# 下载entity_id与entity_vector的映射表
wget -P ./tmp https://atp-modelzoo-sh.oss-cn-shanghai.aliyuncs.com/release/tutorials/artist_text2image/entity2vec.pt
# finetune
python -m torch.distributed.launch $DISTRIBUTED_ARGS examples/text2image_generation/main_knowl.py \
--mode=train \
--worker_gpu=1 \
--tables=./tmp/T2I_knowl_train.tsv,./tmp/T2I_knowl_val.tsv \
--input_schema=idx:str:1,text:str:1,lex_id:str:1,pos_s:str:1,pos_e:str:1,token_len:str:1,imgbase64:str:1, \
--first_sequence=text \
--second_sequence=imgbase64 \
--checkpoint_dir=./tmp/artist_model_finetune \
--learning_rate=4e-5 \
--epoch_num=2 \
--random_seed=42 \
--logging_steps=100 \
--save_checkpoint_steps=200 \
--sequence_length=288 \
--micro_batch_size=8 \
--app_name=text2image_generation \
--user_defined_parameters='
pretrain_model_name_or_path=alibaba-pai/pai-artist-knowl-base-zh
entity_emb_path=./tmp/entity2vec.pt
size=256
text_len=32
img_len=256
img_vocab_size=16384
'
# predict
python -m torch.distributed.launch $DISTRIBUTED_ARGS examples/text2image_generation/main_knowl.py \
--mode=predict \
--worker_gpu=1 \
--tables=./tmp/T2I_knowl_test.tsv \
--input_schema=idx:str:1,text:str:1,lex_id:str:1,pos_s:str:1,pos_e:str:1,token_len:str:1, \
--first_sequence=text \
--outputs=./tmp/T2I_outputs_knowl.tsv \
--output_schema=idx,text,gen_imgbase64 \
--checkpoint_dir=./tmp/artist_model_finetune \
--sequence_length=288 \
--micro_batch_size=8 \
--app_name=text2image_generation \
--user_defined_parameters='
entity_emb_path=./tmp/entity2vec.pt
size=256
text_len=32
img_len=256
img_vocab_size=16384
max_generated_num=4
'
我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看rubyzip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d
我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co
我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何
我有一个包含模块的模型。我想在模块中覆盖模型的访问器方法。例如:classBlah这显然行不通。有什么想法可以实现吗? 最佳答案 您的代码看起来是正确的。我们正在毫无困难地使用这个确切的模式。如果我没记错的话,Rails使用#method_missing作为属性setter,因此您的模块将优先,阻止ActiveRecord的setter。如果您正在使用ActiveSupport::Concern(参见thisblogpost),那么您的实例方法需要进入一个特殊的模块:classBlah
在MRIRuby中我可以这样做:deftransferinternal_server=self.init_serverpid=forkdointernal_server.runend#Maketheserverprocessrunindependently.Process.detach(pid)internal_client=self.init_client#Dootherstuffwithconnectingtointernal_server...internal_client.post('somedata')ensure#KillserverProcess.kill('KILL',
我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss
我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢
我正在编写一个小脚本来定位aws存储桶中的特定文件,并创建一个临时验证的url以发送给同事。(理想情况下,这将创建类似于在控制台上右键单击存储桶中的文件并复制链接地址的结果)。我研究过回形针,它似乎不符合这个标准,但我可能只是不知道它的全部功能。我尝试了以下方法:defauthenticated_url(file_name,bucket)AWS::S3::S3Object.url_for(file_name,bucket,:secure=>true,:expires=>20*60)end产生这种类型的结果:...-1.amazonaws.com/file_path/file.zip.A
我有一些非常大的模型,我必须将它们迁移到最新版本的Rails。这些模型有相当多的验证(User有大约50个验证)。是否可以将所有这些验证移动到另一个文件中?说app/models/validations/user_validations.rb。如果可以,有人可以提供示例吗? 最佳答案 您可以为此使用关注点:#app/models/validations/user_validations.rbrequire'active_support/concern'moduleUserValidationsextendActiveSupport:
对于Rails模型,是否可以/建议让一个类的成员不持久保存到数据库中?我想将用户最后选择的类型存储在session变量中。由于我无法从我的模型中设置session变量,我想将值存储在一个“虚拟”类成员中,该成员只是将值传递回Controller。你能有这样的类(class)成员吗? 最佳答案 将非持久属性添加到Rails模型就像任何其他Ruby类一样:classUser扩展解释:在Ruby中,所有实例变量都是私有(private)的,不需要在赋值前定义。attr_accessor创建一个setter和getter方法:classUs