file_path
stringlengths
3
280
file_language
stringclasses
66 values
content
stringlengths
1
1.04M
repo_name
stringlengths
5
92
repo_stars
int64
0
154k
repo_description
stringlengths
0
402
repo_primary_language
stringclasses
108 values
developer_username
stringlengths
1
25
developer_name
stringlengths
0
30
developer_company
stringlengths
0
82
streaming/src/runtime_context.h
C/C++ Header
#ifndef RAY_STREAMING_H #define RAY_STREAMING_H #include <string> #include "config/streaming_config.h" #include "status.h" namespace ray { namespace streaming { enum class RuntimeStatus : uint8_t { Init = 0, Running = 1, Interrupted = 2 }; #define RETURN_IF_NOT_OK(STATUS_EXP) \ { \ StreamingStatus state = STATUS_EXP; \ if (StreamingStatus::OK != state) { \ return state; \ } \ } class RuntimeContext { public: RuntimeContext(); virtual ~RuntimeContext(); inline const StreamingConfig &GetConfig() const { return config_; }; void SetConfig(const StreamingConfig &config); void SetConfig(const uint8_t *data, uint32_t buffer_len); inline RuntimeStatus GetRuntimeStatus() { return runtime_status_; } inline void SetRuntimeStatus(RuntimeStatus status) { runtime_status_ = status; } inline void MarkMockTest() { is_mock_test_ = true; } inline bool IsMockTest() { return is_mock_test_; } private: StreamingConfig config_; RuntimeStatus runtime_status_; bool is_mock_test_ = false; }; } // namespace streaming } // namespace ray #endif // RAY_STREAMING_H
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
streaming/src/status.h
C/C++ Header
#ifndef RAY_STREAMING_STATUS_H #define RAY_STREAMING_STATUS_H #include <ostream> #include <sstream> #include <string> namespace ray { namespace streaming { enum class StreamingStatus : uint32_t { OK = 0, ReconstructTimeOut = 1, QueueIdNotFound = 3, ResubscribeFailed = 4, EmptyRingBuffer = 5, FullChannel = 6, NoSuchItem = 7, InitQueueFailed = 8, GetBundleTimeOut = 9, SkipSendEmptyMessage = 10, Interrupted = 11, WaitQueueTimeOut = 12, OutOfMemory = 13, Invalid = 14, UnknownError = 15, TailStatus = 999, MIN = OK, MAX = TailStatus }; static inline std::ostream &operator<<(std::ostream &os, const StreamingStatus &status) { os << static_cast<std::underlying_type<StreamingStatus>::type>(status); return os; } #define RETURN_IF_NOT_OK(STATUS_EXP) \ { \ StreamingStatus state = STATUS_EXP; \ if (StreamingStatus::OK != state) { \ return state; \ } \ } } // namespace streaming } // namespace ray #endif // RAY_STREAMING_STATUS_H
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
streaming/src/test/message_serialization_tests.cc
C++
#include <cstring> #include <string> #include "gtest/gtest.h" #include "message/message.h" #include "message/message_bundle.h" using namespace ray; using namespace ray::streaming; TEST(StreamingSerializationTest, streaming_message_serialization_test) { uint8_t data[] = {9, 1, 3}; StreamingMessagePtr message = std::make_shared<StreamingMessage>(data, 3, 7, StreamingMessageType::Message); uint32_t message_length = message->ClassBytesSize(); uint8_t *bytes = new uint8_t[message_length]; message->ToBytes(bytes); StreamingMessagePtr new_message = StreamingMessage::FromBytes(bytes); EXPECT_EQ(std::memcmp(new_message->RawData(), data, 3), 0); delete[] bytes; } TEST(StreamingSerializationTest, streaming_message_empty_bundle_serialization_test) { for (int i = 0; i < 10; ++i) { StreamingMessageBundle bundle(i, i); uint64_t bundle_size = bundle.ClassBytesSize(); uint8_t *bundle_bytes = new uint8_t[bundle_size]; bundle.ToBytes(bundle_bytes); StreamingMessageBundlePtr bundle_ptr = StreamingMessageBundle::FromBytes(bundle_bytes); EXPECT_EQ(bundle.ClassBytesSize(), bundle_ptr->ClassBytesSize()); EXPECT_EQ(bundle.GetMessageListSize(), bundle_ptr->GetMessageListSize()); EXPECT_EQ(bundle.GetBundleType(), bundle_ptr->GetBundleType()); EXPECT_EQ(bundle.GetLastMessageId(), bundle_ptr->GetLastMessageId()); std::list<StreamingMessagePtr> s_message_list; bundle_ptr->GetMessageList(s_message_list); std::list<StreamingMessagePtr> b_message_list; bundle.GetMessageList(b_message_list); EXPECT_EQ(b_message_list.size(), 0); EXPECT_EQ(s_message_list.size(), 0); delete[] bundle_bytes; } } TEST(StreamingSerializationTest, streaming_message_barrier_bundle_serialization_test) { for (int i = 0; i < 10; ++i) { uint8_t data[] = {1, 2, 3, 4}; uint32_t data_size = 4; uint32_t head_size = sizeof(uint64_t); uint64_t checkpoint_id = 777; std::shared_ptr<uint8_t> ptr(new uint8_t[data_size + head_size], std::default_delete<uint8_t[]>()); // move checkpint_id in head of barrier data std::memcpy(ptr.get(), &checkpoint_id, head_size); std::memcpy(ptr.get() + head_size, data, data_size); StreamingMessagePtr message = std::make_shared<StreamingMessage>( data, head_size + data_size, i, StreamingMessageType::Barrier); std::list<StreamingMessagePtr> message_list; message_list.push_back(message); // message list will be moved to bundle member std::list<StreamingMessagePtr> message_list_cpy(message_list); StreamingMessageBundle bundle(message_list_cpy, i, i, StreamingMessageBundleType::Barrier); uint64_t bundle_size = bundle.ClassBytesSize(); uint8_t *bundle_bytes = new uint8_t[bundle_size]; bundle.ToBytes(bundle_bytes); StreamingMessageBundlePtr bundle_ptr = StreamingMessageBundle::FromBytes(bundle_bytes); EXPECT_TRUE(bundle.ClassBytesSize() == bundle_ptr->ClassBytesSize()); EXPECT_TRUE(bundle.GetMessageListSize() == bundle_ptr->GetMessageListSize()); EXPECT_TRUE(bundle.GetBundleType() == bundle_ptr->GetBundleType()); EXPECT_TRUE(bundle.GetLastMessageId() == bundle_ptr->GetLastMessageId()); std::list<StreamingMessagePtr> s_message_list; bundle_ptr->GetMessageList(s_message_list); EXPECT_TRUE(s_message_list.size() == message_list.size()); auto m_item = message_list.back(); auto s_item = s_message_list.back(); EXPECT_TRUE(s_item->ClassBytesSize() == m_item->ClassBytesSize()); EXPECT_TRUE(s_item->GetMessageType() == m_item->GetMessageType()); EXPECT_TRUE(s_item->GetMessageSeqId() == m_item->GetMessageSeqId()); EXPECT_TRUE(s_item->GetDataSize() == m_item->GetDataSize()); EXPECT_TRUE( std::memcmp(s_item->RawData(), m_item->RawData(), m_item->GetDataSize()) == 0); EXPECT_TRUE(*(s_item.get()) == (*(m_item.get()))); delete[] bundle_bytes; } } TEST(StreamingSerializationTest, streaming_message_bundle_serialization_test) { for (int k = 0; k <= 1000; k++) { std::list<StreamingMessagePtr> message_list; for (int i = 0; i < 100; ++i) { uint8_t *data = new uint8_t[i + 1]; data[0] = i; StreamingMessagePtr message = std::make_shared<StreamingMessage>( data, i + 1, i + 1, StreamingMessageType::Message); message_list.push_back(message); delete[] data; } StreamingMessageBundle messageBundle(message_list, 0, 1, StreamingMessageBundleType::Bundle); size_t message_length = messageBundle.ClassBytesSize(); uint8_t *bytes = new uint8_t[message_length]; messageBundle.ToBytes(bytes); StreamingMessageBundlePtr bundle_ptr = StreamingMessageBundle::FromBytes(bytes); EXPECT_EQ(bundle_ptr->ClassBytesSize(), message_length); std::list<StreamingMessagePtr> s_message_list; bundle_ptr->GetMessageList(s_message_list); EXPECT_TRUE(bundle_ptr->operator==(messageBundle)); StreamingMessageBundleMetaPtr bundle_meta_ptr = StreamingMessageBundleMeta::FromBytes(bytes); EXPECT_EQ(bundle_meta_ptr->GetBundleType(), bundle_ptr->GetBundleType()); EXPECT_EQ(bundle_meta_ptr->GetLastMessageId(), bundle_ptr->GetLastMessageId()); EXPECT_EQ(bundle_meta_ptr->GetMessageBundleTs(), bundle_ptr->GetMessageBundleTs()); EXPECT_EQ(bundle_meta_ptr->GetMessageListSize(), bundle_ptr->GetMessageListSize()); delete[] bytes; } } TEST(StreamingSerializationTest, streaming_message_bundle_equal_test) { std::list<StreamingMessagePtr> message_list; std::list<StreamingMessagePtr> message_list_same; std::list<StreamingMessagePtr> message_list_cpy; for (int i = 0; i < 100; ++i) { uint8_t *data = new uint8_t[i + 1]; for (int j = 0; j < i + 1; ++j) { data[j] = i; } StreamingMessagePtr message = std::make_shared<StreamingMessage>( data, i + 1, i + 1, StreamingMessageType::Message); message_list.push_back(message); message_list_cpy.push_front(message); delete[] data; } for (int i = 0; i < 100; ++i) { uint8_t *data = new uint8_t[i + 1]; for (int j = 0; j < i + 1; ++j) { data[j] = i; } StreamingMessagePtr message = std::make_shared<StreamingMessage>( data, i + 1, i + 1, StreamingMessageType::Message); message_list_same.push_back(message); delete[] data; } StreamingMessageBundle message_bundle(message_list, 0, 1, StreamingMessageBundleType::Bundle); StreamingMessageBundle message_bundle_same(message_list_same, 0, 1, StreamingMessageBundleType::Bundle); StreamingMessageBundle message_bundle_reverse(message_list_cpy, 0, 1, StreamingMessageBundleType::Bundle); EXPECT_TRUE(message_bundle_same == message_bundle); EXPECT_FALSE(message_bundle_reverse == message_bundle); size_t message_length = message_bundle.ClassBytesSize(); uint8_t *bytes = new uint8_t[message_length]; message_bundle.ToBytes(bytes); StreamingMessageBundlePtr bundle_ptr = StreamingMessageBundle::FromBytes(bytes); EXPECT_EQ(bundle_ptr->ClassBytesSize(), message_length); std::list<StreamingMessagePtr> s_message_list; bundle_ptr->GetMessageList(s_message_list); EXPECT_TRUE(bundle_ptr->operator==(message_bundle)); delete[] bytes; } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
streaming/src/test/mock_actor.cc
C++
#define BOOST_BIND_NO_PLACEHOLDERS #include "ray/core_worker/context.h" #include "ray/core_worker/core_worker.h" #include "src/ray/util/test_util.h" #include "data_reader.h" #include "data_writer.h" #include "message/message.h" #include "message/message_bundle.h" #include "queue/queue_client.h" #include "ring_buffer.h" #include "status.h" #include "gtest/gtest.h" using namespace std::placeholders; const uint32_t MESSAGE_BOUND_SIZE = 10000; const uint32_t DEFAULT_STREAMING_MESSAGE_BUFFER_SIZE = 1000; namespace ray { namespace streaming { class StreamingQueueTestSuite { public: StreamingQueueTestSuite(std::shared_ptr<CoreWorker> core_worker, ActorID &peer_actor_id, std::vector<ObjectID> queue_ids, std::vector<ObjectID> rescale_queue_ids) : core_worker_(core_worker), peer_actor_id_(peer_actor_id), queue_ids_(queue_ids), rescale_queue_ids_(rescale_queue_ids) {} virtual void ExecuteTest(std::string test_name) { auto it = test_func_map_.find(test_name); STREAMING_CHECK(it != test_func_map_.end()); current_test_ = test_name; status_ = false; auto func = it->second; executor_thread_ = std::make_shared<std::thread>(func); executor_thread_->detach(); } virtual std::shared_ptr<LocalMemoryBuffer> CheckCurTestStatus() { TestCheckStatusRspMsg msg(current_test_, status_); return msg.ToBytes(); } virtual bool TestDone() { return status_; } virtual ~StreamingQueueTestSuite() {} protected: std::unordered_map<std::string, std::function<void()>> test_func_map_; std::string current_test_; bool status_; std::shared_ptr<std::thread> executor_thread_; std::shared_ptr<CoreWorker> core_worker_; ActorID peer_actor_id_; std::vector<ObjectID> queue_ids_; std::vector<ObjectID> rescale_queue_ids_; }; class StreamingQueueWriterTestSuite : public StreamingQueueTestSuite { public: StreamingQueueWriterTestSuite(std::shared_ptr<CoreWorker> core_worker, ActorID &peer_actor_id, std::vector<ObjectID> queue_ids, std::vector<ObjectID> rescale_queue_ids) : StreamingQueueTestSuite(core_worker, peer_actor_id, queue_ids, rescale_queue_ids) { test_func_map_ = { {"streaming_writer_exactly_once_test", std::bind(&StreamingQueueWriterTestSuite::StreamingWriterExactlyOnceTest, this)}}; } private: void TestWriteMessageToBufferRing(std::shared_ptr<DataWriter> writer_client, std::vector<ray::ObjectID> &q_list) { // const uint8_t temp_data[] = {1, 2, 4, 5}; uint32_t i = 1; while (i <= MESSAGE_BOUND_SIZE) { for (auto &q_id : q_list) { uint64_t buffer_len = (i % DEFAULT_STREAMING_MESSAGE_BUFFER_SIZE); uint8_t *data = new uint8_t[buffer_len]; for (uint32_t j = 0; j < buffer_len; ++j) { data[j] = j % 128; } writer_client->WriteMessageToBufferRing(q_id, data, buffer_len, StreamingMessageType::Message); } ++i; } // Wait a while std::this_thread::sleep_for(std::chrono::milliseconds(5000)); } void StreamingWriterStrategyTest(StreamingConfig &config) { for (auto &queue_id : queue_ids_) { STREAMING_LOG(INFO) << "queue_id: " << queue_id; } std::vector<ActorID> actor_ids(queue_ids_.size(), peer_actor_id_); STREAMING_LOG(INFO) << "writer actor_ids size: " << actor_ids.size() << " actor_id: " << peer_actor_id_; std::shared_ptr<RuntimeContext> runtime_context(new RuntimeContext()); runtime_context->SetConfig(config); std::shared_ptr<DataWriter> streaming_writer_client(new DataWriter(runtime_context)); uint64_t queue_size = 10 * 1000 * 1000; std::vector<uint64_t> channel_seq_id_vec(queue_ids_.size(), 0); streaming_writer_client->Init(queue_ids_, actor_ids, channel_seq_id_vec, std::vector<uint64_t>(queue_ids_.size(), queue_size)); STREAMING_LOG(INFO) << "streaming_writer_client Init done"; streaming_writer_client->Run(); std::thread test_loop_thread( &StreamingQueueWriterTestSuite::TestWriteMessageToBufferRing, this, streaming_writer_client, std::ref(queue_ids_)); // test_loop_thread.detach(); if (test_loop_thread.joinable()) { test_loop_thread.join(); } } void StreamingWriterExactlyOnceTest() { StreamingConfig config; StreamingWriterStrategyTest(config); STREAMING_LOG(INFO) << "StreamingQueueWriterTestSuite::StreamingWriterExactlyOnceTest"; status_ = true; } }; class StreamingQueueReaderTestSuite : public StreamingQueueTestSuite { public: StreamingQueueReaderTestSuite(std::shared_ptr<CoreWorker> core_worker, ActorID peer_actor_id, std::vector<ObjectID> queue_ids, std::vector<ObjectID> rescale_queue_ids) : StreamingQueueTestSuite(core_worker, peer_actor_id, queue_ids, rescale_queue_ids) { test_func_map_ = { {"streaming_writer_exactly_once_test", std::bind(&StreamingQueueReaderTestSuite::StreamingWriterExactlyOnceTest, this)}}; } private: void ReaderLoopForward(std::shared_ptr<DataReader> reader_client, std::shared_ptr<DataWriter> writer_client, std::vector<ray::ObjectID> &queue_id_vec) { uint64_t recevied_message_cnt = 0; std::unordered_map<ray::ObjectID, uint64_t> queue_last_cp_id; for (auto &q_id : queue_id_vec) { queue_last_cp_id[q_id] = 0; } STREAMING_LOG(INFO) << "Start read message bundle"; while (true) { std::shared_ptr<DataBundle> msg; StreamingStatus st = reader_client->GetBundle(100, msg); if (st != StreamingStatus::OK || !msg->data) { STREAMING_LOG(DEBUG) << "read bundle timeout, status = " << (int)st; continue; } STREAMING_CHECK(msg.get() && msg->meta.get()) << "read null pointer message, queue id => " << msg->from.Hex(); if (msg->meta->GetBundleType() == StreamingMessageBundleType::Barrier) { STREAMING_LOG(DEBUG) << "barrier message recevied => " << msg->meta->GetMessageBundleTs(); std::unordered_map<ray::ObjectID, ConsumerChannelInfo> *offset_map; reader_client->GetOffsetInfo(offset_map); for (auto &q_id : queue_id_vec) { reader_client->NotifyConsumedItem((*offset_map)[q_id], (*offset_map)[q_id].current_seq_id); } // writer_client->ClearCheckpoint(msg->last_barrier_id); continue; } else if (msg->meta->GetBundleType() == StreamingMessageBundleType::Empty) { STREAMING_LOG(DEBUG) << "empty message recevied => " << msg->meta->GetMessageBundleTs(); continue; } StreamingMessageBundlePtr bundlePtr; bundlePtr = StreamingMessageBundle::FromBytes(msg->data); std::list<StreamingMessagePtr> message_list; bundlePtr->GetMessageList(message_list); STREAMING_LOG(INFO) << "message size => " << message_list.size() << " from queue id => " << msg->from.Hex() << " last message id => " << msg->meta->GetLastMessageId(); recevied_message_cnt += message_list.size(); for (auto &item : message_list) { uint64_t i = item->GetMessageSeqId(); uint32_t buff_len = i % DEFAULT_STREAMING_MESSAGE_BUFFER_SIZE; if (i > MESSAGE_BOUND_SIZE) break; EXPECT_EQ(buff_len, item->GetDataSize()); uint8_t *compared_data = new uint8_t[buff_len]; for (uint32_t j = 0; j < item->GetDataSize(); ++j) { compared_data[j] = j % 128; } EXPECT_EQ(std::memcmp(compared_data, item->RawData(), item->GetDataSize()), 0); delete[] compared_data; } STREAMING_LOG(DEBUG) << "Received message count => " << recevied_message_cnt; if (recevied_message_cnt == queue_id_vec.size() * MESSAGE_BOUND_SIZE) { STREAMING_LOG(INFO) << "recevied message count => " << recevied_message_cnt << ", break"; break; } } } void StreamingReaderStrategyTest(StreamingConfig &config) { std::vector<ActorID> actor_ids(queue_ids_.size(), peer_actor_id_); STREAMING_LOG(INFO) << "reader actor_ids size: " << actor_ids.size() << " actor_id: " << peer_actor_id_; std::shared_ptr<RuntimeContext> runtime_context(new RuntimeContext()); runtime_context->SetConfig(config); std::shared_ptr<DataReader> reader(new DataReader(runtime_context)); reader->Init(queue_ids_, actor_ids, -1); ReaderLoopForward(reader, nullptr, queue_ids_); STREAMING_LOG(INFO) << "Reader exit"; } void StreamingWriterExactlyOnceTest() { STREAMING_LOG(INFO) << "StreamingQueueReaderTestSuite::StreamingWriterExactlyOnceTest"; StreamingConfig config; StreamingReaderStrategyTest(config); status_ = true; } }; class TestSuiteFactory { public: static std::shared_ptr<StreamingQueueTestSuite> CreateTestSuite( std::shared_ptr<CoreWorker> worker, std::shared_ptr<TestInitMessage> message) { std::shared_ptr<StreamingQueueTestSuite> test_suite = nullptr; std::string suite_name = message->TestSuiteName(); queue::protobuf::StreamingQueueTestRole role = message->Role(); const std::vector<ObjectID> &queue_ids = message->QueueIds(); const std::vector<ObjectID> &rescale_queue_ids = message->RescaleQueueIds(); ActorID peer_actor_id = message->PeerActorId(); if (role == queue::protobuf::StreamingQueueTestRole::WRITER) { if (suite_name == "StreamingWriterTest") { test_suite = std::make_shared<StreamingQueueWriterTestSuite>( worker, peer_actor_id, queue_ids, rescale_queue_ids); } else { STREAMING_CHECK(false) << "unsurported suite_name: " << suite_name; } } else { if (suite_name == "StreamingWriterTest") { test_suite = std::make_shared<StreamingQueueReaderTestSuite>( worker, peer_actor_id, queue_ids, rescale_queue_ids); } else { STREAMING_CHECK(false) << "unsupported suite_name: " << suite_name; } } return test_suite; } }; class StreamingWorker { public: StreamingWorker(const std::string &store_socket, const std::string &raylet_socket, int node_manager_port, const gcs::GcsClientOptions &gcs_options) : test_suite_(nullptr), peer_actor_handle_(nullptr) { worker_ = std::make_shared<CoreWorker>( WorkerType::WORKER, Language::PYTHON, store_socket, raylet_socket, JobID::FromInt(1), gcs_options, "", "127.0.0.1", node_manager_port, std::bind(&StreamingWorker::ExecuteTask, this, _1, _2, _3, _4, _5, _6, _7)); RayFunction reader_async_call_func{ray::Language::PYTHON, {"reader_async_call_func"}}; RayFunction reader_sync_call_func{ray::Language::PYTHON, {"reader_sync_call_func"}}; RayFunction writer_async_call_func{ray::Language::PYTHON, {"writer_async_call_func"}}; RayFunction writer_sync_call_func{ray::Language::PYTHON, {"writer_sync_call_func"}}; reader_client_ = std::make_shared<ReaderClient>(worker_.get(), reader_async_call_func, reader_sync_call_func); writer_client_ = std::make_shared<WriterClient>(worker_.get(), writer_async_call_func, writer_sync_call_func); STREAMING_LOG(INFO) << "StreamingWorker constructor"; } void StartExecutingTasks() { // Start executing tasks. worker_->StartExecutingTasks(); } private: Status ExecuteTask(TaskType task_type, const RayFunction &ray_function, const std::unordered_map<std::string, double> &required_resources, const std::vector<std::shared_ptr<RayObject>> &args, const std::vector<ObjectID> &arg_reference_ids, const std::vector<ObjectID> &return_ids, std::vector<std::shared_ptr<RayObject>> *results) { // Only one arg param used in streaming. STREAMING_CHECK(args.size() >= 1) << "args.size() = " << args.size(); std::vector<std::string> function_descriptor = ray_function.GetFunctionDescriptor(); STREAMING_LOG(INFO) << "StreamingWorker::ExecuteTask " << function_descriptor[0]; std::string func_name = function_descriptor[0]; if (func_name == "init") { std::shared_ptr<LocalMemoryBuffer> local_buffer = std::make_shared<LocalMemoryBuffer>(args[0]->GetData()->Data(), args[0]->GetData()->Size(), true); HandleInitTask(local_buffer); } else if (func_name == "execute_test") { STREAMING_LOG(INFO) << "Test name: " << function_descriptor[1]; test_suite_->ExecuteTest(function_descriptor[1]); } else if (func_name == "check_current_test_status") { results->push_back( std::make_shared<RayObject>(test_suite_->CheckCurTestStatus(), nullptr)); } else if (func_name == "reader_sync_call_func") { if (test_suite_->TestDone()) { STREAMING_LOG(WARNING) << "Test has done!!"; return Status::OK(); } std::shared_ptr<LocalMemoryBuffer> local_buffer = std::make_shared<LocalMemoryBuffer>(args[1]->GetData()->Data(), args[1]->GetData()->Size(), true); auto result_buffer = reader_client_->OnReaderMessageSync(local_buffer); results->push_back(std::make_shared<RayObject>(result_buffer, nullptr)); } else if (func_name == "reader_async_call_func") { if (test_suite_->TestDone()) { STREAMING_LOG(WARNING) << "Test has done!!"; return Status::OK(); } std::shared_ptr<LocalMemoryBuffer> local_buffer = std::make_shared<LocalMemoryBuffer>(args[1]->GetData()->Data(), args[1]->GetData()->Size(), true); reader_client_->OnReaderMessage(local_buffer); } else if (func_name == "writer_sync_call_func") { if (test_suite_->TestDone()) { STREAMING_LOG(WARNING) << "Test has done!!"; return Status::OK(); } std::shared_ptr<LocalMemoryBuffer> local_buffer = std::make_shared<LocalMemoryBuffer>(args[1]->GetData()->Data(), args[1]->GetData()->Size(), true); auto result_buffer = writer_client_->OnWriterMessageSync(local_buffer); results->push_back(std::make_shared<RayObject>(result_buffer, nullptr)); } else if (func_name == "writer_async_call_func") { if (test_suite_->TestDone()) { STREAMING_LOG(WARNING) << "Test has done!!"; return Status::OK(); } std::shared_ptr<LocalMemoryBuffer> local_buffer = std::make_shared<LocalMemoryBuffer>(args[1]->GetData()->Data(), args[1]->GetData()->Size(), true); writer_client_->OnWriterMessage(local_buffer); } else { STREAMING_LOG(WARNING) << "Invalid function name " << func_name; } return Status::OK(); } private: void HandleInitTask(std::shared_ptr<LocalMemoryBuffer> buffer) { uint8_t *bytes = buffer->Data(); uint8_t *p_cur = bytes; uint32_t *magic_num = (uint32_t *)p_cur; STREAMING_CHECK(*magic_num == Message::MagicNum); p_cur += sizeof(Message::MagicNum); queue::protobuf::StreamingQueueMessageType *type = (queue::protobuf::StreamingQueueMessageType *)p_cur; STREAMING_CHECK( *type == queue::protobuf::StreamingQueueMessageType::StreamingQueueTestInitMsgType); std::shared_ptr<TestInitMessage> message = TestInitMessage::FromBytes(bytes); STREAMING_LOG(INFO) << "Init message: " << message->ToString(); std::string actor_handle_serialized = message->ActorHandleSerialized(); worker_->DeserializeAndRegisterActorHandle(actor_handle_serialized); std::shared_ptr<ActorHandle> actor_handle(new ActorHandle(actor_handle_serialized)); STREAMING_CHECK(actor_handle != nullptr); STREAMING_LOG(INFO) << " actor id from handle: " << actor_handle->GetActorID(); ; // STREAMING_LOG(INFO) << "actor_handle_serialized: " << actor_handle_serialized; // peer_actor_handle_ = // std::make_shared<ActorHandle>(actor_handle_serialized); STREAMING_LOG(INFO) << "HandleInitTask queues:"; for (auto qid : message->QueueIds()) { STREAMING_LOG(INFO) << "queue: " << qid; } for (auto qid : message->RescaleQueueIds()) { STREAMING_LOG(INFO) << "rescale queue: " << qid; } test_suite_ = TestSuiteFactory::CreateTestSuite(worker_, message); STREAMING_CHECK(test_suite_ != nullptr); } private: std::shared_ptr<CoreWorker> worker_; std::shared_ptr<ReaderClient> reader_client_; std::shared_ptr<WriterClient> writer_client_; std::shared_ptr<std::thread> test_thread_; std::shared_ptr<StreamingQueueTestSuite> test_suite_; std::shared_ptr<ActorHandle> peer_actor_handle_; }; } // namespace streaming } // namespace ray int main(int argc, char **argv) { RAY_CHECK(argc == 4); auto store_socket = std::string(argv[1]); auto raylet_socket = std::string(argv[2]); auto node_manager_port = std::stoi(std::string(argv[3])); ray::gcs::GcsClientOptions gcs_options("127.0.0.1", 6379, ""); ray::streaming::StreamingWorker worker(store_socket, raylet_socket, node_manager_port, gcs_options); worker.StartExecutingTasks(); return 0; }
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
streaming/src/test/mock_transfer_tests.cc
C++
#include "data_reader.h" #include "data_writer.h" #include "gtest/gtest.h" using namespace ray; using namespace ray::streaming; TEST(StreamingMockTransfer, mock_produce_consume) { std::shared_ptr<Config> transfer_config; ObjectID channel_id = ObjectID::FromRandom(); ProducerChannelInfo producer_channel_info; producer_channel_info.channel_id = channel_id; producer_channel_info.current_seq_id = 0; MockProducer producer(transfer_config, producer_channel_info); ConsumerChannelInfo consumer_channel_info; consumer_channel_info.channel_id = channel_id; MockConsumer consumer(transfer_config, consumer_channel_info); producer.CreateTransferChannel(); uint8_t data[3] = {1, 2, 3}; producer.ProduceItemToChannel(data, 3); uint8_t *data_consumed; uint32_t data_size_consumed; uint64_t data_seq_id; consumer.ConsumeItemFromChannel(data_seq_id, data_consumed, data_size_consumed, -1); EXPECT_EQ(data_size_consumed, 3); EXPECT_EQ(data_seq_id, 1); EXPECT_EQ(std::memcmp(data_consumed, data, 3), 0); consumer.NotifyChannelConsumed(1); auto status = consumer.ConsumeItemFromChannel(data_seq_id, data_consumed, data_size_consumed, -1); EXPECT_EQ(status, StreamingStatus::NoSuchItem); } class StreamingTransferTest : public ::testing::Test { public: StreamingTransferTest() { std::shared_ptr<RuntimeContext> runtime_context(new RuntimeContext()); runtime_context->MarkMockTest(); writer = std::make_shared<DataWriter>(runtime_context); reader = std::make_shared<DataReader>(runtime_context); } virtual ~StreamingTransferTest() = default; void InitTransfer(int channel_num = 1) { for (int i = 0; i < channel_num; ++i) { queue_vec.push_back(ObjectID::FromRandom()); } std::vector<uint64_t> channel_id_vec(queue_vec.size(), 0); std::vector<uint64_t> queue_size_vec(queue_vec.size(), 10000); // actor ids are not used in this test, so we can just use Nil. std::vector<ActorID> actor_id_vec(queue_vec.size(), ActorID::NilFromJob(JobID::FromInt(0))); writer->Init(queue_vec, actor_id_vec, channel_id_vec, queue_size_vec); reader->Init(queue_vec, actor_id_vec, channel_id_vec, queue_size_vec, -1); } void DestroyTransfer() { writer.reset(); reader.reset(); } protected: std::shared_ptr<DataWriter> writer; std::shared_ptr<DataReader> reader; std::vector<ObjectID> queue_vec; }; TEST_F(StreamingTransferTest, exchange_single_channel_test) { InitTransfer(); writer->Run(); uint8_t data[4] = {1, 2, 3, 0xff}; uint32_t data_size = 4; writer->WriteMessageToBufferRing(queue_vec[0], data, data_size); std::shared_ptr<DataBundle> msg; reader->GetBundle(5000, msg); StreamingMessageBundlePtr bundle_ptr = StreamingMessageBundle::FromBytes(msg->data); auto &message_list = bundle_ptr->GetMessageList(); auto &message = message_list.front(); EXPECT_EQ(std::memcmp(message->RawData(), data, data_size), 0); } TEST_F(StreamingTransferTest, exchange_multichannel_test) { int channel_num = 4; InitTransfer(4); writer->Run(); for (int i = 0; i < channel_num; ++i) { uint8_t data[4] = {1, 2, 3, (uint8_t)i}; uint32_t data_size = 4; writer->WriteMessageToBufferRing(queue_vec[i], data, data_size); std::shared_ptr<DataBundle> msg; reader->GetBundle(5000, msg); EXPECT_EQ(msg->from, queue_vec[i]); StreamingMessageBundlePtr bundle_ptr = StreamingMessageBundle::FromBytes(msg->data); auto &message_list = bundle_ptr->GetMessageList(); auto &message = message_list.front(); EXPECT_EQ(std::memcmp(message->RawData(), data, data_size), 0); } } TEST_F(StreamingTransferTest, exchange_consumed_test) { InitTransfer(); writer->Run(); uint32_t data_size = 8196; std::shared_ptr<uint8_t> data(new uint8_t[data_size]); auto func = [data, data_size](int index) { std::fill_n(data.get(), data_size, index); }; size_t num = 10000; std::thread write_thread([this, data, data_size, &func, num]() { for (size_t i = 0; i < num; ++i) { func(i); writer->WriteMessageToBufferRing(queue_vec[0], data.get(), data_size); } }); std::list<StreamingMessagePtr> read_message_list; while (read_message_list.size() < num) { std::shared_ptr<DataBundle> msg; reader->GetBundle(5000, msg); StreamingMessageBundlePtr bundle_ptr = StreamingMessageBundle::FromBytes(msg->data); auto &message_list = bundle_ptr->GetMessageList(); std::copy(message_list.begin(), message_list.end(), std::back_inserter(read_message_list)); } int index = 0; for (auto &message : read_message_list) { func(index++); EXPECT_EQ(std::memcmp(message->RawData(), data.get(), data_size), 0); } write_thread.join(); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
streaming/src/test/queue_tests_base.h
C/C++ Header
namespace ray { namespace streaming { ray::ObjectID RandomObjectID() { return ObjectID::FromRandom(); } static void flushall_redis(void) { redisContext *context = redisConnect("127.0.0.1", 6379); freeReplyObject(redisCommand(context, "FLUSHALL")); freeReplyObject(redisCommand(context, "SET NumRedisShards 1")); freeReplyObject(redisCommand(context, "LPUSH RedisShards 127.0.0.1:6380")); redisFree(context); } /// Base class for real-world tests with streaming queue class StreamingQueueTestBase : public ::testing::TestWithParam<uint64_t> { public: StreamingQueueTestBase(int num_nodes, std::string raylet_exe, std::string store_exe, int port, std::string actor_exe) : gcs_options_("127.0.0.1", 6379, ""), raylet_executable_(raylet_exe), store_executable_(store_exe), actor_executable_(actor_exe), node_manager_port_(port) { // flush redis first. flushall_redis(); RAY_CHECK(num_nodes >= 0); if (num_nodes > 0) { raylet_socket_names_.resize(num_nodes); raylet_store_socket_names_.resize(num_nodes); } // start plasma store. for (auto &store_socket : raylet_store_socket_names_) { store_socket = StartStore(); } // start raylet on each node. Assign each node with different resources so that // a task can be scheduled to the desired node. for (int i = 0; i < num_nodes; i++) { raylet_socket_names_[i] = StartRaylet(raylet_store_socket_names_[i], "127.0.0.1", node_manager_port_ + i, "127.0.0.1", "\"CPU,4.0,resource" + std::to_string(i) + ",10\""); } } ~StreamingQueueTestBase() { STREAMING_LOG(INFO) << "Stop raylet store and actors"; for (const auto &raylet_socket : raylet_socket_names_) { StopRaylet(raylet_socket); } for (const auto &store_socket : raylet_store_socket_names_) { StopStore(store_socket); } } JobID NextJobId() const { static uint32_t job_counter = 1; return JobID::FromInt(job_counter++); } std::string StartStore() { std::string store_socket_name = "/tmp/store" + RandomObjectID().Hex(); std::string store_pid = store_socket_name + ".pid"; std::string plasma_command = store_executable_ + " -m 10000000 -s " + store_socket_name + " 1> /dev/null 2> /dev/null & echo $! > " + store_pid; RAY_LOG(DEBUG) << plasma_command; RAY_CHECK(system(plasma_command.c_str()) == 0); usleep(200 * 1000); return store_socket_name; } void StopStore(std::string store_socket_name) { std::string store_pid = store_socket_name + ".pid"; std::string kill_9 = "kill -9 `cat " + store_pid + "`"; RAY_LOG(DEBUG) << kill_9; ASSERT_EQ(system(kill_9.c_str()), 0); ASSERT_EQ(system(("rm -rf " + store_socket_name).c_str()), 0); ASSERT_EQ(system(("rm -rf " + store_socket_name + ".pid").c_str()), 0); } std::string StartRaylet(std::string store_socket_name, std::string node_ip_address, int port, std::string redis_address, std::string resource) { std::string raylet_socket_name = "/tmp/raylet" + RandomObjectID().Hex(); std::string ray_start_cmd = raylet_executable_; ray_start_cmd.append(" --raylet_socket_name=" + raylet_socket_name) .append(" --store_socket_name=" + store_socket_name) .append(" --object_manager_port=0 --node_manager_port=" + std::to_string(port)) .append(" --node_ip_address=" + node_ip_address) .append(" --redis_address=" + redis_address) .append(" --redis_port=6379") .append(" --num_initial_workers=1") .append(" --maximum_startup_concurrency=10") .append(" --static_resource_list=" + resource) .append(" --python_worker_command=\"" + actor_executable_ + " " + store_socket_name + " " + raylet_socket_name + " " + std::to_string(port) + "\"") .append(" --config_list=initial_reconstruction_timeout_milliseconds,2000") .append(" & echo $! > " + raylet_socket_name + ".pid"); RAY_LOG(DEBUG) << "Ray Start command: " << ray_start_cmd; RAY_CHECK(system(ray_start_cmd.c_str()) == 0); usleep(200 * 1000); return raylet_socket_name; } void StopRaylet(std::string raylet_socket_name) { std::string raylet_pid = raylet_socket_name + ".pid"; std::string kill_9 = "kill -9 `cat " + raylet_pid + "`"; RAY_LOG(DEBUG) << kill_9; ASSERT_TRUE(system(kill_9.c_str()) == 0); ASSERT_TRUE(system(("rm -rf " + raylet_socket_name).c_str()) == 0); ASSERT_TRUE(system(("rm -rf " + raylet_socket_name + ".pid").c_str()) == 0); } void InitWorker(CoreWorker &driver, ActorID &self_actor_id, ActorID &peer_actor_id, const queue::protobuf::StreamingQueueTestRole role, const std::vector<ObjectID> &queue_ids, const std::vector<ObjectID> &rescale_queue_ids, std::string suite_name, std::string test_name, uint64_t param) { std::string forked_serialized_str; Status st = driver.SerializeActorHandle(peer_actor_id, &forked_serialized_str); STREAMING_CHECK(st.ok()); STREAMING_LOG(INFO) << "forked_serialized_str: " << forked_serialized_str; TestInitMessage msg(role, self_actor_id, peer_actor_id, forked_serialized_str, queue_ids, rescale_queue_ids, suite_name, test_name, param); std::vector<TaskArg> args; args.emplace_back( TaskArg::PassByValue(std::make_shared<RayObject>(msg.ToBytes(), nullptr, true))); std::unordered_map<std::string, double> resources; TaskOptions options{0, true, resources}; std::vector<ObjectID> return_ids; RayFunction func{ray::Language::PYTHON, {"init"}}; RAY_CHECK_OK(driver.SubmitActorTask(self_actor_id, func, args, options, &return_ids)); } void SubmitTestToActor(CoreWorker &driver, ActorID &actor_id, const std::string test) { uint8_t data[8]; auto buffer = std::make_shared<LocalMemoryBuffer>(data, 8, true); std::vector<TaskArg> args; args.emplace_back( TaskArg::PassByValue(std::make_shared<RayObject>(buffer, nullptr, true))); std::unordered_map<std::string, double> resources; TaskOptions options{0, true, resources}; std::vector<ObjectID> return_ids; RayFunction func{ray::Language::PYTHON, {"execute_test", test}}; RAY_CHECK_OK(driver.SubmitActorTask(actor_id, func, args, options, &return_ids)); } bool CheckCurTest(CoreWorker &driver, ActorID &actor_id, const std::string test_name) { uint8_t data[8]; auto buffer = std::make_shared<LocalMemoryBuffer>(data, 8, true); std::vector<TaskArg> args; args.emplace_back( TaskArg::PassByValue(std::make_shared<RayObject>(buffer, nullptr, true))); std::unordered_map<std::string, double> resources; TaskOptions options{1, true, resources}; std::vector<ObjectID> return_ids; RayFunction func{ray::Language::PYTHON, {"check_current_test_status"}}; RAY_CHECK_OK(driver.SubmitActorTask(actor_id, func, args, options, &return_ids)); std::vector<bool> wait_results; std::vector<std::shared_ptr<RayObject>> results; Status wait_st = driver.Wait(return_ids, 1, 5 * 1000, &wait_results); if (!wait_st.ok()) { STREAMING_LOG(ERROR) << "Wait fail."; return false; } STREAMING_CHECK(wait_results.size() >= 1); if (!wait_results[0]) { STREAMING_LOG(WARNING) << "Wait direct call fail."; return false; } Status get_st = driver.Get(return_ids, -1, &results); if (!get_st.ok()) { STREAMING_LOG(ERROR) << "Get fail."; return false; } STREAMING_CHECK(results.size() >= 1); if (results[0]->IsException()) { STREAMING_LOG(INFO) << "peer actor may has exceptions."; return false; } STREAMING_CHECK(results[0]->HasData()); STREAMING_LOG(DEBUG) << "SendForResult result[0] DataSize: " << results[0]->GetSize(); const std::shared_ptr<ray::Buffer> result_buffer = results[0]->GetData(); std::shared_ptr<LocalMemoryBuffer> return_buffer = std::make_shared<LocalMemoryBuffer>(result_buffer->Data(), result_buffer->Size(), true); uint8_t *bytes = result_buffer->Data(); uint8_t *p_cur = bytes; uint32_t *magic_num = (uint32_t *)p_cur; STREAMING_CHECK(*magic_num == Message::MagicNum); p_cur += sizeof(Message::MagicNum); queue::protobuf::StreamingQueueMessageType *type = (queue::protobuf::StreamingQueueMessageType *)p_cur; STREAMING_CHECK(*type == queue::protobuf::StreamingQueueMessageType:: StreamingQueueTestCheckStatusRspMsgType); std::shared_ptr<TestCheckStatusRspMsg> message = TestCheckStatusRspMsg::FromBytes(bytes); STREAMING_CHECK(message->TestName() == test_name); return message->Status(); } ActorID CreateActorHelper(CoreWorker &worker, const std::unordered_map<std::string, double> &resources, bool is_direct_call, uint64_t max_reconstructions) { std::unique_ptr<ActorHandle> actor_handle; // Test creating actor. uint8_t array[] = {1, 2, 3}; auto buffer = std::make_shared<LocalMemoryBuffer>(array, sizeof(array)); RayFunction func{ray::Language::PYTHON, {"actor creation task"}}; std::vector<TaskArg> args; args.emplace_back(TaskArg::PassByValue(std::make_shared<RayObject>(buffer, nullptr))); ActorCreationOptions actor_options{ max_reconstructions, is_direct_call, /*max_concurrency*/ 1, resources, resources, {}, /*is_detached*/ false, /*is_asyncio*/ false}; // Create an actor. ActorID actor_id; RAY_CHECK_OK(worker.CreateActor(func, args, actor_options, &actor_id)); return actor_id; } void SubmitTest(uint32_t queue_num, std::string suite_name, std::string test_name, uint64_t timeout_ms) { std::vector<ray::ObjectID> queue_id_vec; std::vector<ray::ObjectID> rescale_queue_id_vec; for (uint32_t i = 0; i < queue_num; ++i) { ObjectID queue_id = ray::ObjectID::FromRandom(); queue_id_vec.emplace_back(queue_id); } // One scale id ObjectID rescale_queue_id = ray::ObjectID::FromRandom(); rescale_queue_id_vec.emplace_back(rescale_queue_id); std::vector<uint64_t> channel_seq_id_vec(queue_num, 0); for (size_t i = 0; i < queue_id_vec.size(); ++i) { STREAMING_LOG(INFO) << " qid hex => " << queue_id_vec[i].Hex(); } for (auto &qid : rescale_queue_id_vec) { STREAMING_LOG(INFO) << " rescale qid hex => " << qid.Hex(); } STREAMING_LOG(INFO) << "Sub process: writer."; CoreWorker driver(WorkerType::DRIVER, Language::PYTHON, raylet_store_socket_names_[0], raylet_socket_names_[0], NextJobId(), gcs_options_, "", "127.0.0.1", node_manager_port_, nullptr); // Create writer and reader actors std::unordered_map<std::string, double> resources; auto actor_id_writer = CreateActorHelper(driver, resources, true, 0); auto actor_id_reader = CreateActorHelper(driver, resources, true, 0); InitWorker(driver, actor_id_writer, actor_id_reader, queue::protobuf::StreamingQueueTestRole::WRITER, queue_id_vec, rescale_queue_id_vec, suite_name, test_name, GetParam()); InitWorker(driver, actor_id_reader, actor_id_writer, queue::protobuf::StreamingQueueTestRole::READER, queue_id_vec, rescale_queue_id_vec, suite_name, test_name, GetParam()); std::this_thread::sleep_for(std::chrono::milliseconds(2000)); SubmitTestToActor(driver, actor_id_writer, test_name); SubmitTestToActor(driver, actor_id_reader, test_name); uint64_t slept_time_ms = 0; while (slept_time_ms < timeout_ms) { std::this_thread::sleep_for(std::chrono::milliseconds(5 * 1000)); STREAMING_LOG(INFO) << "Check test status."; if (CheckCurTest(driver, actor_id_writer, test_name) && CheckCurTest(driver, actor_id_reader, test_name)) { STREAMING_LOG(INFO) << "Test Success, Exit."; return; } slept_time_ms += 5 * 1000; } EXPECT_TRUE(false); STREAMING_LOG(INFO) << "Test Timeout, Exit."; } void SetUp() {} void TearDown() {} protected: std::vector<std::string> raylet_socket_names_; std::vector<std::string> raylet_store_socket_names_; gcs::GcsClientOptions gcs_options_; std::string raylet_executable_; std::string store_executable_; std::string actor_executable_; int node_manager_port_; }; } // namespace streaming } // namespace ray
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
streaming/src/test/ring_buffer_tests.cc
C++
#include "gtest/gtest.h" #include "ray/util/logging.h" #include <unistd.h> #include <iostream> #include <set> #include <thread> #include "message/message.h" #include "ring_buffer.h" using namespace ray; using namespace ray::streaming; size_t data_n = 1000000; TEST(StreamingRingBufferTest, streaming_message_ring_buffer_test) { for (int k = 0; k < 10000; ++k) { StreamingRingBuffer ring_buffer(3, StreamingRingBufferType::SPSC_LOCK); for (int i = 0; i < 5; ++i) { uint8_t data[] = {1, 1, 3}; data[0] = i; StreamingMessagePtr message = std::make_shared<StreamingMessage>(data, 3, i, StreamingMessageType::Message); EXPECT_EQ(ring_buffer.Push(message), true); size_t ith = i >= 3 ? 3 : (i + 1); EXPECT_EQ(ring_buffer.Size(), ith); } int th = 2; while (!ring_buffer.IsEmpty()) { StreamingMessagePtr message_ptr = ring_buffer.Front(); ring_buffer.Pop(); EXPECT_EQ(message_ptr->GetDataSize(), 3); EXPECT_EQ(*(message_ptr->RawData()), th++); } } } TEST(StreamingRingBufferTest, spsc_test) { size_t m_num = 1000; StreamingRingBuffer ring_buffer(m_num, StreamingRingBufferType::SPSC); std::thread thread([&ring_buffer]() { for (size_t j = 0; j < data_n; ++j) { StreamingMessagePtr message = std::make_shared<StreamingMessage>( reinterpret_cast<uint8_t *>(&j), sizeof(size_t), j, StreamingMessageType::Message); while (ring_buffer.IsFull()) { } ring_buffer.Push(message); } }); size_t count = 0; while (count < data_n) { while (ring_buffer.IsEmpty()) { } auto &msg = ring_buffer.Front(); EXPECT_EQ(std::memcmp(msg->RawData(), &count, sizeof(size_t)), 0); ring_buffer.Pop(); count++; } thread.join(); EXPECT_EQ(count, data_n); } TEST(StreamingRingBufferTest, mutex_test) { size_t m_num = data_n; StreamingRingBuffer ring_buffer(m_num, StreamingRingBufferType::SPSC_LOCK); std::thread thread([&ring_buffer]() { for (size_t j = 0; j < data_n; ++j) { StreamingMessagePtr message = std::make_shared<StreamingMessage>( reinterpret_cast<uint8_t *>(&j), sizeof(size_t), j, StreamingMessageType::Message); while (ring_buffer.IsFull()) { } ring_buffer.Push(message); } }); size_t count = 0; while (count < data_n) { while (ring_buffer.IsEmpty()) { } auto msg = ring_buffer.Front(); EXPECT_EQ(std::memcmp(msg->RawData(), &count, sizeof(size_t)), 0); ring_buffer.Pop(); count++; } thread.join(); EXPECT_EQ(count, data_n); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
streaming/src/test/run_streaming_queue_test.sh
Shell
#!/usr/bin/env bash # Run all streaming c++ tests using streaming queue, instead of plasma queue # This needs to be run in the root directory. # Try to find an unused port for raylet to use. PORTS="2000 2001 2002 2003 2004 2005 2006 2007 2008 2009" RAYLET_PORT=0 for port in $PORTS; do nc -z localhost $port if [[ $? != 0 ]]; then RAYLET_PORT=$port break fi done if [[ $RAYLET_PORT == 0 ]]; then echo "WARNING: Could not find unused port for raylet to use. Exiting without running tests." exit fi # Cause the script to exit if a single command fails. set -e set -x # Get the directory in which this script is executing. SCRIPT_DIR="`dirname \"$0\"`" # Get the directory in which this script is executing. SCRIPT_DIR="`dirname \"$0\"`" RAY_ROOT="$SCRIPT_DIR/../../.." # Makes $RAY_ROOT an absolute path. RAY_ROOT="`( cd \"$RAY_ROOT\" && pwd )`" if [ -z "$RAY_ROOT" ] ; then exit 1 fi bazel build "//:core_worker_test" "//:mock_worker" "//:raylet" "//:libray_redis_module.so" "@plasma//:plasma_store_server" bazel build //streaming:streaming_test_worker bazel build //streaming:streaming_queue_tests # Ensure we're in the right directory. if [ ! -d "$RAY_ROOT/python" ]; then echo "Unable to find root Ray directory. Has this script moved?" exit 1 fi REDIS_MODULE="./bazel-bin/libray_redis_module.so" LOAD_MODULE_ARGS="--loadmodule ${REDIS_MODULE}" STORE_EXEC="./bazel-bin/external/plasma/plasma_store_server" RAYLET_EXEC="./bazel-bin/raylet" STREAMING_TEST_WORKER_EXEC="./bazel-bin/streaming/streaming_test_worker" # Allow cleanup commands to fail. bazel run //:redis-cli -- -p 6379 shutdown || true sleep 1s bazel run //:redis-cli -- -p 6380 shutdown || true sleep 1s bazel run //:redis-server -- --loglevel warning ${LOAD_MODULE_ARGS} --port 6379 & sleep 2s bazel run //:redis-server -- --loglevel warning ${LOAD_MODULE_ARGS} --port 6380 & sleep 2s # Run tests. ./bazel-bin/streaming/streaming_queue_tests $STORE_EXEC $RAYLET_EXEC $RAYLET_PORT $STREAMING_TEST_WORKER_EXEC sleep 1s bazel run //:redis-cli -- -p 6379 shutdown bazel run //:redis-cli -- -p 6380 shutdown sleep 1s
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
streaming/src/test/streaming_queue_tests.cc
C++
#define BOOST_BIND_NO_PLACEHOLDERS #include <unistd.h> #include "gtest/gtest.h" #include "queue/queue_client.h" #include "ray/core_worker/core_worker.h" #include "data_reader.h" #include "data_writer.h" #include "message/message.h" #include "message/message_bundle.h" #include "ring_buffer.h" #include "queue_tests_base.h" using namespace std::placeholders; namespace ray { namespace streaming { static std::string store_executable; static std::string raylet_executable; static std::string actor_executable; static int node_manager_port; class StreamingWriterTest : public StreamingQueueTestBase { public: StreamingWriterTest() : StreamingQueueTestBase(1, raylet_executable, store_executable, node_manager_port, actor_executable) {} }; class StreamingExactlySameTest : public StreamingQueueTestBase { public: StreamingExactlySameTest() : StreamingQueueTestBase(1, raylet_executable, store_executable, node_manager_port, actor_executable) {} }; TEST_P(StreamingWriterTest, streaming_writer_exactly_once_test) { STREAMING_LOG(INFO) << "StreamingWriterTest.streaming_writer_exactly_once_test"; uint32_t queue_num = 1; STREAMING_LOG(INFO) << "Streaming Strategy => EXACTLY ONCE"; SubmitTest(queue_num, "StreamingWriterTest", "streaming_writer_exactly_once_test", 60 * 1000); } INSTANTIATE_TEST_CASE_P(StreamingTest, StreamingWriterTest, testing::Values(0)); INSTANTIATE_TEST_CASE_P(StreamingTest, StreamingExactlySameTest, testing::Values(0, 1, 5, 9)); } // namespace streaming } // namespace ray int main(int argc, char **argv) { // set_streaming_log_config("streaming_writer_test", StreamingLogLevel::INFO, 0); ::testing::InitGoogleTest(&argc, argv); RAY_CHECK(argc == 5); ray::streaming::store_executable = std::string(argv[1]); ray::streaming::raylet_executable = std::string(argv[2]); ray::streaming::node_manager_port = std::stoi(std::string(argv[3])); ray::streaming::actor_executable = std::string(argv[4]); return RUN_ALL_TESTS(); }
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
streaming/src/test/streaming_util_tests.cc
C++
#include "gtest/gtest.h" #include "util/streaming_util.h" using namespace ray; using namespace ray::streaming; TEST(StreamingUtilTest, test_Byte2hex) { const uint8_t data[2] = {0x11, 0x07}; EXPECT_TRUE(Util::Byte2hex(data, 2) == "1107"); EXPECT_TRUE(Util::Byte2hex(data, 2) != "1108"); } TEST(StreamingUtilTest, test_Hex2str) { const uint8_t data[2] = {0x11, 0x07}; EXPECT_TRUE(std::memcmp(Util::Hexqid2str("1107").c_str(), data, 2) == 0); const uint8_t data2[2] = {0x10, 0x0f}; EXPECT_TRUE(std::memcmp(Util::Hexqid2str("100f").c_str(), data2, 2) == 0); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
streaming/src/util/streaming_logging.cc
C++
#include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "streaming_logging.h" namespace ray { namespace streaming {} // namespace streaming } // namespace ray
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
streaming/src/util/streaming_logging.h
C/C++ Header
#ifndef RAY_STREAMING_LOGGING_H #define RAY_STREAMING_LOGGING_H #include "ray/util/logging.h" #define STREAMING_LOG RAY_LOG #define STREAMING_CHECK RAY_CHECK namespace ray { namespace streaming {} // namespace streaming } // namespace ray #endif // RAY_STREAMING_LOGGING_H
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
streaming/src/util/streaming_util.cc
C++
#include <unordered_set> #include "streaming_util.h" namespace ray { namespace streaming { boost::any &Config::Get(ConfigEnum key) const { auto item = config_map_.find(key); STREAMING_CHECK(item != config_map_.end()); return item->second; } boost::any Config::Get(ConfigEnum key, boost::any default_value) const { auto item = config_map_.find(key); if (item == config_map_.end()) { return default_value; } return item->second; } std::string Util::Byte2hex(const uint8_t *data, uint32_t data_size) { constexpr char hex[] = "0123456789abcdef"; std::string result; for (uint32_t i = 0; i < data_size; i++) { unsigned short val = data[i]; result.push_back(hex[val >> 4]); result.push_back(hex[val & 0xf]); } return result; } std::string Util::Hexqid2str(const std::string &q_id_hex) { std::string result; for (uint32_t i = 0; i < q_id_hex.size(); i += 2) { std::string byte = q_id_hex.substr(i, 2); char chr = static_cast<char>(std::strtol(byte.c_str(), nullptr, 16)); result.push_back(chr); } return result; } } // namespace streaming } // namespace ray
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
streaming/src/util/streaming_util.h
C/C++ Header
#ifndef RAY_STREAMING_UTIL_H #define RAY_STREAMING_UTIL_H #include <boost/any.hpp> #include <string> #include <unordered_map> #include "util/streaming_logging.h" namespace ray { namespace streaming { enum class ConfigEnum : uint32_t { QUEUE_ID_VECTOR = 0, RECONSTRUCT_RETRY_TIMES, RECONSTRUCT_TIMEOUT_PER_MB, CURRENT_DRIVER_ID, /// For direct call CORE_WORKER, SYNC_FUNCTION, ASYNC_FUNCTION, TRANSFER_MIN = QUEUE_ID_VECTOR, TRANSFER_MAX = ASYNC_FUNCTION }; } // namespace streaming } // namespace ray namespace std { template <> struct hash<::ray::streaming::ConfigEnum> { size_t operator()(const ::ray::streaming::ConfigEnum &config_enum_key) const { return static_cast<uint32_t>(config_enum_key); } }; template <> struct hash<const ::ray::streaming::ConfigEnum> { size_t operator()(const ::ray::streaming::ConfigEnum &config_enum_key) const { return static_cast<uint32_t>(config_enum_key); } }; } // namespace std namespace ray { namespace streaming { class Config { public: template <typename ValueType> inline void Set(ConfigEnum key, const ValueType &any) { config_map_.emplace(key, any); } template <typename ValueType> inline void Set(ConfigEnum key, ValueType &&any) { config_map_.emplace(key, any); } template <typename ValueType> inline boost::any &GetOrDefault(ConfigEnum key, ValueType &&any) { auto item = config_map_.find(key); if (item != config_map_.end()) { return item->second; } Set(key, any); return any; } boost::any &Get(ConfigEnum key) const; boost::any Get(ConfigEnum key, boost::any default_value) const; inline uint32_t GetInt32(ConfigEnum key) { return boost::any_cast<uint32_t>(Get(key)); } inline uint64_t GetInt64(ConfigEnum key) { return boost::any_cast<uint64_t>(Get(key)); } inline double GetDouble(ConfigEnum key) { return boost::any_cast<double>(Get(key)); } inline bool GetBool(ConfigEnum key) { return boost::any_cast<bool>(Get(key)); } inline std::string GetString(ConfigEnum key) { return boost::any_cast<std::string>(Get(key)); } virtual ~Config() = default; protected: mutable std::unordered_map<ConfigEnum, boost::any> config_map_; }; class Util { public: static std::string Byte2hex(const uint8_t *data, uint32_t data_size); static std::string Hexqid2str(const std::string &q_id_hex); }; } // namespace streaming } // namespace ray #endif // RAY_STREAMING_UTIL_H
zhuohan123/hoplite-rllib
3
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/distributed_train.py
Python
#!/usr/bin/env python3 -u # Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import os import socket import subprocess from train import main as single_process_main from fairseq import distributed_utils, options def main(args): if args.distributed_init_method is None and args.distributed_port > 0: # We can determine the init method automatically for Slurm. node_list = os.environ.get('SLURM_JOB_NODELIST') if node_list is not None: try: hostnames = subprocess.check_output(['scontrol', 'show', 'hostnames', node_list]) args.distributed_init_method = 'tcp://{host}:{port}'.format( host=hostnames.split()[0].decode('utf-8'), port=args.distributed_port) args.distributed_rank = int(os.environ.get('SLURM_PROCID')) args.device_id = int(os.environ.get('SLURM_LOCALID')) except subprocess.CalledProcessError as e: # scontrol failed raise e except FileNotFoundError as e: # Slurm is not installed pass if args.distributed_init_method is None and args.distributed_port is None: raise ValueError('--distributed-init-method or --distributed-port ' 'must be specified for distributed training') args.distributed_rank = distributed_utils.distributed_init(args) print('| initialized host {} as rank {}'.format(socket.gethostname(), args.distributed_rank)) single_process_main(args) if __name__ == '__main__': parser = options.get_training_parser() args = options.parse_args_and_arch(parser) main(args)
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/eval_lm.py
Python
#!/usr/bin/env python3 -u # Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. """ Evaluate the perplexity of a trained language model. """ import numpy as np import torch from fairseq import data, options, progress_bar, tasks, utils from fairseq.meters import StopwatchMeter, TimeMeter from fairseq.sequence_scorer import SequenceScorer class WordStat(object): def __init__(self, word, is_bpe): self.word = word self.is_bpe = is_bpe self.log_prob = 0 self.count = 0 def add(self, log_prob): self.log_prob += log_prob self.count += 1 def __str__(self): return '{}\t{}\t{}\t{}'.format(self.word, self.count, self.log_prob / self.count, self.is_bpe) def main(parsed_args): assert parsed_args.path is not None, '--path required for evaluation!' print(parsed_args) use_cuda = torch.cuda.is_available() and not parsed_args.cpu task = tasks.setup_task(parsed_args) # Load ensemble print('| loading model(s) from {}'.format(parsed_args.path)) models, args = utils.load_ensemble_for_inference(parsed_args.path.split(':'), task) args.__dict__.update(parsed_args.__dict__) print(args) task.args = args # Load dataset splits task.load_dataset(args.gen_subset) print('| {} {} {} examples'.format(args.data, args.gen_subset, len(task.dataset(args.gen_subset)))) # Optimize ensemble for generation and set the source and dest dicts on the model (required by scorer) for model in models: model.make_generation_fast_() if args.fp16: model.half() assert len(models) > 0 itr = task.get_batch_iterator( dataset=task.dataset(args.gen_subset), max_tokens=args.max_tokens or 36000, max_sentences=args.max_sentences, max_positions=utils.resolve_max_positions(*[ model.max_positions() for model in models ]), num_shards=args.num_shards, shard_id=args.shard_id, ignore_invalid_inputs=True, ).next_epoch_itr(shuffle=False) gen_timer = StopwatchMeter() scorer = SequenceScorer(models, task.target_dictionary) if use_cuda: scorer.cuda() score_sum = 0. count = 0 if args.remove_bpe is not None: bpe_cont = args.remove_bpe.rstrip() bpe_toks = set(i for i in range(len(task.dictionary)) if task.dictionary[i].endswith(bpe_cont)) bpe_len = len(bpe_cont) else: bpe_toks = None bpe_len = 0 word_stats = dict() with progress_bar.build_progress_bar(args, itr) as t: results = scorer.score_batched_itr(t, cuda=use_cuda, timer=gen_timer) wps_meter = TimeMeter() for _, src_tokens, __, hypos in results: for hypo in hypos: pos_scores = hypo['positional_scores'] skipped_toks = 0 if bpe_toks is not None: for i in range(len(hypo['tokens']) - 1): if hypo['tokens'][i].item() in bpe_toks: skipped_toks += 1 pos_scores[i + 1] += pos_scores[i] pos_scores[i] = 0 inf_scores = pos_scores.eq(float('inf')) | pos_scores.eq(float('-inf')) if inf_scores.any(): print('| Skipping tokens with inf scores:', task.target_dictionary.string(hypo['tokens'][inf_scores.nonzero()])) pos_scores = pos_scores[(~inf_scores).nonzero()] score_sum += utils.item(pos_scores.sum()) count += pos_scores.numel() - skipped_toks if args.output_word_probs or args.output_word_stats: w = '' word_prob = [] is_bpe = False for i in range(len(hypo['tokens'])): w_ind = hypo['tokens'][i].item() w += task.dictionary[w_ind] if bpe_toks is not None and w_ind in bpe_toks: w = w[:-bpe_len] is_bpe = True else: word_prob.append((w, pos_scores[i].item())) word_stats.setdefault(w, WordStat(w, is_bpe)).add(pos_scores[i].item()) is_bpe = False w = '' if args.output_word_probs: print('\t'.join('{} [{:2f}]'.format(x[0], x[1]) for x in word_prob)) wps_meter.update(src_tokens.size(0)) t.log({'wps': round(wps_meter.avg)}) avg_nll_loss = -score_sum / count print('| Evaluated {} tokens in {:.1f}s ({:.2f} tokens/s)'.format(gen_timer.n, gen_timer.sum, 1. / gen_timer.avg)) print('| Loss: {:.4f}, Perplexity: {:.2f}'.format(avg_nll_loss, np.exp(avg_nll_loss))) if args.output_word_stats: for ws in sorted(word_stats.values(), key=lambda x: x.count, reverse=True): print(ws) if __name__ == '__main__': parser = options.get_eval_lm_parser() args = options.parse_args_and_arch(parser) main(args)
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/__init__.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. from .multiprocessing_pdb import pdb __all__ = ['pdb'] import fairseq.criterions import fairseq.models import fairseq.modules import fairseq.optim import fairseq.optim.lr_scheduler import fairseq.tasks
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/bleu.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import ctypes import math import torch try: from fairseq import libbleu except ImportError as e: import sys sys.stderr.write('ERROR: missing libbleu.so. run `python setup.py install`\n') raise e C = ctypes.cdll.LoadLibrary(libbleu.__file__) class BleuStat(ctypes.Structure): _fields_ = [ ('reflen', ctypes.c_size_t), ('predlen', ctypes.c_size_t), ('match1', ctypes.c_size_t), ('count1', ctypes.c_size_t), ('match2', ctypes.c_size_t), ('count2', ctypes.c_size_t), ('match3', ctypes.c_size_t), ('count3', ctypes.c_size_t), ('match4', ctypes.c_size_t), ('count4', ctypes.c_size_t), ] class Scorer(object): def __init__(self, pad, eos, unk): self.stat = BleuStat() self.pad = pad self.eos = eos self.unk = unk self.reset() def reset(self, one_init=False): if one_init: C.bleu_one_init(ctypes.byref(self.stat)) else: C.bleu_zero_init(ctypes.byref(self.stat)) def add(self, ref, pred): if not isinstance(ref, torch.IntTensor): raise TypeError('ref must be a torch.IntTensor (got {})' .format(type(ref))) if not isinstance(pred, torch.IntTensor): raise TypeError('pred must be a torch.IntTensor(got {})' .format(type(pred))) # don't match unknown words rref = ref.clone() assert not rref.lt(0).any() rref[rref.eq(self.unk)] = -999 rref = rref.contiguous().view(-1) pred = pred.contiguous().view(-1) C.bleu_add( ctypes.byref(self.stat), ctypes.c_size_t(rref.size(0)), ctypes.c_void_p(rref.data_ptr()), ctypes.c_size_t(pred.size(0)), ctypes.c_void_p(pred.data_ptr()), ctypes.c_int(self.pad), ctypes.c_int(self.eos)) def score(self, order=4): psum = sum(math.log(p) if p > 0 else float('-Inf') for p in self.precision()[:order]) return self.brevity() * math.exp(psum / order) * 100 def precision(self): def ratio(a, b): return a / b if b > 0 else 0 return [ ratio(self.stat.match1, self.stat.count1), ratio(self.stat.match2, self.stat.count2), ratio(self.stat.match3, self.stat.count3), ratio(self.stat.match4, self.stat.count4), ] def brevity(self): r = self.stat.reflen / self.stat.predlen return min(1, math.exp(1 - r)) def result_string(self, order=4): assert order <= 4, "BLEU scores for order > 4 aren't supported" fmt = 'BLEU{} = {:2.2f}, {:2.1f}' for _ in range(1, order): fmt += '/{:2.1f}' fmt += ' (BP={:.3f}, ratio={:.3f}, syslen={}, reflen={})' bleup = [p * 100 for p in self.precision()[:order]] return fmt.format(order, self.score(order=order), *bleup, self.brevity(), self.stat.predlen/self.stat.reflen, self.stat.predlen, self.stat.reflen)
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/clib/libbleu/libbleu.cpp
C++
/** * Copyright 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the license found in the * LICENSE file in the root directory of this source tree. */ #include <map> #include <array> #include <cstring> #include <cstdio> typedef struct { size_t reflen; size_t predlen; size_t match1; size_t count1; size_t match2; size_t count2; size_t match3; size_t count3; size_t match4; size_t count4; } bleu_stat; // left trim (remove pad) void bleu_ltrim(size_t* len, int** sent, int pad) { size_t start = 0; while(start < *len) { if (*(*sent + start) != pad) { break; } start++; } *sent += start; *len -= start; } // right trim remove (eos) void bleu_rtrim(size_t* len, int** sent, int pad, int eos) { size_t end = *len - 1; while (end > 0) { if (*(*sent + end) != eos && *(*sent + end) != pad) { break; } end--; } *len = end + 1; } // left and right trim void bleu_trim(size_t* len, int** sent, int pad, int eos) { bleu_ltrim(len, sent, pad); bleu_rtrim(len, sent, pad, eos); } size_t bleu_hash(int len, int* data) { size_t h = 14695981039346656037ul; size_t prime = 0x100000001b3; char* b = (char*) data; size_t blen = sizeof(int) * len; while (blen-- > 0) { h ^= *b++; h *= prime; } return h; } void bleu_addngram( size_t *ntotal, size_t *nmatch, size_t n, size_t reflen, int* ref, size_t predlen, int* pred) { if (predlen < n) { return; } predlen = predlen - n + 1; (*ntotal) += predlen; if (reflen < n) { return; } reflen = reflen - n + 1; std::map<size_t, size_t> count; while (predlen > 0) { size_t w = bleu_hash(n, pred++); count[w]++; predlen--; } while (reflen > 0) { size_t w = bleu_hash(n, ref++); if (count[w] > 0) { (*nmatch)++; count[w] -=1; } reflen--; } } extern "C" { void bleu_zero_init(bleu_stat* stat) { std::memset(stat, 0, sizeof(bleu_stat)); } void bleu_one_init(bleu_stat* stat) { bleu_zero_init(stat); stat->count1 = 0; stat->count2 = 1; stat->count3 = 1; stat->count4 = 1; stat->match1 = 0; stat->match2 = 1; stat->match3 = 1; stat->match4 = 1; } void bleu_add( bleu_stat* stat, size_t reflen, int* ref, size_t predlen, int* pred, int pad, int eos) { bleu_trim(&reflen, &ref, pad, eos); bleu_trim(&predlen, &pred, pad, eos); stat->reflen += reflen; stat->predlen += predlen; bleu_addngram(&stat->count1, &stat->match1, 1, reflen, ref, predlen, pred); bleu_addngram(&stat->count2, &stat->match2, 2, reflen, ref, predlen, pred); bleu_addngram(&stat->count3, &stat->match3, 3, reflen, ref, predlen, pred); bleu_addngram(&stat->count4, &stat->match4, 4, reflen, ref, predlen, pred); } }
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/clib/libbleu/module.cpp
C++
/** * Copyright 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the license found in the * LICENSE file in the root directory of this source tree. */ #include <Python.h> static PyMethodDef method_def[] = { {NULL, NULL, 0, NULL} }; static struct PyModuleDef module_def = { PyModuleDef_HEAD_INIT, "libbleu", /* name of module */ NULL, /* module documentation, may be NULL */ -1, /* size of per-interpreter state of the module, or -1 if the module keeps state in global variables. */ method_def }; #if PY_MAJOR_VERSION == 2 PyMODINIT_FUNC init_libbleu() #else PyMODINIT_FUNC PyInit_libbleu() #endif { PyObject *m = PyModule_Create(&module_def); if (!m) { return NULL; } return m; }
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/criterions/__init__.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import importlib import os from .fairseq_criterion import FairseqCriterion CRITERION_REGISTRY = {} CRITERION_CLASS_NAMES = set() def build_criterion(args, task): return CRITERION_REGISTRY[args.criterion](args, task) def register_criterion(name): """Decorator to register a new criterion.""" def register_criterion_cls(cls): if name in CRITERION_REGISTRY: raise ValueError('Cannot register duplicate criterion ({})'.format(name)) if not issubclass(cls, FairseqCriterion): raise ValueError('Criterion ({}: {}) must extend FairseqCriterion'.format(name, cls.__name__)) if cls.__name__ in CRITERION_CLASS_NAMES: # We use the criterion class name as a unique identifier in # checkpoints, so all criterions must have unique class names. raise ValueError('Cannot register criterion with duplicate class name ({})'.format(cls.__name__)) CRITERION_REGISTRY[name] = cls CRITERION_CLASS_NAMES.add(cls.__name__) return cls return register_criterion_cls # automatically import any Python files in the criterions/ directory for file in os.listdir(os.path.dirname(__file__)): if file.endswith('.py') and not file.startswith('_'): module = file[:file.find('.py')] importlib.import_module('fairseq.criterions.' + module)
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/criterions/adaptive_loss.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import math import torch.nn.functional as F from fairseq import utils from . import FairseqCriterion, register_criterion @register_criterion('adaptive_loss') class AdaptiveLoss(FairseqCriterion): """This is an implementation of the loss function accompanying the adaptive softmax approximation for graphical processing units (GPU), described in the paper "Efficient softmax approximation for GPUs" (http://arxiv.org/abs/1609.04309).""" def __init__(self, args, task): super().__init__(args, task) if args.ddp_backend == 'c10d': raise Exception( 'AdaptiveLoss is not compatible with the c10d ' 'version of DistributedDataParallel. Please use ' '`--ddp-backend=no_c10d` instead.' ) def forward(self, model, sample, reduce=True): """Compute the loss for the given sample. Returns a tuple with three elements: 1) the loss 2) the sample size, which is used as the denominator for the gradient 3) logging outputs to display while training """ assert hasattr(model.decoder, 'adaptive_softmax') and model.decoder.adaptive_softmax is not None adaptive_softmax = model.decoder.adaptive_softmax net_output = model(**sample['net_input']) orig_target = model.get_targets(sample, net_output) nsentences = orig_target.size(0) orig_target = orig_target.view(-1) bsz = orig_target.size(0) logits, target = adaptive_softmax(net_output[0], orig_target) assert len(target) == len(logits) loss = net_output[0].new(1 if reduce else bsz).zero_() for i in range(len(target)): if target[i] is not None: assert (target[i].min() >= 0 and target[i].max() <= logits[i].size(1)) loss += F.cross_entropy(logits[i], target[i], size_average=False, ignore_index=self.padding_idx, reduce=reduce) orig = utils.strip_pad(orig_target, self.padding_idx) ntokens = orig.numel() sample_size = sample['target'].size(0) if self.args.sentence_avg else ntokens logging_output = { 'loss': utils.item(loss.data) if reduce else loss.data, 'ntokens': ntokens, 'nsentences': nsentences, 'sample_size': sample_size, } return loss, sample_size, logging_output @staticmethod def aggregate_logging_outputs(logging_outputs): """Aggregate logging outputs from data parallel training.""" loss_sum = sum(log.get('loss', 0) for log in logging_outputs) ntokens = sum(log.get('ntokens', 0) for log in logging_outputs) nsentences = sum(log.get('nsentences', 0) for log in logging_outputs) sample_size = sum(log.get('sample_size', 0) for log in logging_outputs) agg_output = { 'loss': loss_sum / sample_size, 'nll_loss': loss_sum / sample_size, 'ntokens': ntokens, 'nsentences': nsentences, 'sample_size': sample_size, } if sample_size != ntokens: agg_output['nll_loss'] = loss_sum / ntokens return agg_output
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/criterions/cross_entropy.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import math import torch.nn.functional as F from fairseq import utils from . import FairseqCriterion, register_criterion @register_criterion('cross_entropy') class CrossEntropyCriterion(FairseqCriterion): def __init__(self, args, task): super().__init__(args, task) def forward(self, model, sample, reduce=True): """Compute the loss for the given sample. Returns a tuple with three elements: 1) the loss 2) the sample size, which is used as the denominator for the gradient 3) logging outputs to display while training """ net_output = model(**sample['net_input']) lprobs = model.get_normalized_probs(net_output, log_probs=True) lprobs = lprobs.view(-1, lprobs.size(-1)) target = model.get_targets(sample, net_output).view(-1) loss = F.nll_loss(lprobs, target, size_average=False, ignore_index=self.padding_idx, reduce=reduce) sample_size = sample['target'].size(0) if self.args.sentence_avg else sample['ntokens'] logging_output = { 'loss': utils.item(loss.data) if reduce else loss.data, 'ntokens': sample['ntokens'], 'nsentences': sample['target'].size(0), 'sample_size': sample_size, } return loss, sample_size, logging_output @staticmethod def aggregate_logging_outputs(logging_outputs): """Aggregate logging outputs from data parallel training.""" loss_sum = sum(log.get('loss', 0) for log in logging_outputs) ntokens = sum(log.get('ntokens', 0) for log in logging_outputs) nsentences = sum(log.get('nsentences', 0) for log in logging_outputs) sample_size = sum(log.get('sample_size', 0) for log in logging_outputs) agg_output = { 'loss': loss_sum / sample_size, 'ntokens': ntokens, 'nsentences': nsentences, 'sample_size': sample_size, } if sample_size != ntokens: agg_output['nll_loss'] = loss_sum / ntokens return agg_output
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/criterions/cross_entropy_bert.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import math import torch.nn.functional as F from fairseq import utils from . import FairseqCriterion, register_criterion @register_criterion('cross_entropy_bert') class CrossEntropyBertCriterion(FairseqCriterion): def __init__(self, args, task): super().__init__(args, task) def forward(self, model, sample, reduce=True): """Compute the loss for the given sample. Returns a tuple with three elements: 1) the loss 2) the sample size, which is used as the denominator for the gradient 3) logging outputs to display while training """ mlm_out, nsp_out = model(**sample['net_input']) mlm_lprobs = model.get_normalized_probs(mlm_out, log_probs=True) mlm_lprobs = mlm_lprobs.view(-1, mlm_lprobs.size(-1)) target = model.get_targets(sample, mlm_out)[sample['net_input']['output_mask']].view(-1) mlm_loss = F.nll_loss(mlm_lprobs, target, ignore_index=self.padding_idx, reduction='sum' if reduce else 'none') mlm_acc = (mlm_lprobs.argmax(dim=-1).eq(target)).float().sum() nsp_out = nsp_out.float() label = model.get_label(sample) # B nsp_loss = F.binary_cross_entropy_with_logits(nsp_out, label.float(), reduction='sum' if reduce else 'none') nsp_acc = ((nsp_out >= 0.0).eq(label.byte())).float().sum() sample_size = target.ne(self.padding_idx).long().sum().item() n_sentences = sample['target'].size(0) loss = mlm_loss + nsp_loss * sample_size / n_sentences logging_output = { 'loss': utils.item(loss.data) if reduce else loss.data, 'mlm_loss': utils.item(mlm_loss.data) if reduce else mlm_loss.data, 'mlm_acc': utils.item(mlm_acc.data) if reduce else mlm_acc.data, 'nsp_loss': utils.item(nsp_loss.data) if reduce else nsp_loss.data, 'nsp_acc': utils.item(nsp_acc.data) if reduce else nsp_acc.data, 'ntokens': sample['ntokens'], 'nsentences': n_sentences, 'sample_size': sample_size, } return loss, sample_size, logging_output @staticmethod def aggregate_logging_outputs(logging_outputs): """Aggregate logging outputs from data parallel training.""" loss_sum = sum(log.get('loss', 0) for log in logging_outputs) mlm_loss_sum = sum(log.get('mlm_loss', 0) for log in logging_outputs) mlm_acc_sum = sum(log.get('mlm_acc', 0) for log in logging_outputs) nsp_loss_sum = sum(log.get('nsp_loss', 0) for log in logging_outputs) nsp_acc_sum = sum(log.get('nsp_acc', 0) for log in logging_outputs) ntokens = sum(log.get('ntokens', 0) for log in logging_outputs) nsentences = sum(log.get('nsentences', 0) for log in logging_outputs) sample_size = sum(log.get('sample_size', 0) for log in logging_outputs) agg_output = { 'loss': loss_sum / sample_size, 'mlm_loss': mlm_loss_sum / sample_size, 'mlm_acc': mlm_acc_sum / sample_size, 'nsp_loss': nsp_loss_sum / nsentences, 'nsp_acc': nsp_acc_sum / nsentences, 'ntokens': ntokens, 'nsentences': nsentences, 'sample_size': sample_size, } return agg_output
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/criterions/cross_entropy_classify.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import torch.nn.functional as F from fairseq import utils from . import FairseqCriterion, register_criterion @register_criterion('cross_entropy_classify') class CrossEntropyClassifyCriterion(FairseqCriterion): def __init__(self, args, task): super().__init__(args, task) def forward(self, model, sample, reduce=True): net_output = model(**sample['net_input']) lprobs = model.get_normalized_probs(net_output, log_probs=True) # B x 2 target = model.get_targets(sample, net_output) # B loss = F.nll_loss(lprobs, target, reduction='sum' if reduce else 'none') acc = (lprobs.argmax(dim=-1).eq(target)).float().sum() sample_size = target.size(0) logging_output = { 'loss': utils.item(loss.data) if reduce else loss.data, 'acc': utils.item(acc.data) if reduce else acc.data, 'ntokens': sample['ntokens'], 'nsentences': sample['target'].size(0), 'sample_size': sample_size, } return loss, sample_size, logging_output @staticmethod def aggregate_logging_outputs(logging_outputs): """Aggregate logging outputs from data parallel training.""" loss_sum = sum(log.get('loss', 0) for log in logging_outputs) acc_sum = sum(log.get('acc', 0) for log in logging_outputs) ntokens = sum(log.get('ntokens', 0) for log in logging_outputs) nsentences = sum(log.get('nsentences', 0) for log in logging_outputs) sample_size = sum(log.get('sample_size', 0) for log in logging_outputs) agg_output = { 'loss': loss_sum / sample_size, 'acc': acc_sum / sample_size, 'ntokens': ntokens, 'nsentences': nsentences, 'sample_size': sample_size, } return agg_output
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/criterions/cross_entropy_classify_binary.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import torch.nn.functional as F from fairseq import utils from . import FairseqCriterion, register_criterion @register_criterion('cross_entropy_classify_binary') class CrossEntropyClassifyBinaryCriterion(FairseqCriterion): def __init__(self, args, task): super().__init__(args, task) def forward(self, model, sample, reduce=True): net_output = model(**sample['net_input']).view(-1) # B target = model.get_targets(sample, net_output) # B loss = F.binary_cross_entropy_with_logits(net_output, target.float(), reduction='sum' if reduce else 'none') tp = ((net_output >= 0) & (target == 1)).long().sum() fp = ((net_output >= 0) & (target == 0)).long().sum() fn = ((net_output < 0) & (target == 1)).long().sum() tn = ((net_output < 0) & (target == 0)).long().sum() assert (tp + fp + tn + fn) == target.size(0), 'invalid size' sample_size = target.size(0) logging_output = { 'loss': utils.item(loss.data) if reduce else loss.data, 'tp': utils.item(tp.data) if reduce else tp.data, 'fp': utils.item(fp.data) if reduce else fp.data, 'fn': utils.item(fn.data) if reduce else fn.data, 'tn': utils.item(tn.data) if reduce else tn.data, 'ntokens': sample['ntokens'], 'nsentences': sample['target'].size(0), 'sample_size': sample_size, } return loss, sample_size, logging_output @staticmethod def aggregate_logging_outputs(logging_outputs): """Aggregate logging outputs from data parallel training.""" loss_sum = sum(log.get('loss', 0) for log in logging_outputs) ntokens = sum(log.get('ntokens', 0) for log in logging_outputs) nsentences = sum(log.get('nsentences', 0) for log in logging_outputs) sample_size = sum(log.get('sample_size', 0) for log in logging_outputs) tp_sum = sum(log.get('tp', 0) for log in logging_outputs) fp_sum = sum(log.get('fp', 0) for log in logging_outputs) fn_sum = sum(log.get('fn', 0) for log in logging_outputs) tn_sum = sum(log.get('tn', 0) for log in logging_outputs) assert tp_sum + fp_sum + fn_sum + tn_sum == sample_size, 'invalid size when aggregating' acc = (tp_sum + tn_sum) / sample_size # tmp = 2 * tp_sum + fp_sum + fn_sum # f1 = (2 * tp_sum) / tmp if tmp else 0 # tmp = (tp_sum + fp_sum) * (tp_sum + fn_sum) * (tn_sum + fp_sum) * (tn_sum + fn_sum) # mcc = (tp_sum * tn_sum - fp_sum * fn_sum) / (tmp ** 0.5) if tmp else 0 agg_output = { 'loss': loss_sum / sample_size, 'acc': acc, 'tp': tp_sum, 'fp': fp_sum, 'fn': fn_sum, 'tn': tn_sum, 'ntokens': ntokens, 'nsentences': nsentences, 'sample_size': sample_size, } return agg_output
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/criterions/fairseq_criterion.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. from torch.nn.modules.loss import _Loss class FairseqCriterion(_Loss): def __init__(self, args, task): super().__init__() self.args = args self.padding_idx = task.target_dictionary.pad() @staticmethod def add_args(parser): """Add criterion-specific arguments to the parser.""" pass def forward(self, model, sample, reduce=True): """Compute the loss for the given sample. Returns a tuple with three elements: 1) the loss 2) the sample size, which is used as the denominator for the gradient 3) logging outputs to display while training """ raise NotImplementedError @staticmethod def aggregate_logging_outputs(logging_outputs): """Aggregate logging outputs from data parallel training.""" raise NotImplementedError @staticmethod def grad_denom(sample_sizes): """Compute the gradient denominator for a set of sample sizes.""" return sum(sample_sizes)
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/criterions/label_smoothed_cross_entropy.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import math from fairseq import utils from . import FairseqCriterion, register_criterion @register_criterion('label_smoothed_cross_entropy') class LabelSmoothedCrossEntropyCriterion(FairseqCriterion): def __init__(self, args, task): super().__init__(args, task) self.eps = args.label_smoothing @staticmethod def add_args(parser): """Add criterion-specific arguments to the parser.""" parser.add_argument('--label-smoothing', default=0., type=float, metavar='D', help='epsilon for label smoothing, 0 means no label smoothing') def forward(self, model, sample, reduce=True): """Compute the loss for the given sample. Returns a tuple with three elements: 1) the loss 2) the sample size, which is used as the denominator for the gradient 3) logging outputs to display while training """ net_output = model(**sample['net_input']) loss, nll_loss = self.compute_loss(model, net_output, sample, reduce=reduce) sample_size = sample['target'].size(0) if self.args.sentence_avg else sample['ntokens'] logging_output = { 'loss': utils.item(loss.data) if reduce else loss.data, 'nll_loss': utils.item(nll_loss.data) if reduce else nll_loss.data, 'ntokens': sample['ntokens'], 'nsentences': sample['target'].size(0), 'sample_size': sample_size, } return loss, sample_size, logging_output def compute_loss(self, model, net_output, sample, reduce=True): lprobs = model.get_normalized_probs(net_output, log_probs=True) lprobs = lprobs.view(-1, lprobs.size(-1)) target = model.get_targets(sample, net_output).view(-1, 1) non_pad_mask = target.ne(self.padding_idx) nll_loss = -lprobs.gather(dim=-1, index=target)[non_pad_mask] smooth_loss = -lprobs.sum(dim=-1, keepdim=True)[non_pad_mask] if reduce: nll_loss = nll_loss.sum() smooth_loss = smooth_loss.sum() eps_i = self.eps / lprobs.size(-1) loss = (1. - self.eps) * nll_loss + eps_i * smooth_loss return loss, nll_loss @staticmethod def aggregate_logging_outputs(logging_outputs): """Aggregate logging outputs from data parallel training.""" ntokens = sum(log.get('ntokens', 0) for log in logging_outputs) nsentences = sum(log.get('nsentences', 0) for log in logging_outputs) sample_size = sum(log.get('sample_size', 0) for log in logging_outputs) return { 'loss': sum(log.get('loss', 0) for log in logging_outputs) / sample_size, 'nll_loss': sum(log.get('nll_loss', 0) for log in logging_outputs) / ntokens, 'ntokens': ntokens, 'nsentences': nsentences, 'sample_size': sample_size, }
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/criterions/mean_squared_error.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import torch.nn.functional as F import scipy.stats as stats import numpy as np from fairseq import utils from . import FairseqCriterion, register_criterion @register_criterion('mean_squared_error') class MeanSquaredErrorCriterion(FairseqCriterion): def __init__(self, args, task): super().__init__(args, task) def forward(self, model, sample, reduce=True): net_output = model(**sample['net_input']).view(-1) # B target = model.get_targets(sample, net_output).float() # B loss = F.mse_loss(net_output, target, reduction='sum' if reduce else 'none') sample_size = target.size(0) logging_output = { 'loss': utils.item(loss.data) if reduce else loss.data, 'ntokens': sample['ntokens'], 'nsentences': sample['target'].size(0), 'sample_size': sample_size, 'x': net_output.detach().cpu().numpy(), 'y': target.detach().cpu().numpy() } return loss, sample_size, logging_output @staticmethod def aggregate_logging_outputs(logging_outputs): """Aggregate logging outputs from data parallel training.""" loss_sum = sum(log.get('loss', 0) for log in logging_outputs) ntokens = sum(log.get('ntokens', 0) for log in logging_outputs) nsentences = sum(log.get('nsentences', 0) for log in logging_outputs) sample_size = sum(log.get('sample_size', 0) for log in logging_outputs) # x = np.concatenate([log.get('x', np.array([])) for log in logging_outputs]) # y = np.concatenate([log.get('y', np.array([])) for log in logging_outputs]) # pearson = stats.pearsonr(x, y)[0] # spearman = stats.spearmanr(x, y)[0] agg_output = { 'loss': loss_sum / sample_size, # 'acc': 0.5 * (pearson + spearman), 'ntokens': ntokens, 'nsentences': nsentences, 'sample_size': sample_size, 'x': np.concatenate([log.get('x', np.array([])) for log in logging_outputs]), 'y': np.concatenate([log.get('y', np.array([])) for log in logging_outputs]) # 'pearson': pearson, # 'spearman': spearman } return agg_output
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/data/__init__.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. from .dictionary import Dictionary, TruncatedDictionary, BertDictionary from .fairseq_dataset import FairseqDataset from .indexed_dataset import IndexedDataset, IndexedInMemoryDataset, IndexedRawTextDataset from .language_pair_dataset import LanguagePairDataset from .monolingual_dataset import MonolingualDataset from .bert_dataset import BertDataset from .glue_dataset import GlueSingleDataset, GluePairDataset from .token_block_dataset import TokenBlockDataset from .iterators import ( CountingIterator, EpochBatchIterator, GroupedIterator, ShardedIterator, ) __all__ = [ 'CountingIterator', 'Dictionary', 'BertDictionary', 'EpochBatchIterator', 'FairseqDataset', 'GroupedIterator', 'IndexedDataset', 'IndexedInMemoryDataset', 'IndexedRawTextDataset', 'LanguagePairDataset', 'MonolingualDataset', 'BertDataset', 'GlueSingleDataset', 'GluePairDataset', 'ShardedIterator', 'TokenBlockDataset', ]
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/data/backtranslation_dataset.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. from fairseq import sequence_generator from . import FairseqDataset, language_pair_dataset class BacktranslationDataset(FairseqDataset): def __init__(self, args, tgt_dataset, tgt_dict, backtranslation_model): """ Sets up a backtranslation dataset which takes a tgt batch, generates a src using a tgt-src backtranslation_model, and returns the corresponding {generated src, input tgt} batch Args: args: generation args for the backtranslation SequenceGenerator' Note that there is no equivalent argparse code for these args anywhere in our top level train scripts yet. Integration is still in progress. You can still, however, test out this dataset functionality with the appropriate args as in the corresponding unittest: test_backtranslation_dataset. tgt_dataset: dataset which will be used to build self.tgt_dataset -- a LanguagePairDataset with tgt dataset as the source dataset and None as the target dataset. We use language_pair_dataset here to encapsulate the tgt_dataset so we can re-use the LanguagePairDataset collater to format the batches in the structure that SequenceGenerator expects. tgt_dict: tgt dictionary (typically a joint src/tgt BPE dictionary) backtranslation_model: tgt-src model to use in the SequenceGenerator to generate backtranslations from tgt batches """ self.tgt_dataset = language_pair_dataset.LanguagePairDataset( src=tgt_dataset, src_sizes=None, src_dict=tgt_dict, tgt=None, tgt_sizes=None, tgt_dict=None, ) self.backtranslation_generator = sequence_generator.SequenceGenerator( [backtranslation_model], tgt_dict, unk_penalty=args.backtranslation_unkpen, sampling=args.backtranslation_sampling, beam_size=args.backtranslation_beam, ) self.backtranslation_max_len_a = args.backtranslation_max_len_a self.backtranslation_max_len_b = args.backtranslation_max_len_b self.backtranslation_beam = args.backtranslation_beam def __getitem__(self, index): """ Returns a single sample. Multiple samples are fed to the collater to create a backtranslation batch. Note you should always use collate_fn BacktranslationDataset.collater() below if given the option to specify which collate_fn to use (e.g. in a dataloader which uses this BacktranslationDataset -- see corresponding unittest for an example). """ return self.tgt_dataset[index] def __len__(self): """ The length of the backtranslation dataset is the length of tgt. """ return len(self.tgt_dataset) def collater(self, samples): """ Using the samples from the tgt dataset, load a collated tgt sample to feed to the backtranslation model. Then take the generated translation with best score as the source and the orignal net input as the target. """ collated_tgt_only_sample = self.tgt_dataset.collater(samples) backtranslation_hypos = self._generate_hypotheses(collated_tgt_only_sample) # Go through each tgt sentence in batch and its corresponding best # generated hypothesis and create a backtranslation data pair # {id: id, source: generated backtranslation, target: original tgt} generated_samples = [] for input_sample, hypos in zip(samples, backtranslation_hypos): generated_samples.append( { "id": input_sample["id"], "source": hypos[0]["tokens"], # first hypo is best hypo "target": input_sample["source"], } ) return language_pair_dataset.collate( samples=generated_samples, pad_idx=self.tgt_dataset.src_dict.pad(), eos_idx=self.tgt_dataset.src_dict.eos(), ) def get_dummy_batch(self, num_tokens, max_positions): """ Just use the tgt dataset get_dummy_batch """ self.tgt_dataset.get_dummy_batch(num_tokens, max_positions) def num_tokens(self, index): """ Just use the tgt dataset num_tokens """ self.tgt_dataset.num_tokens(index) def ordered_indices(self): """ Just use the tgt dataset ordered_indices """ self.tgt_dataset.ordered_indices def valid_size(self, index, max_positions): """ Just use the tgt dataset size """ self.tgt_dataset.valid_size(index, max_positions) def _generate_hypotheses(self, sample): """ Generates hypotheses from a LanguagePairDataset collated / batched sample. Note in this case, sample["target"] is None, and sample["net_input"]["src_tokens"] is really in tgt language. """ self.backtranslation_generator.cuda() input = sample["net_input"] srclen = input["src_tokens"].size(1) hypos = self.backtranslation_generator.generate( input, maxlen=int( self.backtranslation_max_len_a * srclen + self.backtranslation_max_len_b ), ) return hypos
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/data/bert_dataset.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import numpy as np import torch from fairseq import utils from . import data_utils, FairseqDataset def collate( samples, pad_idx, eos_idx, left_pad=True ): if len(samples) == 0: return {} def merge(key, left_pad, move_eos_to_beginning=False): return data_utils.collate_tokens( [s[key] for s in samples], pad_idx, eos_idx, left_pad, move_eos_to_beginning, ) id = torch.LongTensor([s['id'] for s in samples]) src_tokens = merge('source', left_pad=left_pad) # sort by descending source length src_lengths = torch.LongTensor([s['source'].numel() for s in samples]) src_lengths, sort_order = src_lengths.sort(descending=True) id = id.index_select(0, sort_order) src_tokens = src_tokens.index_select(0, sort_order) target = merge('target', left_pad=left_pad) target = target.index_select(0, sort_order) ntokens = sum(len(s['target']) for s in samples) segment = merge('segment', left_pad=left_pad) segment = segment.index_select(0, sort_order) label = torch.stack([s['label'] for s in samples]) label = label.index_select(0, sort_order) batch = { 'id': id, 'ntokens': ntokens, 'net_input': { 'src_tokens': src_tokens, 'src_lengths': src_lengths, 'segment': segment, 'output_mask': target.ne(pad_idx) }, 'target': target, 'label': label, 'nsentences': samples[0]['source'].size(0), } return batch def transform(sentences, idx, dictionary, next_sent, prob, mask_prob, random_prob, max_positions, *, dummy=-1): # Generate NSP if dummy >= 0: # generate a dummy case for testing dummy = (dummy - 1) // 2 sentence = torch.cat([dictionary.dummy_sentence(dummy), dictionary.dummy_sentence(dummy)]) segment = torch.cat([torch.ones(dummy, dtype=torch.long), torch.zeros(dummy, dtype=torch.long)]) label = np.random.randint(0, 2) else: sent1, sent2 = data_utils.truncate_pair(sentences[idx], sentences[next_sent[idx]], max_positions) sentence = torch.cat([sent1, sent2]) segment = torch.cat([torch.ones_like(sent1), torch.zeros_like(sent2)]) label = int(next_sent[idx] == idx + 1) # Generate MLM to_mask = torch.arange(sentence.size(0))[sentence > dictionary.nspecial] to_mask = to_mask[torch.randperm(to_mask.size(0))[:int(round(to_mask.size(0) * prob))]] source = sentence.clone() target = torch.ones_like(sentence) * dictionary.pad() target[to_mask] = sentence[to_mask] for i in to_mask: r = np.random.random() if r < mask_prob: source[i] = dictionary.mask() elif r < mask_prob + random_prob: source[i] = np.random.randint(low=dictionary.nspecial, high=len(dictionary.symbols)) # Add cls tag source = torch.cat([torch.LongTensor([dictionary.cls()]), source]) target = torch.cat([torch.LongTensor([dictionary.cls()]), target]) segment = torch.cat([torch.LongTensor([1]), segment]) return source, target, segment, torch.tensor(label) class BertDataset(FairseqDataset): def __init__( self, src, src_sizes, src_dict, left_pad=True, max_positions=384, shuffle=True, masked_lm_prob=0.15, mlm_mask_prob=0.8, mlm_random_prob=0.1 ): self.src = src self.src_sizes = np.array(src_sizes) self.next_sent = None self.out_sizes = None self.src_dict = src_dict self.left_pad = left_pad self.max_positions = max_positions self.shuffle = shuffle self.masked_lm_prob = masked_lm_prob self.mlm_mask_prob = mlm_mask_prob self.mlm_random_prob = mlm_random_prob def __getitem__(self, index): source, target, segment, label = transform(self.src, index, self.src_dict, self.next_sent, self.masked_lm_prob, self.mlm_mask_prob, self.mlm_random_prob, self.max_positions) return { 'id': index, 'source': source, 'target': target, 'segment': segment, 'label': label } def __len__(self): return len(self.src) - 1 def collater(self, samples): """Merge a list of samples to form a mini-batch. Args: samples (List[dict]): samples to collate Returns: dict: a mini-batch with the following keys: - `id` (LongTensor): example IDs in the original input order - `ntokens` (int): total number of tokens in the batch - `net_input` (dict): the input to the Model, containing keys: - `src_tokens` (LongTensor): a padded 2D Tensor of tokens in the source sentence of shape `(bsz, src_len)`. Padding will appear on the left if *left_pad_source* is ``True``. - `src_lengths` (LongTensor): 1D Tensor of the unpadded lengths of each source sentence of shape `(bsz)` - `prev_output_tokens` (LongTensor): a padded 2D Tensor of tokens in the target sentence, shifted right by one position for input feeding/teacher forcing, of shape `(bsz, tgt_len)`. This key will not be present if *input_feeding* is ``False``. Padding will appear on the left if *left_pad_target* is ``True``. - `target` (LongTensor): a padded 2D Tensor of tokens in the target sentence of shape `(bsz, tgt_len)`. Padding will appear on the left if *left_pad_target* is ``True``. """ return collate( samples, pad_idx=self.src_dict.pad(), eos_idx=self.src_dict.eos(), left_pad=self.left_pad ) def get_dummy_batch(self, num_tokens, max_positions, src_len=384): """Return a dummy batch with a given number of tokens.""" src_len = utils.resolve_max_positions( src_len, max_positions, self.max_positions ) bsz = num_tokens // src_len source, target, segment, label = transform(self.src, -1, self.src_dict, self.next_sent, self.masked_lm_prob, self.mlm_mask_prob, self.mlm_random_prob, self.max_positions, dummy=src_len) return self.collater([ { 'id': i, 'source': source, 'target': target, 'segment': segment, 'label': label } for i in range(bsz) ]) def update_nsp_indices(self): n = len(self.src) perm = np.random.permutation(n - 1) to_roll = perm[:(n - 1) // 2] to_keep = perm[(n - 1) // 2:] self.next_sent = np.empty(n - 1, dtype=np.int64) self.next_sent[to_keep] = to_keep + 1 self.next_sent[to_roll] = np.random.permutation(to_roll) + 1 self.out_sizes = np.minimum(self.src_sizes[:-1] + self.src_sizes[self.next_sent] + 1, self.max_positions) def num_tokens(self, index): """Return the number of tokens in a sample. This value is used to enforce ``--max-tokens`` during batching.""" return self.out_sizes[index] def size(self, index): """Return an example's size as a float or tuple. This value is used when filtering a dataset with ``--max-positions``.""" return self.out_sizes[index] def ordered_indices(self): """Return an ordered list of indices. Batches will be constructed based on this order.""" self.update_nsp_indices() if self.shuffle: indices = np.random.permutation(len(self)) else: indices = np.arange(len(self)) return indices[np.argsort(self.out_sizes[indices], kind='mergesort')]
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/data/data_utils.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import contextlib import os import numpy as np def infer_language_pair(path): """Infer language pair from filename: <split>.<lang1>-<lang2>.(...).idx""" src, dst = None, None for filename in os.listdir(path): parts = filename.split('.') if len(parts) >= 3 and len(parts[1].split('-')) == 2: return parts[1].split('-') return src, dst def collate_tokens(values, pad_idx, eos_idx, left_pad, move_eos_to_beginning=False): """Convert a list of 1d tensors into a padded 2d tensor.""" size = max(v.size(0) for v in values) res = values[0].new(len(values), size).fill_(pad_idx) def copy_tensor(src, dst): assert dst.numel() == src.numel() if move_eos_to_beginning: assert src[-1] == eos_idx dst[0] = eos_idx dst[1:] = src[:-1] else: dst.copy_(src) for i, v in enumerate(values): copy_tensor(v, res[i][size - len(v):] if left_pad else res[i][:len(v)]) return res @contextlib.contextmanager def numpy_seed(seed): """Context manager which seeds the NumPy PRNG with the specified seed and restores the state afterward""" if seed is None: yield return state = np.random.get_state() np.random.seed(seed) try: yield finally: np.random.set_state(state) def collect_filtered(function, iterable, filtered): """ Similar to :func:`filter` but collects filtered elements in ``filtered``. Args: function (callable): function that returns ``False`` for elements that should be filtered iterable (iterable): iterable to filter filtered (list): list to store filtered elements """ for el in iterable: if function(el): yield el else: filtered.append(el) def filter_by_size(indices, size_fn, max_positions, raise_exception=False): """ Filter indices based on their size. Args: indices (List[int]): ordered list of dataset indices size_fn (callable): function that returns the size of a given index max_positions (tuple): filter elements larger than this size. Comparisons are done component-wise. raise_exception (bool, optional): if ``True``, raise an exception if any elements are filtered. Default: ``False`` """ def check_size(idx): if isinstance(max_positions, float) or isinstance(max_positions, int): return size_fn(idx) <= max_positions else: return all(a is None or b is None or a <= b for a, b in zip(size_fn(idx), max_positions)) ignored = [] itr = collect_filtered(check_size, indices, ignored) for idx in itr: if len(ignored) > 0 and raise_exception: raise Exception(( 'Size of sample #{} is invalid (={}) since max_positions={}, ' 'skip this example with --skip-invalid-size-inputs-valid-test' ).format(idx, size_fn(idx), max_positions)) yield idx if len(ignored) > 0: print(( '| WARNING: {} samples have invalid sizes and will be skipped, ' 'max_positions={}, first few sample ids={}' ).format(len(ignored), max_positions, ignored[:10])) def _trunc_sent(sent, cnt): trunc_head = np.random.binomial(cnt, 0.5) trunc_tail = cnt - trunc_head return sent[trunc_head:-trunc_tail] def truncate_single(sent, max_positions): diff = sent.size(0) + 1 - max_positions if diff <= 0: return sent return _trunc_sent(sent, diff) def truncate_pair(sent1, sent2, max_positions): diff = sent1.size(0) + sent2.size(0) + 1 - max_positions if diff <= 0: return sent1, sent2 if sent1.size(0) > sent2.size(0): to_trunc = min(sent1.size(0) - sent2.size(0), diff) sent1 = _trunc_sent(sent1, to_trunc) diff -= to_trunc elif sent1.size(0) < sent2.size(0): to_trunc = min(sent2.size(0) - sent1.size(0), diff) sent2 = _trunc_sent(sent2, to_trunc) diff -= to_trunc if diff <= 0: return sent1, sent2 trunc1 = np.random.binomial(diff, 0.5) trunc2 = diff - trunc1 return _trunc_sent(sent1, trunc1), _trunc_sent(sent2, trunc2) def batch_by_size( indices, num_tokens_fn, max_tokens=None, max_sentences=None, required_batch_size_multiple=1, ): """ Yield mini-batches of indices bucketed by size. Batches may contain sequences of different lengths. Args: indices (List[int]): ordered list of dataset indices num_tokens_fn (callable): function that returns the number of tokens at a given index max_tokens (int, optional): max number of tokens in each batch. Default: ``None`` max_sentences (int, optional): max number of sentences in each batch. Default: ``None`` required_batch_size_multiple (int, optional): require batch size to be a multiple of N. Default: ``1`` """ max_tokens = max_tokens if max_tokens is not None else float('Inf') max_sentences = max_sentences if max_sentences is not None else float('Inf') bsz_mult = required_batch_size_multiple batch = [] def is_batch_full(num_tokens): if len(batch) == 0: return False if len(batch) == max_sentences: return True if num_tokens > max_tokens: return True return False sample_len = 0 sample_lens = [] ignored = [] for idx in indices: sample_lens.append(num_tokens_fn(idx)) sample_len = max(sample_len, sample_lens[-1]) num_tokens = (len(batch) + 1) * sample_len if is_batch_full(num_tokens): mod_len = max( bsz_mult * (len(batch) // bsz_mult), len(batch) % bsz_mult, ) yield batch[:mod_len] batch = batch[mod_len:] sample_lens = sample_lens[mod_len:] sample_len = max(sample_lens) if len(sample_lens) > 0 else 0 batch.append(idx) if len(batch) > 0: yield batch
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/data/dictionary.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. from collections import Counter import os import torch class Dictionary(object): """A mapping from symbols to consecutive integers""" def __init__(self, pad='<pad>', eos='</s>', unk='<unk>'): self.unk_word, self.pad_word, self.eos_word = unk, pad, eos self.symbols = [] self.count = [] self.indices = {} # dictionary indexing starts at 1 for consistency with Lua self.add_symbol('<Lua heritage>') self.pad_index = self.add_symbol(pad) self.eos_index = self.add_symbol(eos) self.unk_index = self.add_symbol(unk) self.nspecial = len(self.symbols) def __eq__(self, other): return self.indices == other.indices def __getitem__(self, idx): if idx < len(self.symbols): return self.symbols[idx] return self.unk_word def __len__(self): """Returns the number of symbols in the dictionary""" return len(self.symbols) def index(self, sym): """Returns the index of the specified symbol""" if sym in self.indices: return self.indices[sym] return self.unk_index def string(self, tensor, bpe_symbol=None, escape_unk=False): """Helper for converting a tensor of token indices to a string. Can optionally remove BPE symbols or escape <unk> words. """ if torch.is_tensor(tensor) and tensor.dim() == 2: return '\n'.join(self.string(t) for t in tensor) def token_string(i): if i == self.unk(): return self.unk_string(escape_unk) else: return self[i] sent = ' '.join(token_string(i) for i in tensor if i != self.eos()) if bpe_symbol is not None: sent = (sent + ' ').replace(bpe_symbol, '').rstrip() return sent def unk_string(self, escape=False): """Return unknown string, optionally escaped as: <<unk>>""" if escape: return '<{}>'.format(self.unk_word) else: return self.unk_word def add_symbol(self, word, n=1): """Adds a word to the dictionary""" if word in self.indices: idx = self.indices[word] self.count[idx] = self.count[idx] + n return idx else: idx = len(self.symbols) self.indices[word] = idx self.symbols.append(word) self.count.append(n) return idx def update(self, new_dict): """Updates counts from new dictionary.""" for word in new_dict.symbols: idx2 = new_dict.indices[word] if word in self.indices: idx = self.indices[word] self.count[idx] = self.count[idx] + new_dict.count[idx2] else: idx = len(self.symbols) self.indices[word] = idx self.symbols.append(word) self.count.append(new_dict.count[idx2]) def finalize(self, threshold=-1, nwords=-1, padding_factor=8): """Sort symbols by frequency in descending order, ignoring special ones. Args: - threshold defines the minimum word count - nwords defines the total number of words in the final dictionary, including special symbols - padding_factor can be used to pad the dictionary size to be a multiple of 8, which is important on some hardware (e.g., Nvidia Tensor Cores). """ if nwords <= 0: nwords = len(self) new_indices = dict(zip(self.symbols[:self.nspecial], range(self.nspecial))) new_symbols = self.symbols[:self.nspecial] new_count = self.count[:self.nspecial] c = Counter(dict(zip(self.symbols[self.nspecial:], self.count[self.nspecial:]))) for symbol, count in c.most_common(nwords - self.nspecial): if count >= threshold: new_indices[symbol] = len(new_symbols) new_symbols.append(symbol) new_count.append(count) else: break threshold_nwords = len(new_symbols) if padding_factor > 1: i = 0 while threshold_nwords % padding_factor != 0: symbol = 'madeupword{:04d}'.format(i) new_indices[symbol] = len(new_symbols) new_symbols.append(symbol) new_count.append(0) i += 1 threshold_nwords += 1 assert len(new_symbols) % padding_factor == 0 assert len(new_symbols) == len(new_indices) self.count = list(new_count) self.symbols = list(new_symbols) self.indices = new_indices def pad(self): """Helper to get index of pad symbol""" return self.pad_index def eos(self): """Helper to get index of end-of-sentence symbol""" return self.eos_index def unk(self): """Helper to get index of unk symbol""" return self.unk_index @classmethod def load(cls, f, ignore_utf_errors=False): """Loads the dictionary from a text file with the format: ``` <symbol0> <count0> <symbol1> <count1> ... ``` """ if isinstance(f, str): try: if not ignore_utf_errors: with open(f, 'r', encoding='utf-8') as fd: return cls.load(fd) else: with open(f, 'r', encoding='utf-8', errors='ignore') as fd: return cls.load(fd) except FileNotFoundError as fnfe: raise fnfe except Exception: raise Exception("Incorrect encoding detected in {}, please " "rebuild the dataset".format(f)) d = cls() for line in f.readlines(): idx = line.rfind(' ') word = line[:idx] count = int(line[idx+1:]) d.indices[word] = len(d.symbols) d.symbols.append(word) d.count.append(count) return d def save(self, f): """Stores dictionary into a text file""" if isinstance(f, str): os.makedirs(os.path.dirname(f), exist_ok=True) with open(f, 'w', encoding='utf-8') as fd: return self.save(fd) for symbol, count in zip(self.symbols[self.nspecial:], self.count[self.nspecial:]): print('{} {}'.format(symbol, count), file=f) def dummy_sentence(self, length): t = torch.Tensor(length).uniform_(self.nspecial + 1, len(self)).long() t[-1] = self.eos() return t class BertDictionary(Dictionary): def __init__(self): super(BertDictionary, self).__init__() self.mask_index = self.add_symbol('<mask>') self.cls_index = self.add_symbol('<cls>') self.nspecial = len(self.symbols) def mask(self): return self.mask_index def cls(self): return self.cls_index class TruncatedDictionary(object): def __init__(self, wrapped_dict, length): self.__class__ = type(wrapped_dict.__class__.__name__, (self.__class__, wrapped_dict.__class__), {}) self.__dict__ = wrapped_dict.__dict__ self.wrapped_dict = wrapped_dict self.length = min(len(self.wrapped_dict), length) def __len__(self): return self.length def __getitem__(self, i): if i < self.length: return self.wrapped_dict[i] return self.wrapped_dict.unk()
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/data/fairseq_dataset.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import torch.utils.data from fairseq.data import data_utils class FairseqDataset(torch.utils.data.Dataset): """A dataset that provides helpers for batching.""" def __getitem__(self, index): raise NotImplementedError def __len__(self): raise NotImplementedError def collater(self, samples): """Merge a list of samples to form a mini-batch. Args: samples (List[int]): sample indices to collate Returns: dict: a mini-batch suitable for forwarding with a Model """ raise NotImplementedError def get_dummy_batch(self, num_tokens, max_positions): """Return a dummy batch with a given number of tokens.""" raise NotImplementedError def num_tokens(self, index): """Return the number of tokens in a sample. This value is used to enforce ``--max-tokens`` during batching.""" raise NotImplementedError def size(self, index): """Return an example's size as a float or tuple. This value is used when filtering a dataset with ``--max-positions``.""" raise NotImplementedError def ordered_indices(self): """Return an ordered list of indices. Batches will be constructed based on this order.""" raise NotImplementedError
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/data/glue_dataset.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import numpy as np import torch from fairseq import utils from . import data_utils, FairseqDataset def collate( samples, pad_idx, eos_idx, left_pad=True ): if len(samples) == 0: return {} def merge(key, left_pad, move_eos_to_beginning=False): return data_utils.collate_tokens( [s[key] for s in samples], pad_idx, eos_idx, left_pad, move_eos_to_beginning, ) id = torch.LongTensor([s['id'] for s in samples]) src_tokens = merge('source', left_pad=left_pad) # sort by descending source length src_lengths = torch.LongTensor([s['source'].numel() for s in samples]) src_lengths, sort_order = src_lengths.sort(descending=True) id = id.index_select(0, sort_order) src_tokens = src_tokens.index_select(0, sort_order) target = torch.stack([s['target'] for s in samples]) target = target.index_select(0, sort_order) ntokens = sum(len(s['source']) for s in samples) segment = merge('segment', left_pad=left_pad) segment = segment.index_select(0, sort_order) batch = { 'id': id, 'ntokens': ntokens, 'net_input': { 'src_tokens': src_tokens, 'src_lengths': src_lengths, 'segment': segment }, 'target': target, 'nsentences': samples[0]['source'].size(0), } return batch class GlueSingleDataset(FairseqDataset): def __init__( self, src, src_sizes, src_dict, labels, left_pad=True, max_positions=384, shuffle=True ): self.src = src self.src_sizes = np.array(src_sizes) self.src_dict = src_dict self.left_pad = left_pad self.max_positions = max_positions self.shuffle = shuffle self.labels = labels def __getitem__(self, index): source = torch.cat([ torch.LongTensor([self.src_dict.cls()]), data_utils.truncate_single(self.src[index], self.max_positions) ]) return { 'id': index, 'source': source, 'target': self.labels[index], 'segment': torch.ones_like(source) } def __len__(self): return len(self.src) def collater(self, samples): """Merge a list of samples to form a mini-batch. Args: samples (List[dict]): samples to collate Returns: dict: a mini-batch with the following keys: - `id` (LongTensor): example IDs in the original input order - `ntokens` (int): total number of tokens in the batch - `net_input` (dict): the input to the Model, containing keys: - `src_tokens` (LongTensor): a padded 2D Tensor of tokens in the source sentence of shape `(bsz, src_len)`. Padding will appear on the left if *left_pad_source* is ``True``. - `src_lengths` (LongTensor): 1D Tensor of the unpadded lengths of each source sentence of shape `(bsz)` - `prev_output_tokens` (LongTensor): a padded 2D Tensor of tokens in the target sentence, shifted right by one position for input feeding/teacher forcing, of shape `(bsz, tgt_len)`. This key will not be present if *input_feeding* is ``False``. Padding will appear on the left if *left_pad_target* is ``True``. - `target` (LongTensor): a padded 2D Tensor of tokens in the target sentence of shape `(bsz, tgt_len)`. Padding will appear on the left if *left_pad_target* is ``True``. """ return collate( samples, pad_idx=self.src_dict.pad(), eos_idx=self.src_dict.eos(), left_pad=self.left_pad ) def get_dummy_batch(self, num_tokens, max_positions, src_len=384): """Return a dummy batch with a given number of tokens.""" src_len = utils.resolve_max_positions( src_len, max_positions, self.max_positions ) bsz = num_tokens // src_len source = self.src_dict.dummy_sentence(src_len - 1) source = torch.cat([torch.LongTensor([self.src_dict.cls()]), source]) return self.collater([ { 'id': i, 'source': source, 'target': torch.tensor(0), 'segment': torch.ones_like(source) } for i in range(bsz) ]) def num_tokens(self, index): """Return the number of tokens in a sample. This value is used to enforce ``--max-tokens`` during batching.""" return min(self.src_sizes[index] + 1, self.max_positions) def size(self, index): """Return an example's size as a float or tuple. This value is used when filtering a dataset with ``--max-positions``.""" return min(self.src_sizes[index] + 1, self.max_positions) def ordered_indices(self): """Return an ordered list of indices. Batches will be constructed based on this order.""" if self.shuffle: indices = np.random.permutation(len(self)) else: indices = np.arange(len(self)) return indices[np.argsort(self.src_sizes[indices], kind='mergesort')] class GluePairDataset(FairseqDataset): def __init__( self, src, src_sizes, src_dict, labels, left_pad=True, max_positions=384, shuffle=True, symmetric=False ): self.src = src assert len(self.src) % 2 == 0 self.src_sizes = np.array(src_sizes) self.src_dict = src_dict self.left_pad = left_pad self.max_positions = max_positions self.shuffle = shuffle self.labels = labels self.symmetric = symmetric def __getitem__(self, index): sent1, sent2 = self.src[index * 2], self.src[index * 2 + 1] if self.symmetric and np.random.rand() < 0.5: sent1, sent2 = sent2, sent1 sent1, sent2 = data_utils.truncate_pair(sent1, sent2, self.max_positions) return { 'id': index, 'source': torch.cat([torch.LongTensor([self.src_dict.cls()]), sent1, sent2]), 'target': self.labels[index], 'segment': torch.cat([torch.LongTensor([1]), torch.ones_like(sent1), torch.zeros_like(sent2)]) } def __len__(self): return len(self.src) // 2 def collater(self, samples): """Merge a list of samples to form a mini-batch. Args: samples (List[dict]): samples to collate Returns: dict: a mini-batch with the following keys: - `id` (LongTensor): example IDs in the original input order - `ntokens` (int): total number of tokens in the batch - `net_input` (dict): the input to the Model, containing keys: - `src_tokens` (LongTensor): a padded 2D Tensor of tokens in the source sentence of shape `(bsz, src_len)`. Padding will appear on the left if *left_pad_source* is ``True``. - `src_lengths` (LongTensor): 1D Tensor of the unpadded lengths of each source sentence of shape `(bsz)` - `prev_output_tokens` (LongTensor): a padded 2D Tensor of tokens in the target sentence, shifted right by one position for input feeding/teacher forcing, of shape `(bsz, tgt_len)`. This key will not be present if *input_feeding* is ``False``. Padding will appear on the left if *left_pad_target* is ``True``. - `target` (LongTensor): a padded 2D Tensor of tokens in the target sentence of shape `(bsz, tgt_len)`. Padding will appear on the left if *left_pad_target* is ``True``. """ return collate( samples, pad_idx=self.src_dict.pad(), eos_idx=self.src_dict.eos(), left_pad=self.left_pad ) def get_dummy_batch(self, num_tokens, max_positions, src_len=384): """Return a dummy batch with a given number of tokens.""" src_len = utils.resolve_max_positions( src_len, max_positions, self.max_positions ) bsz = num_tokens // src_len source = self.src_dict.dummy_sentence(src_len - 1) source = torch.cat([torch.LongTensor([self.src_dict.cls()]), source]) return self.collater([ { 'id': i, 'source': source, 'target': torch.tensor(0), 'segment': torch.ones_like(source) } for i in range(bsz) ]) def num_tokens(self, index): """Return the number of tokens in a sample. This value is used to enforce ``--max-tokens`` during batching.""" return min(self.src_sizes[index * 2] + self.src_sizes[index * 2 + 1] + 1, self.max_positions) def size(self, index): """Return an example's size as a float or tuple. This value is used when filtering a dataset with ``--max-positions``.""" return min(self.src_sizes[index * 2] + self.src_sizes[index * 2 + 1] + 1, self.max_positions) def ordered_indices(self): """Return an ordered list of indices. Batches will be constructed based on this order.""" out_sizes = np.minimum(self.src_sizes[::2] + self.src_sizes[1::2] + 1, self.max_positions) if self.shuffle: indices = np.random.permutation(len(self)) else: indices = np.arange(len(self)) return indices[np.argsort(out_sizes, kind='mergesort')]
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/data/indexed_dataset.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import os import struct import numpy as np import torch from fairseq.tokenizer import Tokenizer def read_longs(f, n): a = np.empty(n, dtype=np.int64) f.readinto(a) return a def write_longs(f, a): f.write(np.array(a, dtype=np.int64)) dtypes = { 1: np.uint8, 2: np.int8, 3: np.int16, 4: np.int32, 5: np.int64, 6: np.float, 7: np.double, } def code(dtype): for k in dtypes.keys(): if dtypes[k] == dtype: return k def index_file_path(prefix_path): return prefix_path + '.idx' def data_file_path(prefix_path): return prefix_path + '.bin' class IndexedDataset(torch.utils.data.Dataset): """Loader for TorchNet IndexedDataset""" def __init__(self, path, fix_lua_indexing=False, read_data=True): super().__init__() self.fix_lua_indexing = fix_lua_indexing self.read_index(path) self.data_file = None if read_data: self.read_data(path) def read_index(self, path): with open(index_file_path(path), 'rb') as f: magic = f.read(8) assert magic == b'TNTIDX\x00\x00' version = f.read(8) assert struct.unpack('<Q', version) == (1,) code, self.element_size = struct.unpack('<QQ', f.read(16)) self.dtype = dtypes[code] self.size, self.s = struct.unpack('<QQ', f.read(16)) self.dim_offsets = read_longs(f, self.size + 1) self.data_offsets = read_longs(f, self.size + 1) self.sizes = read_longs(f, self.s) def read_data(self, path): self.data_file = open(data_file_path(path), 'rb', buffering=0) def check_index(self, i): if i < 0 or i >= self.size: raise IndexError('index out of range') def __del__(self): if self.data_file: self.data_file.close() def __getitem__(self, i): self.check_index(i) tensor_size = self.sizes[self.dim_offsets[i]:self.dim_offsets[i + 1]] a = np.empty(tensor_size, dtype=self.dtype) self.data_file.seek(self.data_offsets[i] * self.element_size) self.data_file.readinto(a) item = torch.from_numpy(a).long() if self.fix_lua_indexing: item -= 1 # subtract 1 for 0-based indexing return item def __len__(self): return self.size @staticmethod def exists(path): return ( os.path.exists(index_file_path(path)) and os.path.exists(data_file_path(path)) ) class IndexedInMemoryDataset(IndexedDataset): """Loader for TorchNet IndexedDataset, keeps all the data in memory""" def read_data(self, path): self.data_file = open(data_file_path(path), 'rb') self.buffer = np.empty(self.data_offsets[-1], dtype=self.dtype) self.data_file.readinto(self.buffer) self.data_file.close() if self.fix_lua_indexing: self.buffer -= 1 # subtract 1 for 0-based indexing def __del__(self): pass def __getitem__(self, i): self.check_index(i) tensor_size = self.sizes[self.dim_offsets[i]:self.dim_offsets[i + 1]] a = np.empty(tensor_size, dtype=self.dtype) np.copyto(a, self.buffer[self.data_offsets[i]:self.data_offsets[i + 1]]) return torch.from_numpy(a).long() class IndexedRawTextDataset(IndexedDataset): """Takes a text file as input and binarizes it in memory at instantiation. Original lines are also kept in memory""" def __init__(self, path, dictionary, append_eos=True, reverse_order=False): self.tokens_list = [] self.lines = [] self.sizes = [] self.append_eos = append_eos self.reverse_order = reverse_order self.read_data(path, dictionary) self.size = len(self.tokens_list) def read_data(self, path, dictionary): with open(path, 'r') as f: for line in f: self.lines.append(line.strip('\n')) tokens = Tokenizer.tokenize( line, dictionary, add_if_not_exist=False, append_eos=self.append_eos, reverse_order=self.reverse_order, ).long() self.tokens_list.append(tokens) self.sizes.append(len(tokens)) self.sizes = np.array(self.sizes) def __getitem__(self, i): self.check_index(i) return self.tokens_list[i] def get_original_text(self, i): self.check_index(i) return self.lines[i] def __del__(self): pass def __len__(self): return self.size @staticmethod def exists(path): return os.path.exists(path) class IndexedDatasetBuilder(object): element_sizes = { np.uint8: 1, np.int8: 1, np.int16: 2, np.int32: 4, np.int64: 8, np.float: 4, np.double: 8 } def __init__(self, out_file, dtype=np.int32): self.out_file = open(out_file, 'wb') self.dtype = dtype self.data_offsets = [0] self.dim_offsets = [0] self.sizes = [] self.element_size = self.element_sizes[self.dtype] def add_item(self, tensor): # +1 for Lua compatibility bytes = self.out_file.write(np.array(tensor.numpy() + 1, dtype=self.dtype)) self.data_offsets.append(self.data_offsets[-1] + bytes / self.element_size) for s in tensor.size(): self.sizes.append(s) self.dim_offsets.append(self.dim_offsets[-1] + len(tensor.size())) def merge_file_(self, another_file): index = IndexedDataset(another_file, read_data=False) assert index.dtype == self.dtype begin = self.data_offsets[-1] for offset in index.data_offsets[1:]: self.data_offsets.append(begin + offset) self.sizes.extend(index.sizes) begin = self.dim_offsets[-1] for dim_offset in index.dim_offsets[1:]: self.dim_offsets.append(begin + dim_offset) with open(data_file_path(another_file), 'rb') as f: while True: data = f.read(1024) if data: self.out_file.write(data) else: break def finalize(self, index_file): self.out_file.close() index = open(index_file, 'wb') index.write(b'TNTIDX\x00\x00') index.write(struct.pack('<Q', 1)) index.write(struct.pack('<QQ', code(self.dtype), self.element_size)) index.write(struct.pack('<QQ', len(self.data_offsets) - 1, len(self.sizes))) write_longs(index, self.dim_offsets) write_longs(index, self.data_offsets) write_longs(index, self.sizes) index.close()
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/data/iterators.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import itertools import math import numpy as np import torch from . import data_utils class CountingIterator(object): """Wrapper around an iterable that maintains the iteration count. Args: iterable (iterable): iterable to wrap Attributes: count (int): number of elements consumed from this iterator """ def __init__(self, iterable): self.iterable = iterable self.count = 0 self.itr = iter(self) def __len__(self): return len(self.iterable) def __iter__(self): for x in self.iterable: self.count += 1 yield x def __next__(self): return next(self.itr) def has_next(self): """Whether the iterator has been exhausted.""" return self.count < len(self) def skip(self, num_to_skip): """Fast-forward the iterator by skipping *num_to_skip* elements.""" next(itertools.islice(self.itr, num_to_skip, num_to_skip), None) return self class EpochBatchIterator(object): """A multi-epoch iterator over a :class:`torch.utils.data.Dataset`. Compared to :class:`torch.utils.data.DataLoader`, this iterator: - can be reused across multiple epochs with the :func:`next_epoch_itr` method (optionally shuffled between epochs) - can be serialized/deserialized with the :func:`state_dict` and :func:`load_state_dict` methods - supports sharding with the *num_shards* and *shard_id* arguments Args: dataset (~torch.utils.data.Dataset): dataset from which to load the data collate_fn (callable): merges a list of samples to form a mini-batch batch_sampler (~torch.utils.data.Sampler): an iterator over batches of indices seed (int, optional): seed for random number generator for reproducibility. Default: ``1`` num_shards (int, optional): shard the data iterator into N shards. Default: ``1`` shard_id (int, optional): which shard of the data iterator to return. Default: ``0`` """ def __init__(self, dataset, collate_fn, batch_sampler, seed=1, num_shards=1, shard_id=0): assert isinstance(dataset, torch.utils.data.Dataset) self.dataset = dataset self.collate_fn = collate_fn self.frozen_batches = tuple(batch_sampler) self.seed = seed self.num_shards = num_shards self.shard_id = shard_id self.epoch = 0 self._cur_epoch_itr = None self._next_epoch_itr = None def __len__(self): return len(self.frozen_batches) def next_epoch_itr(self, shuffle=True): """Return a new iterator over the dataset. Args: shuffle (bool, optional): shuffle batches before returning the iterator. Default: ``True`` """ if self._next_epoch_itr is not None: self._cur_epoch_itr = self._next_epoch_itr self._next_epoch_itr = None else: self.epoch += 1 self._cur_epoch_itr = self._get_iterator_for_epoch(self.epoch, shuffle) return self._cur_epoch_itr def end_of_epoch(self): """Returns whether the most recent epoch iterator has been exhausted""" return not self._cur_epoch_itr.has_next() @property def iterations_in_epoch(self): """The number of consumed batches in the current epoch.""" if self._cur_epoch_itr is not None: return self._cur_epoch_itr.count elif self._next_epoch_itr is not None: return self._next_epoch_itr.count return 0 def state_dict(self): """Returns a dictionary containing a whole state of the iterator.""" return { 'epoch': self.epoch, 'iterations_in_epoch': self.iterations_in_epoch, } def load_state_dict(self, state_dict): """Copies the state of the iterator from the given *state_dict*.""" self.epoch = state_dict['epoch'] itr_pos = state_dict.get('iterations_in_epoch', 0) if itr_pos > 0: # fast-forward epoch iterator itr = self._get_iterator_for_epoch(self.epoch, state_dict.get('shuffle', True)) if itr_pos < len(itr): self._next_epoch_itr = itr.skip(itr_pos) def _get_iterator_for_epoch(self, epoch, shuffle): if shuffle: # set seed based on the seed and epoch number so that we get # reproducible results when resuming from checkpoints with data_utils.numpy_seed(self.seed + epoch): batches = list(self.frozen_batches) # copy np.random.shuffle(batches) else: batches = self.frozen_batches return CountingIterator(torch.utils.data.DataLoader( self.dataset, collate_fn=self.collate_fn, batch_sampler=ShardedIterator(batches, self.num_shards, self.shard_id, fill_value=[]), )) class GroupedIterator(object): """Wrapper around an iterable that returns groups (chunks) of items. Args: iterable (iterable): iterable to wrap chunk_size (int): size of each chunk """ def __init__(self, iterable, chunk_size): self._len = int(math.ceil(len(iterable) / float(chunk_size))) self.itr = iter(iterable) self.chunk_size = chunk_size def __len__(self): return self._len def __iter__(self): return self def __next__(self): chunk = [] try: for _ in range(self.chunk_size): chunk.append(next(self.itr)) except StopIteration as e: if len(chunk) == 0: raise e return chunk class ShardedIterator(object): """A sharded wrapper around an iterable, padded to length. Args: iterable (iterable): iterable to wrap num_shards (int): number of shards to split the iterable into shard_id (int): which shard to iterator over fill_value (Any, optional): padding value when the iterable doesn't evenly divide *num_shards*. Default: ``None`` """ def __init__(self, iterable, num_shards, shard_id, fill_value=None): if shard_id < 0 or shard_id >= num_shards: raise ValueError('shard_id must be between 0 and num_shards') self._sharded_len = len(iterable) // num_shards if len(iterable) % num_shards > 0: self._sharded_len += 1 self.itr = itertools.zip_longest( range(self._sharded_len), itertools.islice(iterable, shard_id, len(iterable), num_shards), fillvalue=fill_value, ) def __len__(self): return self._sharded_len def __iter__(self): return self def __next__(self): return next(self.itr)[1]
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/data/language_pair_dataset.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import numpy as np import torch from fairseq import utils from . import data_utils, FairseqDataset def collate( samples, pad_idx, eos_idx, left_pad_source=True, left_pad_target=False, input_feeding=True, ): if len(samples) == 0: return {} def merge(key, left_pad, move_eos_to_beginning=False): return data_utils.collate_tokens( [s[key] for s in samples], pad_idx, eos_idx, left_pad, move_eos_to_beginning, ) id = torch.LongTensor([s['id'] for s in samples]) src_tokens = merge('source', left_pad=left_pad_source) # sort by descending source length src_lengths = torch.LongTensor([s['source'].numel() for s in samples]) src_lengths, sort_order = src_lengths.sort(descending=True) id = id.index_select(0, sort_order) src_tokens = src_tokens.index_select(0, sort_order) prev_output_tokens = None target = None if samples[0].get('target', None) is not None: target = merge('target', left_pad=left_pad_target) target = target.index_select(0, sort_order) ntokens = sum(len(s['target']) for s in samples) if input_feeding: # we create a shifted version of targets for feeding the # previous output token(s) into the next decoder step prev_output_tokens = merge( 'target', left_pad=left_pad_target, move_eos_to_beginning=True, ) prev_output_tokens = prev_output_tokens.index_select(0, sort_order) else: ntokens = sum(len(s['source']) for s in samples) batch = { 'id': id, 'ntokens': ntokens, 'net_input': { 'src_tokens': src_tokens, 'src_lengths': src_lengths, }, 'target': target, 'nsentences': samples[0]['source'].size(0), } if prev_output_tokens is not None: batch['net_input']['prev_output_tokens'] = prev_output_tokens return batch class LanguagePairDataset(FairseqDataset): """ A pair of torch.utils.data.Datasets. Args: src (torch.utils.data.Dataset): source dataset to wrap src_sizes (List[int]): source sentence lengths src_dict (~fairseq.data.Dictionary): source vocabulary tgt (torch.utils.data.Dataset, optional): target dataset to wrap tgt_sizes (List[int], optional): target sentence lengths tgt_dict (~fairseq.data.Dictionary, optional): target vocabulary left_pad_source (bool, optional): pad source tensors on the left side. Default: ``True`` left_pad_target (bool, optional): pad target tensors on the left side. Default: ``False`` max_source_positions (int, optional): max number of tokens in the source sentence. Default: ``1024`` max_target_positions (int, optional): max number of tokens in the target sentence. Default: ``1024`` shuffle (bool, optional): shuffle dataset elements before batching. Default: ``True`` input_feeding (bool, optional): create a shifted version of the targets to be passed into the model for input feeding/teacher forcing. Default: ``True`` """ def __init__( self, src, src_sizes, src_dict, tgt=None, tgt_sizes=None, tgt_dict=None, left_pad_source=True, left_pad_target=False, max_source_positions=1024, max_target_positions=1024, shuffle=True, input_feeding=True, ): if tgt_dict is not None: assert src_dict.pad() == tgt_dict.pad() assert src_dict.eos() == tgt_dict.eos() assert src_dict.unk() == tgt_dict.unk() self.src = src self.tgt = tgt self.src_sizes = np.array(src_sizes) self.tgt_sizes = np.array(tgt_sizes) if tgt_sizes is not None else None self.src_dict = src_dict self.tgt_dict = tgt_dict self.left_pad_source = left_pad_source self.left_pad_target = left_pad_target self.max_source_positions = max_source_positions self.max_target_positions = max_target_positions self.shuffle = shuffle self.input_feeding = input_feeding def __getitem__(self, index): return { 'id': index, 'source': self.src[index], 'target': self.tgt[index] if self.tgt is not None else None, } def __len__(self): return len(self.src) def collater(self, samples): """Merge a list of samples to form a mini-batch. Args: samples (List[dict]): samples to collate Returns: dict: a mini-batch with the following keys: - `id` (LongTensor): example IDs in the original input order - `ntokens` (int): total number of tokens in the batch - `net_input` (dict): the input to the Model, containing keys: - `src_tokens` (LongTensor): a padded 2D Tensor of tokens in the source sentence of shape `(bsz, src_len)`. Padding will appear on the left if *left_pad_source* is ``True``. - `src_lengths` (LongTensor): 1D Tensor of the unpadded lengths of each source sentence of shape `(bsz)` - `prev_output_tokens` (LongTensor): a padded 2D Tensor of tokens in the target sentence, shifted right by one position for input feeding/teacher forcing, of shape `(bsz, tgt_len)`. This key will not be present if *input_feeding* is ``False``. Padding will appear on the left if *left_pad_target* is ``True``. - `target` (LongTensor): a padded 2D Tensor of tokens in the target sentence of shape `(bsz, tgt_len)`. Padding will appear on the left if *left_pad_target* is ``True``. """ return collate( samples, pad_idx=self.src_dict.pad(), eos_idx=self.src_dict.eos(), left_pad_source=self.left_pad_source, left_pad_target=self.left_pad_target, input_feeding=self.input_feeding, ) def get_dummy_batch(self, num_tokens, max_positions, src_len=128, tgt_len=128): """Return a dummy batch with a given number of tokens.""" src_len, tgt_len = utils.resolve_max_positions( (src_len, tgt_len), max_positions, (self.max_source_positions, self.max_target_positions), ) bsz = num_tokens // max(src_len, tgt_len) return self.collater([ { 'id': i, 'source': self.src_dict.dummy_sentence(src_len), 'target': self.tgt_dict.dummy_sentence(tgt_len) if self.tgt_dict is not None else None, } for i in range(bsz) ]) def num_tokens(self, index): """Return the number of tokens in a sample. This value is used to enforce ``--max-tokens`` during batching.""" return max(self.src_sizes[index], self.tgt_sizes[index] if self.tgt_sizes is not None else 0) def size(self, index): """Return an example's size as a float or tuple. This value is used when filtering a dataset with ``--max-positions``.""" return (self.src_sizes[index], self.tgt_sizes[index] if self.tgt_sizes is not None else 0) def ordered_indices(self): """Return an ordered list of indices. Batches will be constructed based on this order.""" if self.shuffle: indices = np.random.permutation(len(self)) else: indices = np.arange(len(self)) if self.tgt_sizes is not None: indices = indices[np.argsort(self.tgt_sizes[indices], kind='mergesort')] return indices[np.argsort(self.src_sizes[indices], kind='mergesort')]
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/data/monolingual_dataset.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import numpy as np import torch from . import data_utils, FairseqDataset from typing import List def collate(samples, pad_idx, eos_idx): if len(samples) == 0: return {} def merge(key, is_list=False): if is_list: res = [] for i in range(len(samples[0][key])): res.append(data_utils.collate_tokens( [s[key][i] for s in samples], pad_idx, eos_idx, left_pad=False, )) return res else: return data_utils.collate_tokens( [s[key] for s in samples], pad_idx, eos_idx, left_pad=False, ) is_target_list = isinstance(samples[0]['target'], list) return { 'id': torch.LongTensor([s['id'] for s in samples]), 'ntokens': sum(len(s['source']) for s in samples), 'net_input': { 'src_tokens': merge('source'), 'src_lengths': torch.LongTensor([ s['source'].numel() for s in samples ]), }, 'target': merge('target', is_target_list), 'nsentences': samples[0]['source'].size(0), } class MonolingualDataset(FairseqDataset): """ A wrapper around torch.utils.data.Dataset for monolingual data. Args: dataset (torch.utils.data.Dataset): dataset to wrap sizes (List[int]): sentence lengths vocab (~fairseq.data.Dictionary): vocabulary shuffle (bool, optional): shuffle the elements before batching. Default: ``True`` """ def __init__(self, dataset, sizes, src_vocab, tgt_vocab, add_eos_for_other_targets, shuffle, targets=None): self.dataset = dataset self.sizes = np.array(sizes) self.vocab = src_vocab self.tgt_vocab = tgt_vocab self.add_eos_for_other_targets = add_eos_for_other_targets self.shuffle = shuffle assert targets is None or all( t in {'self', 'future', 'past'} for t in targets), "targets must be none or one of 'self', 'future', 'past'" if targets is not None and len(targets) == 0: targets = None self.targets = targets def __getitem__(self, index): source, future_target, past_target = self.dataset[index] source, target = self._make_source_target(source, future_target, past_target) return {'id': index, 'source': source, 'target': target} def __len__(self): return len(self.dataset) def _make_source_target(self, source, future_target, past_target): if self.targets is not None: target = [] if self.add_eos_for_other_targets and (('self' in self.targets) or ('past' in self.targets)) \ and source[-1] != self.vocab.eos(): # append eos at the end of source source = torch.cat([source, source.new([self.vocab.eos()])]) if 'future' in self.targets: future_target = torch.cat([future_target, future_target.new([self.vocab.pad()])]) if 'past' in self.targets: # first token is before the start of sentence which is only used in "none" break mode when # add_eos_for_other_targets is False past_target = torch.cat([past_target.new([self.vocab.pad()]), past_target[1:], source[-2, None]]) for t in self.targets: if t == 'self': target.append(source) elif t == 'future': target.append(future_target) elif t == 'past': target.append(past_target) else: raise Exception('invalid target ' + t) if len(target) == 1: target = target[0] else: target = future_target return source, self._filter_vocab(target) def _filter_vocab(self, target): if len(self.tgt_vocab) != len(self.vocab): def _filter(target): mask = target.ge(len(self.tgt_vocab)) if mask.any(): target[mask] = self.tgt_vocab.unk() return target if isinstance(target, list): return [_filter(t) for t in target] return _filter(target) return target def collater(self, samples): """Merge a list of samples to form a mini-batch. Args: samples (List[dict]): samples to collate Returns: dict: a mini-batch with the following keys: - `id` (LongTensor): example IDs in the original input order - `ntokens` (int): total number of tokens in the batch - `net_input` (dict): the input to the Model, containing keys: - `src_tokens` (LongTensor): a padded 2D Tensor of tokens in the source sentence of shape `(bsz, src_len)`. Padding will appear on the right. - `target` (LongTensor): a padded 2D Tensor of tokens in the target sentence of shape `(bsz, tgt_len)`. Padding will appear on the right. """ return collate(samples, self.vocab.pad(), self.vocab.eos()) def get_dummy_batch(self, num_tokens, max_positions, tgt_len=128): """Return a dummy batch with a given number of tokens.""" if isinstance(max_positions, float) or isinstance(max_positions, int): tgt_len = min(tgt_len, max_positions) bsz = num_tokens // tgt_len target = self.vocab.dummy_sentence(tgt_len + 2) source, past_target, future_target = target[1:-1], target[2:], target[:-2] source, target = self._make_source_target(source, past_target, future_target) return self.collater([ {'id': i, 'source': source, 'target': target} for i in range(bsz) ]) def num_tokens(self, index): """Return the number of tokens in a sample. This value is used to enforce ``--max-tokens`` during batching.""" return self.sizes[index] def size(self, index): """Return an example's size as a float or tuple. This value is used when filtering a dataset with ``--max-positions``.""" return self.sizes[index] def ordered_indices(self): """Return an ordered list of indices. Batches will be constructed based on this order.""" if self.shuffle: order = [np.random.permutation(len(self))] else: order = [np.arange(len(self))] order.append(np.flip(self.sizes, 0)) return np.lexsort(order)
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/data/token_block_dataset.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import math import numpy as np import torch class TokenBlockDataset(torch.utils.data.Dataset): """Break a 1d tensor of tokens into blocks. The blocks are fetched from the original tensor so no additional memory is allocated. Args: tokens: 1d tensor of tokens to break into blocks sizes: sentence lengths (required for 'complete' and 'eos') block_size: maximum block size (ignored in 'eos' break mode) break_mode: Mode used for breaking tokens. Values can be one of: - 'none': break tokens into equally sized blocks (up to block_size) - 'complete': break tokens into blocks (up to block_size) such that blocks contains complete sentences, although block_size may be exceeded if some sentences exceed block_size - 'eos': each block contains one sentence (block_size is ignored) include_targets: return next tokens as targets """ def __init__(self, tokens, sizes, block_size, pad, eos, break_mode=None, include_targets=False): super().__init__() self.tokens = tokens self.total_size = len(tokens) self.pad = pad self.eos = eos self.include_targets = include_targets self.slice_indices = [] if break_mode is None or break_mode == 'none': length = math.ceil(len(tokens) / block_size) def block_at(i): start = i * block_size end = min(start + block_size, len(tokens)) return (start, end) self.slice_indices = [block_at(i) for i in range(length)] elif break_mode == 'complete': assert sizes is not None and sum(sizes) == len(tokens), '{} != {}'.format(sum(sizes), len(tokens)) tok_idx = 0 sz_idx = 0 curr_size = 0 while sz_idx < len(sizes): if curr_size + sizes[sz_idx] <= block_size or curr_size == 0: curr_size += sizes[sz_idx] sz_idx += 1 else: self.slice_indices.append((tok_idx, tok_idx + curr_size)) tok_idx += curr_size curr_size = 0 if curr_size > 0: self.slice_indices.append((tok_idx, tok_idx + curr_size)) elif break_mode == 'eos': assert sizes is not None and sum(sizes) == len(tokens), '{} != {}'.format(sum(sizes), len(tokens)) curr = 0 for sz in sizes: # skip samples with just 1 example (which would be just the eos token) if sz > 1: self.slice_indices.append((curr, curr + sz)) curr += sz else: raise ValueError('Invalid break_mode: ' + break_mode) self.sizes = np.array([e - s for s, e in self.slice_indices]) def __getitem__(self, index): s, e = self.slice_indices[index] item = torch.LongTensor(self.tokens[s:e]) if self.include_targets: # target is the sentence, for source, rotate item one token to the left (would start with eos) # past target is rotated to the left by 2 (padded if its first) if s == 0: source = np.concatenate([[self.eos], self.tokens[0:e - 1]]) past_target = np.concatenate([[self.pad, self.eos], self.tokens[0:e - 2]]) else: source = self.tokens[s - 1:e - 1] if s == 1: past_target = np.concatenate([[self.eos], self.tokens[0:e - 2]]) else: past_target = self.tokens[s - 2:e - 2] return torch.LongTensor(source), item, torch.LongTensor(past_target) return item def __len__(self): return len(self.slice_indices)
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/distributed_utils.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. from collections import namedtuple import pickle import torch from torch import nn from fairseq import utils def is_master(args): return args.distributed_rank == 0 _use_c10d = [True] C10dStatus = namedtuple('C10dStatus', ['has_c10d', 'is_default']) if hasattr(nn.parallel, 'deprecated'): c10d_status = C10dStatus(has_c10d=True, is_default=True) elif hasattr(nn.parallel, '_DistributedDataParallelC10d'): c10d_status = C10dStatus(has_c10d=True, is_default=False) else: c10d_status = C10dStatus(has_c10d=False, is_default=False) if c10d_status.is_default: import torch.distributed as dist_c10d import torch.distributed.deprecated as dist_no_c10d elif c10d_status.has_c10d: import torch.distributed.c10d as dist_c10d import torch.distributed as dist_no_c10d else: import torch.distributed as dist_no_c10d def distributed_init(args): if args.distributed_world_size == 1: raise ValueError('Cannot initialize distributed with distributed_world_size=1') if args.ddp_backend == 'no_c10d': _use_c10d[0] = False print('| distributed init (rank {}): {}'.format( args.distributed_rank, args.distributed_init_method), flush=True) if _use_c10d[0]: init_fn = dist_c10d.init_process_group else: init_fn = dist_no_c10d.init_process_group init_fn( backend=args.distributed_backend, init_method=args.distributed_init_method, world_size=args.distributed_world_size, rank=args.distributed_rank, ) if not is_master(args): suppress_output() return args.distributed_rank def suppress_output(): """Suppress printing on the current device. Force printing with `force=True`.""" import builtins as __builtin__ builtin_print = __builtin__.print def print(*args, **kwargs): if 'force' in kwargs: force = kwargs.pop('force') if force: builtin_print(*args, **kwargs) __builtin__.print = print def get_rank(): if _use_c10d[0]: return dist_c10d.get_rank() else: return dist_no_c10d.get_rank() def get_world_size(): if _use_c10d[0]: return dist_c10d.get_world_size() else: return dist_no_c10d.get_world_size() def get_default_group(): if _use_c10d[0]: return dist_c10d.group.WORLD else: return dist_no_c10d.group.WORLD def all_reduce(tensor, group=None): if group is None: group = get_default_group() if _use_c10d[0]: return dist_c10d.all_reduce(tensor, group=group) else: return dist_no_c10d.all_reduce(tensor, group=group) def all_gather_list(data, group=None, max_size=16384): """Gathers arbitrary data from all nodes into a list. Similar to :func:`~torch.distributed.all_gather` but for arbitrary Python data. Note that *data* must be picklable. Args: data (Any): data from the local worker to be gathered on other workers group (optional): group of the collective max_size (int, optional): maximum size of the data to be gathered across workers """ rank = get_rank() world_size = get_world_size() buffer_size = max_size * world_size if not hasattr(all_gather_list, '_buffer') or \ all_gather_list._buffer.numel() < buffer_size: all_gather_list._buffer = torch.cuda.ByteTensor(buffer_size) buffer = all_gather_list._buffer buffer.zero_() enc = pickle.dumps(data) enc_size = len(enc) if enc_size + 2 > max_size: raise ValueError('encoded data exceeds max_size: {}'.format(enc_size + 2)) assert max_size < 255*256 buffer_rank = buffer[rank * max_size : (rank + 1) * max_size] buffer_rank[0] = enc_size // 255 # this encoding works for max_size < 65k buffer_rank[1] = enc_size % 255 buffer_rank[2:enc_size+2] = torch.ByteTensor(list(enc)) all_reduce(buffer, group=group) result = [] for i in range(world_size): out_buffer = buffer[i * max_size : (i + 1) * max_size] size = (255 * utils.item(out_buffer[0])) + utils.item(out_buffer[1]) if size > 0: result.append( pickle.loads(bytes(out_buffer[2:size+2].tolist())) ) return result
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/meters.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import time class AverageMeter(object): """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count class TimeMeter(object): """Computes the average occurrence of some event per second""" def __init__(self, init=0): self.reset(init) def reset(self, init=0): self.init = init self.start = time.time() self.n = 0 def update(self, val=1): self.n += val @property def avg(self): return self.n / self.elapsed_time @property def elapsed_time(self): return self.init + (time.time() - self.start) class StopwatchMeter(object): """Computes the sum/avg duration of some event in seconds""" def __init__(self): self.reset() def start(self): self.start_time = time.time() def stop(self, n=1): if self.start_time is not None: delta = time.time() - self.start_time self.sum += delta self.n += n self.start_time = None def reset(self): self.sum = 0 self.n = 0 self.start_time = None @property def avg(self): return self.sum / self.n
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/models/__init__.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import argparse import importlib import os from .fairseq_decoder import FairseqDecoder # noqa: F401 from .fairseq_encoder import FairseqEncoder # noqa: F401 from .fairseq_incremental_decoder import FairseqIncrementalDecoder # noqa: F401 from .fairseq_model import BaseFairseqModel, FairseqModel, FairseqLanguageModel, FairseqBertModel, FairseqClassifierModel # noqa: F401 from .composite_encoder import CompositeEncoder # noqa: F401 from .distributed_fairseq_model import DistributedFairseqModel # noqa: F401 MODEL_REGISTRY = {} ARCH_MODEL_REGISTRY = {} ARCH_MODEL_INV_REGISTRY = {} ARCH_CONFIG_REGISTRY = {} def build_model(args, task): return ARCH_MODEL_REGISTRY[args.arch].build_model(args, task) def register_model(name): """ New model types can be added to fairseq with the :func:`register_model` function decorator. For example:: @register_model('lstm') class LSTM(FairseqModel): (...) .. note:: All models must implement the :class:`BaseFairseqModel` interface. Typically you will extend :class:`FairseqModel` for sequence-to-sequence tasks or :class:`FairseqLanguageModel` for language modeling tasks. Args: name (str): the name of the model """ def register_model_cls(cls): if name in MODEL_REGISTRY: raise ValueError('Cannot register duplicate model ({})'.format(name)) if not issubclass(cls, BaseFairseqModel): raise ValueError('Model ({}: {}) must extend BaseFairseqModel'.format(name, cls.__name__)) MODEL_REGISTRY[name] = cls return cls return register_model_cls def register_model_architecture(model_name, arch_name): """ New model architectures can be added to fairseq with the :func:`register_model_architecture` function decorator. After registration, model architectures can be selected with the ``--arch`` command-line argument. For example:: @register_model_architecture('lstm', 'lstm_luong_wmt_en_de') def lstm_luong_wmt_en_de(args): args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 1000) (...) The decorated function should take a single argument *args*, which is a :class:`argparse.Namespace` of arguments parsed from the command-line. The decorated function should modify these arguments in-place to match the desired architecture. Args: model_name (str): the name of the Model (Model must already be registered) arch_name (str): the name of the model architecture (``--arch``) """ def register_model_arch_fn(fn): if model_name not in MODEL_REGISTRY: raise ValueError('Cannot register model architecture for unknown model type ({})'.format(model_name)) if arch_name in ARCH_MODEL_REGISTRY: raise ValueError('Cannot register duplicate model architecture ({})'.format(arch_name)) if not callable(fn): raise ValueError('Model architecture must be callable ({})'.format(arch_name)) ARCH_MODEL_REGISTRY[arch_name] = MODEL_REGISTRY[model_name] ARCH_MODEL_INV_REGISTRY.setdefault(model_name, []).append(arch_name) ARCH_CONFIG_REGISTRY[arch_name] = fn return fn return register_model_arch_fn # automatically import any Python files in the models/ directory for file in os.listdir(os.path.dirname(__file__)): if file.endswith('.py') and not file.startswith('_'): model_name = file[:file.find('.py')] module = importlib.import_module('fairseq.models.' + model_name) # extra `model_parser` for sphinx if model_name in MODEL_REGISTRY: parser = argparse.ArgumentParser(add_help=False) group_archs = parser.add_argument_group('Named architectures') group_archs.add_argument('--arch', choices=ARCH_MODEL_INV_REGISTRY[model_name]) group_args = parser.add_argument_group('Additional command-line arguments') MODEL_REGISTRY[model_name].add_args(group_args) globals()[model_name + '_parser'] = parser
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/models/composite_encoder.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. from . import FairseqEncoder class CompositeEncoder(FairseqEncoder): """ A wrapper around a dictionary of :class:`FairseqEncoder` objects. We run forward on each encoder and return a dictionary of outputs. The first encoder's dictionary is used for initialization. Args: encoders (dict): a dictionary of :class:`FairseqEncoder` objects. """ def __init__(self, encoders): super().__init__(next(iter(encoders.values())).dictionary) self.encoders = encoders for key in self.encoders: self.add_module(key, self.encoders[key]) def forward(self, src_tokens, src_lengths): """ Args: src_tokens (LongTensor): tokens in the source language of shape `(batch, src_len)` src_lengths (LongTensor): lengths of each source sentence of shape `(batch)` Returns: dict: the outputs from each Encoder """ encoder_out = {} for key in self.encoders: encoder_out[key] = self.encoders[key](src_tokens, src_lengths) return encoder_out def reorder_encoder_out(self, encoder_out, new_order): """Reorder encoder output according to new_order.""" for key in self.encoders: encoder_out[key] = self.encoders[key].reorder_encoder_out(encoder_out[key], new_order) return encoder_out def max_positions(self): return min([self.encoders[key].max_positions() for key in self.encoders]) def upgrade_state_dict(self, state_dict): for key in self.encoders: self.encoders[key].upgrade_state_dict(state_dict) return state_dict
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/models/distributed_fairseq_model.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. from torch.nn import parallel from fairseq.distributed_utils import c10d_status from . import BaseFairseqModel class DistributedFairseqModel(BaseFairseqModel): """ A wrapper around a :class:`BaseFairseqModel` instance that adds support for distributed training. Anytime a method or attribute is called on this class we first try to forward it to the underlying DistributedDataParallel instance, otherwise we forward it to the original :class:`BaseFairseqModel` instance. Args: args (argparse.Namespace): fairseq args model (BaseFairseqModel): model to wrap """ def __init__(self, args, model): super().__init__() assert isinstance(model, BaseFairseqModel) if args.ddp_backend == 'c10d': if c10d_status.is_default: ddp_class = parallel.DistributedDataParallel elif c10d_status.has_c10d: ddp_class = parallel._DistributedDataParallelC10d else: raise Exception( 'Can\'t find c10d version of DistributedDataParallel. ' 'Please update PyTorch.' ) self.ddp_model = ddp_class( module=model, device_ids=[args.device_id], output_device=args.device_id, broadcast_buffers=False, bucket_cap_mb=args.bucket_cap_mb, ) elif args.ddp_backend == 'no_c10d': if c10d_status.is_default: ddp_class = parallel.deprecated.DistributedDataParallel else: ddp_class = parallel.DistributedDataParallel self.ddp_model = ddp_class( module=model, device_ids=[args.device_id], output_device=args.device_id, broadcast_buffers=False, ) else: raise ValueError('Unknown --ddp-backend: ' + args.ddp_backend) def __call__(self, *args, **kwargs): return self.ddp_model(*args, **kwargs) def forward(self, *args, **kwargs): return self.ddp_model.forward(*args, **kwargs) def __getattr__(self, name): try: return super().__getattr__(name) except AttributeError: pass try: return self.ddp_model.__getattr__(name) except AttributeError: pass return self.ddp_model.module.__getattr__(name)
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/models/fairseq_decoder.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import torch.nn as nn import torch.nn.functional as F class FairseqDecoder(nn.Module): """Base class for decoders.""" def __init__(self, dictionary): super().__init__() self.dictionary = dictionary def forward(self, prev_output_tokens, encoder_out): """ Args: prev_output_tokens (LongTensor): previous decoder outputs of shape `(batch, tgt_len)`, for input feeding/teacher forcing encoder_out (Tensor, optional): output from the encoder, used for encoder-side attention Returns: tuple: - the last decoder layer's output of shape `(batch, tgt_len, vocab)` - the last decoder layer's attention weights of shape `(batch, tgt_len, src_len)` """ raise NotImplementedError def get_normalized_probs(self, net_output, log_probs, sample): """Get normalized probabilities (or log probs) from a net's output.""" if hasattr(self, 'adaptive_softmax') and self.adaptive_softmax is not None: assert sample is not None and 'target' in sample out = self.adaptive_softmax.get_log_prob(net_output[0], sample['target']) return out.exp_() if not log_probs else out logits = net_output[0].float() if log_probs: return F.log_softmax(logits, dim=-1) else: return F.softmax(logits, dim=-1) def max_positions(self): """Maximum input length supported by the decoder.""" return 1e6 # an arbitrary large number def upgrade_state_dict(self, state_dict): """Upgrade a (possibly old) state dict for new versions of fairseq.""" return state_dict
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/models/fairseq_encoder.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import torch.nn as nn class FairseqEncoder(nn.Module): """Base class for encoders.""" def __init__(self, dictionary): super().__init__() self.dictionary = dictionary def forward(self, src_tokens, src_lengths, segment): """ Args: src_tokens (LongTensor): tokens in the source language of shape `(batch, src_len)` src_lengths (LongTensor): lengths of each source sentence of shape `(batch)` segment (LongTensor): segment of the sentence (1 for the first and 0 for the second) """ raise NotImplementedError def reorder_encoder_out(self, encoder_out, new_order): """ Reorder encoder output according to `new_order`. Args: encoder_out: output from the ``forward()`` method new_order (LongTensor): desired order Returns: `encoder_out` rearranged according to `new_order` """ raise NotImplementedError def max_positions(self): """Maximum input length supported by the encoder.""" return 1e6 # an arbitrary large number def upgrade_state_dict(self, state_dict): """Upgrade a (possibly old) state dict for new versions of fairseq.""" return state_dict
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/models/fairseq_incremental_decoder.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. from . import FairseqDecoder class FairseqIncrementalDecoder(FairseqDecoder): """Base class for incremental decoders. Incremental decoding is a special mode at inference time where the Model only receives a single timestep of input corresponding to the immediately previous output token (for input feeding) and must produce the next output *incrementally*. Thus the model must cache any long-term state that is needed about the sequence, e.g., hidden states, convolutional states, etc. Compared to the standard :class:`FairseqDecoder` interface, the incremental decoder interface allows :func:`forward` functions to take an extra keyword argument (*incremental_state*) that can be used to cache state across time-steps. The :class:`FairseqIncrementalDecoder` interface also defines the :func:`reorder_incremental_state` method, which is used during beam search to select and reorder the incremental state based on the selection of beams. """ def __init__(self, dictionary): super().__init__(dictionary) def forward(self, prev_output_tokens, encoder_out, incremental_state=None): """ Args: prev_output_tokens (LongTensor): previous decoder outputs of shape `(batch, tgt_len)`, for input feeding/teacher forcing encoder_out (Tensor, optional): output from the encoder, used for encoder-side attention incremental_state (dict): dictionary used for storing state during :ref:`Incremental decoding` Returns: tuple: - the last decoder layer's output of shape `(batch, tgt_len, vocab)` - the last decoder layer's attention weights of shape `(batch, tgt_len, src_len)` """ raise NotImplementedError def reorder_incremental_state(self, incremental_state, new_order): """Reorder incremental state. This should be called when the order of the input has changed from the previous time step. A typical use case is beam search, where the input order changes between time steps based on the selection of beams. """ def apply_reorder_incremental_state(module): if module != self and hasattr(module, 'reorder_incremental_state'): module.reorder_incremental_state( incremental_state, new_order, ) self.apply(apply_reorder_incremental_state) def set_beam_size(self, beam_size): """Sets the beam size in the decoder and all children.""" if getattr(self, '_beam_size', -1) != beam_size: def apply_set_beam_size(module): if module != self and hasattr(module, 'set_beam_size'): module.set_beam_size(beam_size) self.apply(apply_set_beam_size) self._beam_size = beam_size
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/models/fairseq_model.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import torch import torch.nn as nn import torch.nn.functional as F from . import FairseqDecoder, FairseqEncoder class BaseFairseqModel(nn.Module): """Base class for fairseq models.""" def __init__(self): super().__init__() self._is_generation_fast = False @staticmethod def add_args(parser): """Add model-specific arguments to the parser.""" pass @classmethod def build_model(cls, args, task): """Build a new model instance.""" raise NotImplementedError def get_targets(self, sample, net_output): """Get targets from either the sample or the net's output.""" return sample['target'] def get_label(self, sample): return sample['label'] def get_normalized_probs(self, net_output, log_probs, sample=None): """Get normalized probabilities (or log probs) from a net's output.""" if hasattr(self, 'decoder'): return self.decoder.get_normalized_probs(net_output, log_probs, sample) elif torch.is_tensor(net_output): logits = net_output.float() if log_probs: return F.log_softmax(logits, dim=-1) else: return F.softmax(logits, dim=-1) raise NotImplementedError def max_positions(self): """Maximum length supported by the model.""" return None def max_decoder_positions(self): """Maximum length supported by the decoder.""" return self.decoder.max_positions() def load_state_dict(self, state_dict, strict=True): """Copies parameters and buffers from *state_dict* into this module and its descendants. Overrides the method in :class:`nn.Module`. Compared with that method this additionally "upgrades" *state_dicts* from old checkpoints. """ self.upgrade_state_dict(state_dict) super().load_state_dict(state_dict, strict) def upgrade_state_dict(self, state_dict): """Upgrade old state dicts to work with newer code.""" self.upgrade_state_dict_named(state_dict, '') def upgrade_state_dict_named(self, state_dict, name): assert state_dict is not None def do_upgrade(m, prefix): if len(prefix) > 0: prefix += '.' for n, c in m.named_children(): name = prefix + n if hasattr(c, 'upgrade_state_dict_named'): c.upgrade_state_dict_named(state_dict, name) elif hasattr(c, 'upgrade_state_dict'): c.upgrade_state_dict(state_dict) do_upgrade(c, name) do_upgrade(self, name) def make_generation_fast_(self, **kwargs): """Optimize model for faster generation.""" if self._is_generation_fast: return # only apply once self._is_generation_fast = True # remove weight norm from all modules in the network def apply_remove_weight_norm(module): try: nn.utils.remove_weight_norm(module) except ValueError: # this module didn't have weight norm return self.apply(apply_remove_weight_norm) def apply_make_generation_fast_(module): if module != self and hasattr(module, 'make_generation_fast_'): module.make_generation_fast_(**kwargs) self.apply(apply_make_generation_fast_) def train(mode): if mode: raise RuntimeError('cannot train after make_generation_fast') # this model should no longer be used for training self.eval() self.train = train def prepare_for_onnx_export_(self, **kwargs): """Make model exportable via ONNX trace.""" def apply_prepare_for_onnx_export_(module): if module != self and hasattr(module, 'prepare_for_onnx_export_'): module.prepare_for_onnx_export_(**kwargs) self.apply(apply_prepare_for_onnx_export_) class FairseqModel(BaseFairseqModel): """Base class for encoder-decoder models. Args: encoder (FairseqEncoder): the encoder decoder (FairseqDecoder): the decoder """ def __init__(self, encoder, decoder): super().__init__() self.encoder = encoder self.decoder = decoder assert isinstance(self.encoder, FairseqEncoder) assert isinstance(self.decoder, FairseqDecoder) def forward(self, src_tokens, src_lengths, prev_output_tokens): """ Run the forward pass for an encoder-decoder model. First feed a batch of source tokens through the encoder. Then, feed the encoder output and previous decoder outputs (i.e., input feeding/teacher forcing) to the decoder to produce the next outputs:: encoder_out = self.encoder(src_tokens, src_lengths) return self.decoder(prev_output_tokens, encoder_out) Args: src_tokens (LongTensor): tokens in the source language of shape `(batch, src_len)` src_lengths (LongTensor): source sentence lengths of shape `(batch)` prev_output_tokens (LongTensor): previous decoder outputs of shape `(batch, tgt_len)`, for input feeding/teacher forcing Returns: the decoder's output, typically of shape `(batch, tgt_len, vocab)` """ encoder_out = self.encoder(src_tokens, src_lengths) decoder_out = self.decoder(prev_output_tokens, encoder_out) return decoder_out def max_positions(self): """Maximum length supported by the model.""" return (self.encoder.max_positions(), self.decoder.max_positions()) class FairseqBertModel(BaseFairseqModel): def __init__(self, encoder, mid_layer, embed_out, feature_dim): super().__init__() self.encoder = encoder self.mid_layer = mid_layer self.embed_out = embed_out self.classifier = nn.Linear(feature_dim, 1) assert isinstance(self.encoder, FairseqEncoder) def forward(self, src_tokens, src_lengths, segment, output_mask): encoder_return_value = self.encoder(src_tokens, src_lengths, segment, output_mask) encoder_out = encoder_return_value['encoder_out'] # (B + N) x C mlm_out = F.linear(self.mid_layer(encoder_out[src_tokens.size(0):]), self.embed_out) # N x V nsp_out = self.classifier(encoder_out[:src_tokens.size(0)]).view(-1) # B return mlm_out, nsp_out def max_positions(self): return self.encoder.max_positions() class FairseqClassifierModel(BaseFairseqModel): def __init__(self, encoder, feature_dim, n_classes): super().__init__() self.encoder = encoder self.classifier = nn.Linear(feature_dim, n_classes) nn.init.zeros_(self.classifier.weight) nn.init.zeros_(self.classifier.bias) assert isinstance(self.encoder, FairseqEncoder) def forward(self, src_tokens, src_lengths, segment): encoder_out = self.encoder(src_tokens, src_lengths, segment)['encoder_out'] # T x B x C features = encoder_out[0, ...] # B x C return self.classifier(features) def max_positions(self): return self.encoder.max_positions() class FairseqLanguageModel(BaseFairseqModel): """Base class for decoder-only models. Args: decoder (FairseqDecoder): the decoder """ def __init__(self, decoder): super().__init__() self.decoder = decoder assert isinstance(self.decoder, FairseqDecoder) def forward(self, src_tokens, src_lengths): """ Run the forward pass for a decoder-only model. Feeds a batch of tokens through the decoder to predict the next tokens. Args: src_tokens (LongTensor): tokens on which to condition the decoder, of shape `(batch, tgt_len)` src_lengths (LongTensor): source sentence lengths of shape `(batch)` Returns: the decoder's output, typically of shape `(batch, seq_len, vocab)` """ return self.decoder(src_tokens) def max_positions(self): """Maximum length supported by the model.""" return self.decoder.max_positions() @property def supported_targets(self): return {'future'}
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/models/fconv.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import math import torch import torch.nn as nn import torch.nn.functional as F from fairseq import options, utils from fairseq.modules import ( AdaptiveSoftmax, BeamableMM, GradMultiply, LearnedPositionalEmbedding, LinearizedConvolution, ) from . import ( FairseqEncoder, FairseqIncrementalDecoder, FairseqModel, FairseqLanguageModel, register_model, register_model_architecture, ) @register_model('fconv') class FConvModel(FairseqModel): """ A fully convolutional model, i.e. a convolutional encoder and a convolutional decoder, as described in `"Convolutional Sequence to Sequence Learning" (Gehring et al., 2017) <https://arxiv.org/abs/1705.03122>`_. Args: encoder (FConvEncoder): the encoder decoder (FConvDecoder): the decoder The Convolutional model provides the following named architectures and command-line arguments: .. argparse:: :ref: fairseq.models.fconv_parser :prog: """ def __init__(self, encoder, decoder): super().__init__(encoder, decoder) self.encoder.num_attention_layers = sum(layer is not None for layer in decoder.attention) @staticmethod def add_args(parser): """Add model-specific arguments to the parser.""" parser.add_argument('--dropout', type=float, metavar='D', help='dropout probability') parser.add_argument('--encoder-embed-dim', type=int, metavar='N', help='encoder embedding dimension') parser.add_argument('--encoder-embed-path', type=str, metavar='STR', help='path to pre-trained encoder embedding') parser.add_argument('--encoder-layers', type=str, metavar='EXPR', help='encoder layers [(dim, kernel_size), ...]') parser.add_argument('--decoder-embed-dim', type=int, metavar='N', help='decoder embedding dimension') parser.add_argument('--decoder-embed-path', type=str, metavar='STR', help='path to pre-trained decoder embedding') parser.add_argument('--decoder-layers', type=str, metavar='EXPR', help='decoder layers [(dim, kernel_size), ...]') parser.add_argument('--decoder-out-embed-dim', type=int, metavar='N', help='decoder output embedding dimension') parser.add_argument('--decoder-attention', type=str, metavar='EXPR', help='decoder attention [True, ...]') parser.add_argument('--share-input-output-embed', action='store_true', help='share input and output embeddings (requires' ' --decoder-out-embed-dim and --decoder-embed-dim' ' to be equal)') @classmethod def build_model(cls, args, task): """Build a new model instance.""" # make sure that all args are properly defaulted (in case there are any new ones) base_architecture(args) encoder_embed_dict = None if args.encoder_embed_path: encoder_embed_dict = utils.parse_embedding(args.encoder_embed_path) utils.print_embed_overlap(encoder_embed_dict, task.source_dictionary) decoder_embed_dict = None if args.decoder_embed_path: decoder_embed_dict = utils.parse_embedding(args.decoder_embed_path) utils.print_embed_overlap(decoder_embed_dict, task.target_dictionary) encoder = FConvEncoder( dictionary=task.source_dictionary, embed_dim=args.encoder_embed_dim, embed_dict=encoder_embed_dict, convolutions=eval(args.encoder_layers), dropout=args.dropout, max_positions=args.max_source_positions, ) decoder = FConvDecoder( dictionary=task.target_dictionary, embed_dim=args.decoder_embed_dim, embed_dict=decoder_embed_dict, convolutions=eval(args.decoder_layers), out_embed_dim=args.decoder_out_embed_dim, attention=eval(args.decoder_attention), dropout=args.dropout, max_positions=args.max_target_positions, share_embed=args.share_input_output_embed, ) return FConvModel(encoder, decoder) @register_model('fconv_lm') class FConvLanguageModel(FairseqLanguageModel): def __init__(self, decoder): super().__init__(decoder) @staticmethod def add_args(parser): """Add model-specific arguments to the parser.""" parser.add_argument('--dropout', type=float, metavar='D', help='dropout probability') parser.add_argument('--decoder-embed-dim', type=int, metavar='N', help='decoder embedding dimension') parser.add_argument('--decoder-layers', type=str, metavar='EXPR', help='decoder layers [(dim, kernel_size), ...]') parser.add_argument('--decoder-out-embed-dim', type=int, metavar='N', help='decoder output embedding dimension') parser.add_argument('--adaptive-softmax-cutoff', metavar='EXPR', help='comma separated list of adaptive softmax cutoff points. ' 'Must be used with adaptive_loss criterion') parser.add_argument('--adaptive-softmax-dropout', type=float, metavar='D', help='sets adaptive softmax dropout for the tail projections') parser.add_argument('--decoder-attention', type=str, metavar='EXPR', help='decoder attention [True, ...]') @classmethod def build_model(cls, args, task): """Build a new model instance.""" # make sure all arguments are present in older models base_lm_architecture(args) if hasattr(args, 'max_target_positions'): args.tokens_per_sample = args.max_target_positions decoder = FConvDecoder( dictionary=task.target_dictionary, embed_dim=args.decoder_embed_dim, convolutions=eval(args.decoder_layers), out_embed_dim=args.decoder_embed_dim, attention=eval(args.decoder_attention), dropout=args.dropout, max_positions=args.tokens_per_sample, share_embed=False, positional_embeddings=False, adaptive_softmax_cutoff=( options.eval_str_list(args.adaptive_softmax_cutoff, type=int) if args.criterion == 'adaptive_loss' else None ), adaptive_softmax_dropout=args.adaptive_softmax_dropout, ) return FConvLanguageModel(decoder) class FConvEncoder(FairseqEncoder): """ Convolutional encoder consisting of `len(convolutions)` layers. Args: dictionary (~fairseq.data.Dictionary): encoding dictionary embed_dim (int, optional): embedding dimension embed_dict (str, optional): filename from which to load pre-trained embeddings max_positions (int, optional): maximum supported input sequence length convolutions (list, optional): the convolutional layer structure. Each list item `i` corresponds to convolutional layer `i`. Layers are given as ``(out_channels, kernel_width, [residual])``. Residual connections are added between layers when ``residual=1`` (which is the default behavior). dropout (float, optional): dropout to be applied before each conv layer normalization_constant (float, optional): multiplies the result of the residual block by sqrt(value) left_pad (bool, optional): whether the input is left-padded. Default: ``True`` """ def __init__( self, dictionary, embed_dim=512, embed_dict=None, max_positions=1024, convolutions=((512, 3),) * 20, dropout=0.1, left_pad=True, ): super().__init__(dictionary) self.dropout = dropout self.left_pad = left_pad self.num_attention_layers = None num_embeddings = len(dictionary) self.padding_idx = dictionary.pad() self.embed_tokens = Embedding(num_embeddings, embed_dim, self.padding_idx) if embed_dict: self.embed_tokens = utils.load_embedding(embed_dict, self.dictionary, self.embed_tokens) self.embed_positions = PositionalEmbedding( max_positions, embed_dim, self.padding_idx, left_pad=self.left_pad, ) convolutions = extend_conv_spec(convolutions) in_channels = convolutions[0][0] self.fc1 = Linear(embed_dim, in_channels, dropout=dropout) self.projections = nn.ModuleList() self.convolutions = nn.ModuleList() self.residuals = [] layer_in_channels = [in_channels] for i, (out_channels, kernel_size, residual) in enumerate(convolutions): if residual == 0: residual_dim = out_channels else: residual_dim = layer_in_channels[-residual] self.projections.append(Linear(residual_dim, out_channels) if residual_dim != out_channels else None) if kernel_size % 2 == 1: padding = kernel_size // 2 else: padding = 0 self.convolutions.append( ConvTBC(in_channels, out_channels * 2, kernel_size, dropout=dropout, padding=padding) ) self.residuals.append(residual) in_channels = out_channels layer_in_channels.append(out_channels) self.fc2 = Linear(in_channels, embed_dim) def forward(self, src_tokens, src_lengths): """ Args: src_tokens (LongTensor): tokens in the source language of shape `(batch, src_len)` src_lengths (LongTensor): lengths of each source sentence of shape `(batch)` Returns: dict: - **encoder_out** (tuple): a tuple with two elements, where the first element is the last encoder layer's output and the second element is the same quantity summed with the input embedding (used for attention). The shape of both tensors is `(batch, src_len, embed_dim)`. - **encoder_padding_mask** (ByteTensor): the positions of padding elements of shape `(batch, src_len)` """ # embed tokens and positions x = self.embed_tokens(src_tokens) + self.embed_positions(src_tokens) x = F.dropout(x, p=self.dropout, training=self.training) input_embedding = x # project to size of convolution x = self.fc1(x) # used to mask padding in input encoder_padding_mask = src_tokens.eq(self.padding_idx).t() # -> T x B if not encoder_padding_mask.any(): encoder_padding_mask = None # B x T x C -> T x B x C x = x.transpose(0, 1) residuals = [x] # temporal convolutions for proj, conv, res_layer in zip(self.projections, self.convolutions, self.residuals): if res_layer > 0: residual = residuals[-res_layer] residual = residual if proj is None else proj(residual) else: residual = None if encoder_padding_mask is not None: x = x.masked_fill(encoder_padding_mask.unsqueeze(-1), 0) x = F.dropout(x, p=self.dropout, training=self.training) if conv.kernel_size[0] % 2 == 1: # padding is implicit in the conv x = conv(x) else: padding_l = (conv.kernel_size[0] - 1) // 2 padding_r = conv.kernel_size[0] // 2 x = F.pad(x, (0, 0, 0, 0, padding_l, padding_r)) x = conv(x) x = F.glu(x, dim=2) if residual is not None: x = (x + residual) * math.sqrt(0.5) residuals.append(x) # T x B x C -> B x T x C x = x.transpose(1, 0) # project back to size of embedding x = self.fc2(x) if encoder_padding_mask is not None: encoder_padding_mask = encoder_padding_mask.t() # -> B x T x = x.masked_fill(encoder_padding_mask.unsqueeze(-1), 0) # scale gradients (this only affects backward, not forward) x = GradMultiply.apply(x, 1.0 / (2.0 * self.num_attention_layers)) # add output to input embedding for attention y = (x + input_embedding) * math.sqrt(0.5) return { 'encoder_out': (x, y), 'encoder_padding_mask': encoder_padding_mask, # B x T } def reorder_encoder_out(self, encoder_out, new_order): if encoder_out['encoder_out'] is not None: encoder_out['encoder_out'] = ( encoder_out['encoder_out'][0].index_select(0, new_order), encoder_out['encoder_out'][1].index_select(0, new_order), ) if encoder_out['encoder_padding_mask'] is not None: encoder_out['encoder_padding_mask'] = \ encoder_out['encoder_padding_mask'].index_select(0, new_order) return encoder_out def max_positions(self): """Maximum input length supported by the encoder.""" return self.embed_positions.max_positions() class AttentionLayer(nn.Module): def __init__(self, conv_channels, embed_dim, bmm=None): super().__init__() # projects from output of convolution to embedding dimension self.in_projection = Linear(conv_channels, embed_dim) # projects from embedding dimension to convolution size self.out_projection = Linear(embed_dim, conv_channels) self.bmm = bmm if bmm is not None else torch.bmm def forward(self, x, target_embedding, encoder_out, encoder_padding_mask): residual = x # attention x = (self.in_projection(x) + target_embedding) * math.sqrt(0.5) x = self.bmm(x, encoder_out[0]) # don't attend over padding if encoder_padding_mask is not None: x = x.float().masked_fill( encoder_padding_mask.unsqueeze(1), float('-inf') ).type_as(x) # FP16 support: cast to float and back # softmax over last dim sz = x.size() x = F.softmax(x.view(sz[0] * sz[1], sz[2]), dim=1) x = x.view(sz) attn_scores = x x = self.bmm(x, encoder_out[1]) # scale attention output (respecting potentially different lengths) s = encoder_out[1].size(1) if encoder_padding_mask is None: x = x * (s * math.sqrt(1.0 / s)) else: s = s - encoder_padding_mask.type_as(x).sum(dim=1, keepdim=True) # exclude padding s = s.unsqueeze(-1) x = x * (s * s.rsqrt()) # project back x = (self.out_projection(x) + residual) * math.sqrt(0.5) return x, attn_scores def make_generation_fast_(self, beamable_mm_beam_size=None, **kwargs): """Replace torch.bmm with BeamableMM.""" if beamable_mm_beam_size is not None: del self.bmm self.add_module('bmm', BeamableMM(beamable_mm_beam_size)) class FConvDecoder(FairseqIncrementalDecoder): """Convolutional decoder""" def __init__( self, dictionary, embed_dim=512, embed_dict=None, out_embed_dim=256, max_positions=1024, convolutions=((512, 3),) * 20, attention=True, dropout=0.1, share_embed=False, positional_embeddings=True, adaptive_softmax_cutoff=None, adaptive_softmax_dropout=0, left_pad=False, ): super().__init__(dictionary) self.register_buffer('version', torch.Tensor([2])) self.dropout = dropout self.left_pad = left_pad self.need_attn = True convolutions = extend_conv_spec(convolutions) in_channels = convolutions[0][0] if isinstance(attention, bool): # expand True into [True, True, ...] and do the same with False attention = [attention] * len(convolutions) if not isinstance(attention, list) or len(attention) != len(convolutions): raise ValueError('Attention is expected to be a list of booleans of ' 'length equal to the number of layers.') num_embeddings = len(dictionary) padding_idx = dictionary.pad() self.embed_tokens = Embedding(num_embeddings, embed_dim, padding_idx) if embed_dict: self.embed_tokens = utils.load_embedding(embed_dict, self.dictionary, self.embed_tokens) self.embed_positions = PositionalEmbedding( max_positions, embed_dim, padding_idx, left_pad=self.left_pad, ) if positional_embeddings else None self.fc1 = Linear(embed_dim, in_channels, dropout=dropout) self.projections = nn.ModuleList() self.convolutions = nn.ModuleList() self.attention = nn.ModuleList() self.residuals = [] layer_in_channels = [in_channels] for i, (out_channels, kernel_size, residual) in enumerate(convolutions): if residual == 0: residual_dim = out_channels else: residual_dim = layer_in_channels[-residual] self.projections.append(Linear(residual_dim, out_channels) if residual_dim != out_channels else None) self.convolutions.append( LinearizedConv1d(in_channels, out_channels * 2, kernel_size, padding=(kernel_size - 1), dropout=dropout) ) self.attention.append(AttentionLayer(out_channels, embed_dim) if attention[i] else None) self.residuals.append(residual) in_channels = out_channels layer_in_channels.append(out_channels) self.adaptive_softmax = None self.fc2 = self.fc3 = None if adaptive_softmax_cutoff is not None: assert not share_embed self.adaptive_softmax = AdaptiveSoftmax(num_embeddings, in_channels, adaptive_softmax_cutoff, dropout=adaptive_softmax_dropout) else: self.fc2 = Linear(in_channels, out_embed_dim) if share_embed: assert out_embed_dim == embed_dim, \ "Shared embed weights implies same dimensions " \ " out_embed_dim={} vs embed_dim={}".format(out_embed_dim, embed_dim) self.fc3 = nn.Linear(out_embed_dim, num_embeddings) self.fc3.weight = self.embed_tokens.weight else: self.fc3 = Linear(out_embed_dim, num_embeddings, dropout=dropout) def forward(self, prev_output_tokens, encoder_out_dict=None, incremental_state=None): if encoder_out_dict is not None: encoder_out = encoder_out_dict['encoder_out'] encoder_padding_mask = encoder_out_dict['encoder_padding_mask'] # split and transpose encoder outputs encoder_a, encoder_b = self._split_encoder_out(encoder_out, incremental_state) if self.embed_positions is not None: pos_embed = self.embed_positions(prev_output_tokens, incremental_state) else: pos_embed = 0 if incremental_state is not None: prev_output_tokens = prev_output_tokens[:, -1:] x = self._embed_tokens(prev_output_tokens, incremental_state) # embed tokens and combine with positional embeddings x += pos_embed x = F.dropout(x, p=self.dropout, training=self.training) target_embedding = x # project to size of convolution x = self.fc1(x) # B x T x C -> T x B x C x = self._transpose_if_training(x, incremental_state) # temporal convolutions avg_attn_scores = None num_attn_layers = len(self.attention) residuals = [x] for proj, conv, attention, res_layer in zip(self.projections, self.convolutions, self.attention, self.residuals): if res_layer > 0: residual = residuals[-res_layer] residual = residual if proj is None else proj(residual) else: residual = None x = F.dropout(x, p=self.dropout, training=self.training) x = conv(x, incremental_state) x = F.glu(x, dim=2) # attention if attention is not None: x = self._transpose_if_training(x, incremental_state) x, attn_scores = attention(x, target_embedding, (encoder_a, encoder_b), encoder_padding_mask) if not self.training and self.need_attn: attn_scores = attn_scores / num_attn_layers if avg_attn_scores is None: avg_attn_scores = attn_scores else: avg_attn_scores.add_(attn_scores) x = self._transpose_if_training(x, incremental_state) # residual if residual is not None: x = (x + residual) * math.sqrt(0.5) residuals.append(x) # T x B x C -> B x T x C x = self._transpose_if_training(x, incremental_state) # project back to size of vocabulary if not using adaptive softmax if self.fc2 is not None and self.fc3 is not None: x = self.fc2(x) x = F.dropout(x, p=self.dropout, training=self.training) x = self.fc3(x) return x, avg_attn_scores def reorder_incremental_state(self, incremental_state, new_order): super().reorder_incremental_state(incremental_state, new_order) encoder_out = utils.get_incremental_state(self, incremental_state, 'encoder_out') if encoder_out is not None: encoder_out = tuple(eo.index_select(0, new_order) for eo in encoder_out) utils.set_incremental_state(self, incremental_state, 'encoder_out', encoder_out) def max_positions(self): """Maximum output length supported by the decoder.""" return self.embed_positions.max_positions() if self.embed_positions is not None else float('inf') def upgrade_state_dict(self, state_dict): if utils.item(state_dict.get('decoder.version', torch.Tensor([1]))[0]) < 2: # old models use incorrect weight norm dimension for i, conv in enumerate(self.convolutions): # reconfigure weight norm nn.utils.remove_weight_norm(conv) self.convolutions[i] = nn.utils.weight_norm(conv, dim=0) state_dict['decoder.version'] = torch.Tensor([1]) return state_dict def make_generation_fast_(self, need_attn=False, **kwargs): self.need_attn = need_attn def _embed_tokens(self, tokens, incremental_state): if incremental_state is not None: # keep only the last token for incremental forward pass tokens = tokens[:, -1:] return self.embed_tokens(tokens) def _split_encoder_out(self, encoder_out, incremental_state): """Split and transpose encoder outputs. This is cached when doing incremental inference. """ cached_result = utils.get_incremental_state(self, incremental_state, 'encoder_out') if cached_result is not None: return cached_result # transpose only once to speed up attention layers encoder_a, encoder_b = encoder_out encoder_a = encoder_a.transpose(1, 2).contiguous() result = (encoder_a, encoder_b) if incremental_state is not None: utils.set_incremental_state(self, incremental_state, 'encoder_out', result) return result def _transpose_if_training(self, x, incremental_state): if incremental_state is None: x = x.transpose(0, 1) return x def extend_conv_spec(convolutions): """ Extends convolutional spec that is a list of tuples of 2 or 3 parameters (kernel size, dim size and optionally how many layers behind to look for residual) to default the residual propagation param if it is not specified """ extended = [] for spec in convolutions: if len(spec) == 3: extended.append(spec) elif len(spec) == 2: extended.append(spec + (1,)) else: raise Exception('invalid number of parameters in convolution spec ' + str(spec) + '. expected 2 or 3') return tuple(extended) def Embedding(num_embeddings, embedding_dim, padding_idx): m = nn.Embedding(num_embeddings, embedding_dim, padding_idx=padding_idx) nn.init.normal_(m.weight, 0, 0.1) nn.init.constant_(m.weight[padding_idx], 0) return m def PositionalEmbedding(num_embeddings, embedding_dim, padding_idx, left_pad): m = LearnedPositionalEmbedding(num_embeddings, embedding_dim, padding_idx, left_pad) nn.init.normal_(m.weight, 0, 0.1) nn.init.constant_(m.weight[padding_idx], 0) return m def Linear(in_features, out_features, dropout=0): """Weight-normalized Linear layer (input: N x T x C)""" m = nn.Linear(in_features, out_features) nn.init.normal_(m.weight, mean=0, std=math.sqrt((1 - dropout) / in_features)) nn.init.constant_(m.bias, 0) return nn.utils.weight_norm(m) def LinearizedConv1d(in_channels, out_channels, kernel_size, dropout=0, **kwargs): """Weight-normalized Conv1d layer optimized for decoding""" m = LinearizedConvolution(in_channels, out_channels, kernel_size, **kwargs) std = math.sqrt((4 * (1.0 - dropout)) / (m.kernel_size[0] * in_channels)) nn.init.normal_(m.weight, mean=0, std=std) nn.init.constant_(m.bias, 0) return nn.utils.weight_norm(m, dim=2) def ConvTBC(in_channels, out_channels, kernel_size, dropout=0, **kwargs): """Weight-normalized Conv1d layer""" from fairseq.modules import ConvTBC m = ConvTBC(in_channels, out_channels, kernel_size, **kwargs) std = math.sqrt((4 * (1.0 - dropout)) / (m.kernel_size[0] * in_channels)) nn.init.normal_(m.weight, mean=0, std=std) nn.init.constant_(m.bias, 0) return nn.utils.weight_norm(m, dim=2) @register_model_architecture('fconv_lm', 'fconv_lm') def base_lm_architecture(args): args.dropout = getattr(args, 'dropout', 0.1) args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 128) args.decoder_layers = getattr(args, 'decoder_layers', '[(1268, 4)] * 13') args.decoder_attention = getattr(args, 'decoder_attention', 'False') args.adaptive_softmax_cutoff = getattr(args, 'adaptive_softmax_cutoff', None) args.adaptive_softmax_dropout = getattr(args, 'adaptive_softmax_dropout', 0) @register_model_architecture('fconv_lm', 'fconv_lm_dauphin_wikitext103') def fconv_lm_dauphin_wikitext103(args): layers = '[(850, 6)] * 3' layers += ' + [(850, 1)] * 1' layers += ' + [(850, 5)] * 4' layers += ' + [(850, 1)] * 1' layers += ' + [(850, 4)] * 3' layers += ' + [(1024, 4)] * 1' layers += ' + [(2048, 4)] * 1' args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 280) args.decoder_layers = getattr(args, 'decoder_layers', layers) args.decoder_attention = getattr(args, 'decoder_attention', 'False') args.adaptive_softmax_cutoff = getattr(args, 'adaptive_softmax_cutoff', '10000,20000,200000') base_lm_architecture(args) @register_model_architecture('fconv_lm', 'fconv_lm_dauphin_gbw') def fconv_lm_dauphin_gbw(args): layers = '[(512, 5)]' layers += ' + [(128, 1, 0), (128, 5, 0), (512, 1, 3)] * 3' layers += ' + [(512, 1, 0), (512, 5, 0), (1024, 1, 3)] * 3' layers += ' + [(1024, 1, 0), (1024, 5, 0), (2048, 1, 3)] * 6' layers += ' + [(1024, 1, 0), (1024, 5, 0), (4096, 1, 3)]' args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 128) args.decoder_layers = getattr(args, 'decoder_layers', layers) args.decoder_attention = getattr(args, 'decoder_attention', 'False') args.adaptive_softmax_cutoff = getattr(args, 'adaptive_softmax_cutoff', '10000,50000,200000') base_lm_architecture(args) @register_model_architecture('fconv', 'fconv') def base_architecture(args): args.dropout = getattr(args, 'dropout', 0.1) args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 512) args.encoder_embed_path = getattr(args, 'encoder_embed_path', None) args.encoder_layers = getattr(args, 'encoder_layers', '[(512, 3)] * 20') args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 512) args.decoder_embed_path = getattr(args, 'decoder_embed_path', None) args.decoder_layers = getattr(args, 'decoder_layers', '[(512, 3)] * 20') args.decoder_out_embed_dim = getattr(args, 'decoder_out_embed_dim', 256) args.decoder_attention = getattr(args, 'decoder_attention', 'True') args.share_input_output_embed = getattr(args, 'share_input_output_embed', False) @register_model_architecture('fconv', 'fconv_iwslt_de_en') def fconv_iwslt_de_en(args): args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 256) args.encoder_layers = getattr(args, 'encoder_layers', '[(256, 3)] * 4') args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 256) args.decoder_layers = getattr(args, 'decoder_layers', '[(256, 3)] * 3') args.decoder_out_embed_dim = getattr(args, 'decoder_out_embed_dim', 256) base_architecture(args) @register_model_architecture('fconv', 'fconv_wmt_en_ro') def fconv_wmt_en_ro(args): args.decoder_out_embed_dim = getattr(args, 'decoder_out_embed_dim', 512) base_architecture(args) @register_model_architecture('fconv', 'fconv_wmt_en_de') def fconv_wmt_en_de(args): convs = '[(512, 3)] * 9' # first 9 layers have 512 units convs += ' + [(1024, 3)] * 4' # next 4 layers have 1024 units convs += ' + [(2048, 1)] * 2' # final 2 layers use 1x1 convolutions args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 768) args.encoder_layers = getattr(args, 'encoder_layers', convs) args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 768) args.decoder_layers = getattr(args, 'decoder_layers', convs) args.decoder_out_embed_dim = getattr(args, 'decoder_out_embed_dim', 512) base_architecture(args) @register_model_architecture('fconv', 'fconv_wmt_en_fr') def fconv_wmt_en_fr(args): convs = '[(512, 3)] * 6' # first 6 layers have 512 units convs += ' + [(768, 3)] * 4' # next 4 layers have 768 units convs += ' + [(1024, 3)] * 3' # next 3 layers have 1024 units convs += ' + [(2048, 1)] * 1' # next 1 layer uses 1x1 convolutions convs += ' + [(4096, 1)] * 1' # final 1 layer uses 1x1 convolutions args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 768) args.encoder_layers = getattr(args, 'encoder_layers', convs) args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 768) args.decoder_layers = getattr(args, 'decoder_layers', convs) args.decoder_out_embed_dim = getattr(args, 'decoder_out_embed_dim', 512) base_architecture(args)
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/models/fconv_self_att.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. # import math import torch import torch.nn as nn import torch.nn.functional as F from fairseq.modules import ( DownsampledMultiHeadAttention, GradMultiply, LearnedPositionalEmbedding, LinearizedConvolution, ) from fairseq import utils from . import ( FairseqEncoder, CompositeEncoder, FairseqDecoder, FairseqModel, register_model, register_model_architecture, ) @register_model('fconv_self_att') class FConvModelSelfAtt(FairseqModel): def __init__(self, encoder, decoder, pretrained_encoder=None): super().__init__(encoder, decoder) self.encoder.num_attention_layers = sum(layer is not None for layer in decoder.attention) self.pretrained_encoder = pretrained_encoder if self.pretrained_encoder is None: encoders = {'encoder': encoder} else: encoders = {'encoder': encoder, 'pretrained': self.pretrained_encoder} # for fusion model, CompositeEncoder contains both pretrained and training encoders # these are forwarded and then combined in the decoder self.encoder = CompositeEncoder(encoders) @staticmethod def add_args(parser): """Add model-specific arguments to the parser.""" parser.add_argument('--dropout', type=float, metavar='D', help='dropout probability') parser.add_argument('--encoder-embed-dim', type=int, metavar='N', help='encoder embedding dimension') parser.add_argument('--encoder-layers', type=str, metavar='EXPR', help='encoder layers [(dim, kernel_size), ...]') parser.add_argument('--decoder-embed-dim', type=int, metavar='N', help='decoder embedding dimension') parser.add_argument('--decoder-layers', type=str, metavar='EXPR', help='decoder layers [(dim, kernel_size), ...]') parser.add_argument('--decoder-out-embed-dim', type=int, metavar='N', help='decoder output embedding dimension') parser.add_argument('--decoder-attention', type=str, metavar='EXPR', help='decoder attention [True, ...]') parser.add_argument('--self-attention', type=str, metavar='EXPR', help='decoder self-attention layers, ex: [True] + [False]*5') parser.add_argument('--multihead-attention-nheads', type=int, help='Number of heads to use in attention') parser.add_argument('--multihead-self-attention-nheads', type=int, help='Number of heads to use in self-attention') parser.add_argument('--encoder-attention', type=str, metavar='EXPR', help='encoder attention [True, ...]') parser.add_argument('--encoder-attention-nheads', type=int, help='Number of heads to use in encoder attention') parser.add_argument('--project-input', type=str, metavar='EXPR', help='Use projections in self-attention [True, ...]') parser.add_argument('--gated-attention', type=str, metavar='EXPR', help='Use GLU layers in self-attention projections [True, ...]') parser.add_argument('--downsample', type=str, metavar='EXPR', help='Use downsampling in self-attention [True, ...]') parser.add_argument('--pretrained-checkpoint', metavar='DIR', help='path to load checkpoint from pretrained model') parser.add_argument('--pretrained', type=str, metavar='EXPR', help='use pretrained model when training [True, ...]') @classmethod def build_model(cls, args, task): trained_encoder, trained_decoder = None, None pretrained = eval(args.pretrained) if pretrained: print("| loading pretrained model") trained_model = utils.load_ensemble_for_inference( # not actually for inference, but loads pretrained model parameters filenames=[args.pretrained_checkpoint], task=task, )[0][0] trained_decoder = list(trained_model.children())[1] trained_encoder = list(trained_model.children())[0] # freeze pretrained model for param in trained_decoder.parameters(): param.requires_grad = False for param in trained_encoder.parameters(): param.requires_grad = False """Build a new model instance.""" encoder = FConvEncoder( task.source_dictionary, embed_dim=args.encoder_embed_dim, convolutions=eval(args.encoder_layers), dropout=args.dropout, max_positions=args.max_source_positions, attention=eval(args.encoder_attention), attention_nheads=args.encoder_attention_nheads ) decoder = FConvDecoder( task.target_dictionary, embed_dim=args.decoder_embed_dim, convolutions=eval(args.decoder_layers), out_embed_dim=args.decoder_out_embed_dim, attention=eval(args.decoder_attention), dropout=args.dropout, max_positions=args.max_target_positions, selfattention=eval(args.self_attention), attention_nheads=args.multihead_attention_nheads, selfattention_nheads=args.multihead_self_attention_nheads, project_input=eval(args.project_input), gated_attention=eval(args.gated_attention), downsample=eval(args.downsample), pretrained=pretrained, trained_decoder=trained_decoder ) model = FConvModelSelfAtt(encoder, decoder, trained_encoder) return model @property def pretrained(self): return self.pretrained_encoder is not None class FConvEncoder(FairseqEncoder): """Convolutional encoder""" def __init__( self, dictionary, embed_dim=512, max_positions=1024, convolutions=((512, 3),) * 20, dropout=0.1, attention=False, attention_nheads=1, left_pad=True, ): super().__init__(dictionary) self.dropout = dropout self.num_attention_layers = None self.left_pad = left_pad num_embeddings = len(dictionary) self.padding_idx = dictionary.pad() self.embed_tokens = Embedding(num_embeddings, embed_dim, self.padding_idx) self.embed_positions = PositionalEmbedding( max_positions, embed_dim, self.padding_idx, left_pad=self.left_pad, ) def expand_bool_array(val): if isinstance(val, bool): # expand True into [True, True, ...] and do the same with False return [val] * len(convolutions) return val attention = expand_bool_array(attention) in_channels = convolutions[0][0] self.fc1 = Linear(embed_dim, in_channels, dropout=dropout) self.projections = nn.ModuleList() self.convolutions = nn.ModuleList() self.attention = nn.ModuleList() self.attproj = nn.ModuleList() for i, (out_channels, kernel_size) in enumerate(convolutions): self.projections.append( Linear(in_channels, out_channels) if in_channels != out_channels else None ) self.convolutions.append( ConvTBC(in_channels, out_channels * 2, kernel_size, dropout=dropout) ) self.attention.append( SelfAttention(out_channels, embed_dim, attention_nheads) if attention[i] else None ) in_channels = out_channels self.fc2 = Linear(in_channels, embed_dim) def forward(self, src_tokens, src_lengths): # embed tokens and positions x = self.embed_tokens(src_tokens) + self.embed_positions(src_tokens) x = F.dropout(x, p=self.dropout, training=self.training) input_embedding = x.transpose(0, 1) # project to size of convolution x = self.fc1(x) # B x T x C -> T x B x C x = x.transpose(0, 1) # temporal convolutions for proj, conv, attention in zip(self.projections, self.convolutions, self.attention): residual = x if proj is None else proj(x) x = F.dropout(x, p=self.dropout, training=self.training) padding_l = (conv.kernel_size[0] - 1) // 2 padding_r = conv.kernel_size[0] // 2 x = F.pad(x, (0, 0, 0, 0, padding_l, padding_r)) x = conv(x) x = F.glu(x, dim=2) if attention is not None: x = attention(x) x = (x + residual) * math.sqrt(0.5) # T x B x C -> B x T x C x = x.transpose(1, 0) # project back to size of embedding x = self.fc2(x) # scale gradients (this only affects backward, not forward) x = GradMultiply.apply(x, 1.0 / (2.0 * self.num_attention_layers)) # add output to input embedding for attention y = (x + input_embedding.transpose(0, 1)) * math.sqrt(0.5) return { 'encoder_out': (x, y), } def reorder_encoder_out(self, encoder_out, new_order): encoder_out['encoder_out'] = tuple( eo.index_select(0, new_order) for eo in encoder_out['encoder_out'] ) if 'pretrained' in encoder_out: encoder_out['pretrained']['encoder_out'] = tuple( eo.index_select(0, new_order) for eo in encoder_out['pretrained']['encoder_out'] ) return encoder_out def max_positions(self): """Maximum input length supported by the encoder.""" return self.embed_positions.max_positions() class FConvDecoder(FairseqDecoder): """Convolutional decoder""" def __init__( self, dictionary, embed_dim=512, out_embed_dim=256, max_positions=1024, convolutions=((512, 3),) * 8, attention=True, dropout=0.1, selfattention=False, attention_nheads=1, selfattention_nheads=1, project_input=False, gated_attention=False, downsample=False, pretrained=False, trained_decoder=None, left_pad=False, ): super().__init__(dictionary) self.register_buffer('version', torch.Tensor([2])) self.pretrained = pretrained self.pretrained_decoder = trained_decoder self.dropout = dropout self.left_pad = left_pad self.need_attn = True in_channels = convolutions[0][0] def expand_bool_array(val): if isinstance(val, bool): # expand True into [True, True, ...] and do the same with False return [val] * len(convolutions) return val attention = expand_bool_array(attention) selfattention = expand_bool_array(selfattention) if not isinstance(attention, list) or len(attention) != len(convolutions): raise ValueError('Attention is expected to be a list of booleans of ' 'length equal to the number of layers.') num_embeddings = len(dictionary) padding_idx = dictionary.pad() self.embed_tokens = Embedding(num_embeddings, embed_dim, padding_idx) self.embed_positions = PositionalEmbedding( max_positions, embed_dim, padding_idx, left_pad=self.left_pad, ) self.fc1 = Linear(embed_dim, in_channels, dropout=dropout) self.projections = nn.ModuleList() self.convolutions = nn.ModuleList() self.attention = nn.ModuleList() self.selfattention = nn.ModuleList() self.attproj = nn.ModuleList() for i, (out_channels, kernel_size) in enumerate(convolutions): self.projections.append( Linear(in_channels, out_channels) if in_channels != out_channels else None ) self.convolutions.append( LinearizedConv1d( in_channels, out_channels * 2, kernel_size, padding=(kernel_size - 1), dropout=dropout, ) ) self.attention.append( DownsampledMultiHeadAttention( out_channels, embed_dim, attention_nheads, project_input=project_input, gated=False, downsample=False, ) if attention[i] else None ) self.attproj.append( Linear(out_channels, embed_dim, dropout=dropout) if attention[i] else None ) self.selfattention.append( SelfAttention( out_channels, embed_dim, selfattention_nheads, project_input=project_input, gated=gated_attention, downsample=downsample, ) if selfattention[i] else None ) in_channels = out_channels self.fc2 = Linear(in_channels, out_embed_dim) self.fc3 = Linear(out_embed_dim, num_embeddings, dropout=dropout) # model fusion if self.pretrained: # independent gates are learned from the concatenated input self.gate1 = nn.Sequential(Linear(out_embed_dim*2, out_embed_dim), nn.Sigmoid()) self.gate2 = nn.Sequential(Linear(out_embed_dim*2, out_embed_dim), nn.Sigmoid()) # pretrained and trained models are joined self.joining = nn.Sequential( Linear(out_embed_dim*2, out_embed_dim*2), nn.LayerNorm(out_embed_dim*2), nn.GLU(), Linear(out_embed_dim, out_embed_dim*2), nn.LayerNorm(out_embed_dim*2), nn.GLU(), Linear(out_embed_dim, out_embed_dim), nn.LayerNorm(out_embed_dim) ) # pretrained model contains an output layer that is nhid -> vocab size # but the models are combined in their hidden state # the hook stores the output of the pretrained model forward self.pretrained_outputs = {} def save_output(): def hook(a, b, output): self.pretrained_outputs["out"] = output return hook self.pretrained_decoder.fc2.register_forward_hook(save_output()) def forward(self, prev_output_tokens, encoder_out_dict): encoder_out = encoder_out_dict['encoder']['encoder_out'] trained_encoder_out = encoder_out_dict['pretrained'] if self.pretrained else None encoder_a, encoder_b = self._split_encoder_out(encoder_out) # embed positions positions = self.embed_positions(prev_output_tokens) # embed tokens and positions x = self.embed_tokens(prev_output_tokens) + positions x = F.dropout(x, p=self.dropout, training=self.training) target_embedding = x.transpose(0, 1) # project to size of convolution x = self.fc1(x) # B x T x C -> T x B x C x = x.transpose(0, 1) # temporal convolutions avg_attn_scores = None for proj, conv, attention, selfattention, attproj in zip( self.projections, self.convolutions, self.attention, self.selfattention, self.attproj ): residual = x if proj is None else proj(x) x = F.dropout(x, p=self.dropout, training=self.training) x = conv(x) x = F.glu(x, dim=2) # attention if attention is not None: r = x x, attn_scores = attention(attproj(x) + target_embedding, encoder_a, encoder_b) x = x + r if not self.training and self.need_attn: if avg_attn_scores is None: avg_attn_scores = attn_scores else: avg_attn_scores.add_(attn_scores) if selfattention is not None: x = selfattention(x) x = (x + residual) * math.sqrt(0.5) # T x B x C -> B x T x C x = x.transpose(0, 1) # project back to size of vocabulary x = self.fc2(x) x = F.dropout(x, p=self.dropout, training=self.training) if not self.pretrained: x = self.fc3(x) # fusion gating if self.pretrained: trained_x, _ = self.pretrained_decoder.forward(prev_output_tokens, trained_encoder_out) y = torch.cat([x, self.pretrained_outputs["out"]], dim=-1) gate1 = self.gate1(y) gate2 = self.gate2(y) gated_x1 = gate1 * x gated_x2 = gate2 * self.pretrained_outputs["out"] fusion = torch.cat([gated_x1, gated_x2], dim=-1) fusion = self.joining(fusion) fusion_output = self.fc3(fusion) return fusion_output, avg_attn_scores else: return x, avg_attn_scores def max_positions(self): """Maximum output length supported by the decoder.""" return self.embed_positions.max_positions() def make_generation_fast_(self, need_attn=False, **kwargs): self.need_attn = need_attn def _split_encoder_out(self, encoder_out): """Split and transpose encoder outputs.""" # transpose only once to speed up attention layers encoder_a, encoder_b = encoder_out encoder_a = encoder_a.transpose(0, 1).contiguous() encoder_b = encoder_b.transpose(0, 1).contiguous() result = (encoder_a, encoder_b) return result class SelfAttention(nn.Module): def __init__(self, out_channels, embed_dim, num_heads, project_input=False, gated=False, downsample=False): super().__init__() self.attention = DownsampledMultiHeadAttention( out_channels, embed_dim, num_heads, dropout=0, bias=True, project_input=project_input, gated=gated, downsample=downsample, ) self.in_proj_q = Linear(out_channels, embed_dim) self.in_proj_k = Linear(out_channels, embed_dim) self.in_proj_v = Linear(out_channels, embed_dim) self.ln = nn.LayerNorm(out_channels) def forward(self, x): residual = x query = self.in_proj_q(x) key = self.in_proj_k(x) value = self.in_proj_v(x) x, _ = self.attention(query, key, value, mask_future_timesteps=True, use_scalar_bias=True) return self.ln(x + residual) def Embedding(num_embeddings, embedding_dim, padding_idx): m = nn.Embedding(num_embeddings, embedding_dim, padding_idx=padding_idx) m.weight.data.normal_(0, 0.1) return m def PositionalEmbedding(num_embeddings, embedding_dim, padding_idx, left_pad): m = LearnedPositionalEmbedding(num_embeddings, embedding_dim, padding_idx, left_pad) m.weight.data.normal_(0, 0.1) return m def Linear(in_features, out_features, dropout=0.): """Weight-normalized Linear layer (input: N x T x C)""" m = nn.Linear(in_features, out_features) m.weight.data.normal_(mean=0, std=math.sqrt((1 - dropout) / in_features)) m.bias.data.zero_() return m def LinearizedConv1d(in_channels, out_channels, kernel_size, dropout=0., **kwargs): """Weight-normalized Conv1d layer optimized for decoding""" m = LinearizedConvolution(in_channels, out_channels, kernel_size, **kwargs) std = math.sqrt((4 * (1.0 - dropout)) / (m.kernel_size[0] * in_channels)) m.weight.data.normal_(mean=0, std=std) m.bias.data.zero_() return m def ConvTBC(in_channels, out_channels, kernel_size, dropout=0, **kwargs): """Weight-normalized Conv1d layer""" from fairseq.modules import ConvTBC m = ConvTBC(in_channels, out_channels, kernel_size, **kwargs) std = math.sqrt((4 * (1.0 - dropout)) / (m.kernel_size[0] * in_channels)) m.weight.data.normal_(mean=0, std=std) m.bias.data.zero_() return m @register_model_architecture('fconv_self_att', 'fconv_self_att') def base_architecture(args): args.dropout = getattr(args, 'dropout', 0.1) args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 512) args.encoder_layers = getattr(args, 'encoder_layers', '[(512, 3)] * 3') args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 512) args.decoder_layers = getattr(args, 'decoder_layers', '[(512, 3)] * 8') args.decoder_out_embed_dim = getattr(args, 'decoder_out_embed_dim', 256) args.decoder_attention = getattr(args, 'decoder_attention', 'True') args.self_attention = getattr(args, 'self_attention', 'False') args.encoder_attention = getattr(args, 'encoder_attention', 'False') args.multihead_attention_nheads = getattr(args, 'multihead_attention_nheads', 1) args.multihead_self_attention_nheads = getattr(args, 'multihead_self_attention_nheads', 1) args.encoder_attention_nheads = getattr(args, 'encoder_attention_nheads', 1) args.project_input = getattr(args, 'project_input', 'False') args.gated_attention = getattr(args, 'gated_attention', 'False') args.downsample = getattr(args, 'downsample', 'False') args.pretrained_checkpoint = getattr(args, 'pretrained_checkpoint', '') args.pretrained = getattr(args, 'pretrained', 'False') @register_model_architecture('fconv_self_att', 'fconv_self_att_wp') def fconv_self_att_wp(args): args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 256) args.encoder_layers = getattr(args, 'encoder_layers', '[(128, 3)] * 2 + [(512,3)] * 1') args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 256) args.decoder_layers = getattr(args, 'decoder_layers', '[(512, 4)] * 4 + [(768, 4)] * 2 + [(1024, 4)] * 1') args.decoder_out_embed_dim = getattr(args, 'decoder_out_embed_dim', 256) args.self_attention = getattr(args, 'self_attention', 'True') args.multihead_self_attention_nheads = getattr(args, 'multihead_self_attention_nheads', 4) args.project_input = getattr(args, 'project_input', 'True') args.gated_attention = getattr(args, 'gated_attention', 'True') args.downsample = getattr(args, 'downsample', 'True') base_architecture(args)
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/models/lstm.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import torch import torch.nn as nn import torch.nn.functional as F from fairseq import options, utils from fairseq.modules import AdaptiveSoftmax from . import ( FairseqEncoder, FairseqIncrementalDecoder, FairseqModel, register_model, register_model_architecture, ) @register_model('lstm') class LSTMModel(FairseqModel): def __init__(self, encoder, decoder): super().__init__(encoder, decoder) @staticmethod def add_args(parser): """Add model-specific arguments to the parser.""" parser.add_argument('--dropout', type=float, metavar='D', help='dropout probability') parser.add_argument('--encoder-embed-dim', type=int, metavar='N', help='encoder embedding dimension') parser.add_argument('--encoder-embed-path', type=str, metavar='STR', help='path to pre-trained encoder embedding') parser.add_argument('--encoder-hidden-size', type=int, metavar='N', help='encoder hidden size') parser.add_argument('--encoder-layers', type=int, metavar='N', help='number of encoder layers') parser.add_argument('--encoder-bidirectional', action='store_true', help='make all layers of encoder bidirectional') parser.add_argument('--decoder-embed-dim', type=int, metavar='N', help='decoder embedding dimension') parser.add_argument('--decoder-embed-path', type=str, metavar='STR', help='path to pre-trained decoder embedding') parser.add_argument('--decoder-hidden-size', type=int, metavar='N', help='decoder hidden size') parser.add_argument('--decoder-layers', type=int, metavar='N', help='number of decoder layers') parser.add_argument('--decoder-out-embed-dim', type=int, metavar='N', help='decoder output embedding dimension') parser.add_argument('--decoder-attention', type=str, metavar='BOOL', help='decoder attention') parser.add_argument('--adaptive-softmax-cutoff', metavar='EXPR', help='comma separated list of adaptive softmax cutoff points. ' 'Must be used with adaptive_loss criterion') # Granular dropout settings (if not specified these default to --dropout) parser.add_argument('--encoder-dropout-in', type=float, metavar='D', help='dropout probability for encoder input embedding') parser.add_argument('--encoder-dropout-out', type=float, metavar='D', help='dropout probability for encoder output') parser.add_argument('--decoder-dropout-in', type=float, metavar='D', help='dropout probability for decoder input embedding') parser.add_argument('--decoder-dropout-out', type=float, metavar='D', help='dropout probability for decoder output') parser.add_argument('--share-decoder-input-output-embed', default=False, action='store_true', help='share decoder input and output embeddings') parser.add_argument('--share-all-embeddings', default=False, action='store_true', help='share encoder, decoder and output embeddings' ' (requires shared dictionary and embed dim)') @classmethod def build_model(cls, args, task): """Build a new model instance.""" # make sure that all args are properly defaulted (in case there are any new ones) base_architecture(args) def load_pretrained_embedding_from_file(embed_path, dictionary, embed_dim): num_embeddings = len(dictionary) padding_idx = dictionary.pad() embed_tokens = Embedding(num_embeddings, embed_dim, padding_idx) embed_dict = utils.parse_embedding(embed_path) utils.print_embed_overlap(embed_dict, dictionary) return utils.load_embedding(embed_dict, dictionary, embed_tokens) if args.encoder_embed_path: pretrained_encoder_embed = load_pretrained_embedding_from_file( args.encoder_embed_path, task.source_dictionary, args.encoder_embed_dim) else: num_embeddings = len(task.source_dictionary) pretrained_encoder_embed = Embedding( num_embeddings, args.encoder_embed_dim, task.source_dictionary.pad() ) if args.share_all_embeddings: # double check all parameters combinations are valid if task.source_dictionary != task.target_dictionary: raise RuntimeError('--share-all-embeddings requires a joint dictionary') if args.decoder_embed_path and ( args.decoder_embed_path != args.encoder_embed_path): raise RuntimeError( '--share-all-embed not compatible with --decoder-embed-path' ) if args.encoder_embed_dim != args.decoder_embed_dim: raise RuntimeError( '--share-all-embeddings requires --encoder-embed-dim to ' 'match --decoder-embed-dim' ) pretrained_decoder_embed = pretrained_encoder_embed args.share_decoder_input_output_embed = True else: # separate decoder input embeddings pretrained_decoder_embed = None if args.decoder_embed_path: pretrained_decoder_embed = load_pretrained_embedding_from_file( args.decoder_embed_path, task.target_dictionary, args.decoder_embed_dim ) # one last double check of parameter combinations if args.share_decoder_input_output_embed and ( args.decoder_embed_dim != args.decoder_out_embed_dim): raise RuntimeError( '--share-decoder-input-output-embeddings requires ' '--decoder-embed-dim to match --decoder-out-embed-dim' ) encoder = LSTMEncoder( dictionary=task.source_dictionary, embed_dim=args.encoder_embed_dim, hidden_size=args.encoder_hidden_size, num_layers=args.encoder_layers, dropout_in=args.encoder_dropout_in, dropout_out=args.encoder_dropout_out, bidirectional=args.encoder_bidirectional, pretrained_embed=pretrained_encoder_embed, ) decoder = LSTMDecoder( dictionary=task.target_dictionary, embed_dim=args.decoder_embed_dim, hidden_size=args.decoder_hidden_size, out_embed_dim=args.decoder_out_embed_dim, num_layers=args.decoder_layers, dropout_in=args.decoder_dropout_in, dropout_out=args.decoder_dropout_out, attention=options.eval_bool(args.decoder_attention), encoder_embed_dim=args.encoder_embed_dim, encoder_output_units=encoder.output_units, pretrained_embed=pretrained_decoder_embed, share_input_output_embed=args.share_decoder_input_output_embed, adaptive_softmax_cutoff=( options.eval_str_list(args.adaptive_softmax_cutoff, type=int) if args.criterion == 'adaptive_loss' else None ), ) return cls(encoder, decoder) class LSTMEncoder(FairseqEncoder): """LSTM encoder.""" def __init__( self, dictionary, embed_dim=512, hidden_size=512, num_layers=1, dropout_in=0.1, dropout_out=0.1, bidirectional=False, left_pad=True, pretrained_embed=None, padding_value=0., ): super().__init__(dictionary) self.num_layers = num_layers self.dropout_in = dropout_in self.dropout_out = dropout_out self.bidirectional = bidirectional self.hidden_size = hidden_size num_embeddings = len(dictionary) self.padding_idx = dictionary.pad() if pretrained_embed is None: self.embed_tokens = Embedding(num_embeddings, embed_dim, self.padding_idx) else: self.embed_tokens = pretrained_embed self.lstm = LSTM( input_size=embed_dim, hidden_size=hidden_size, num_layers=num_layers, dropout=self.dropout_out if num_layers > 1 else 0., bidirectional=bidirectional, ) self.left_pad = left_pad self.padding_value = padding_value self.output_units = hidden_size if bidirectional: self.output_units *= 2 def forward(self, src_tokens, src_lengths): if self.left_pad: # convert left-padding to right-padding src_tokens = utils.convert_padding_direction( src_tokens, self.padding_idx, left_to_right=True, ) bsz, seqlen = src_tokens.size() # embed tokens x = self.embed_tokens(src_tokens) x = F.dropout(x, p=self.dropout_in, training=self.training) # B x T x C -> T x B x C x = x.transpose(0, 1) # pack embedded source tokens into a PackedSequence packed_x = nn.utils.rnn.pack_padded_sequence(x, src_lengths.data.tolist()) # apply LSTM if self.bidirectional: state_size = 2 * self.num_layers, bsz, self.hidden_size else: state_size = self.num_layers, bsz, self.hidden_size h0 = x.data.new(*state_size).zero_() c0 = x.data.new(*state_size).zero_() packed_outs, (final_hiddens, final_cells) = self.lstm(packed_x, (h0, c0)) # unpack outputs and apply dropout x, _ = nn.utils.rnn.pad_packed_sequence(packed_outs, padding_value=self.padding_value) x = F.dropout(x, p=self.dropout_out, training=self.training) assert list(x.size()) == [seqlen, bsz, self.output_units] if self.bidirectional: def combine_bidir(outs): return outs.view(self.num_layers, 2, bsz, -1).transpose(1, 2).contiguous().view(self.num_layers, bsz, -1) final_hiddens = combine_bidir(final_hiddens) final_cells = combine_bidir(final_cells) encoder_padding_mask = src_tokens.eq(self.padding_idx).t() return { 'encoder_out': (x, final_hiddens, final_cells), 'encoder_padding_mask': encoder_padding_mask if encoder_padding_mask.any() else None } def reorder_encoder_out(self, encoder_out, new_order): encoder_out['encoder_out'] = tuple( eo.index_select(1, new_order) for eo in encoder_out['encoder_out'] ) if encoder_out['encoder_padding_mask'] is not None: encoder_out['encoder_padding_mask'] = \ encoder_out['encoder_padding_mask'].index_select(1, new_order) return encoder_out def max_positions(self): """Maximum input length supported by the encoder.""" return int(1e5) # an arbitrary large number class AttentionLayer(nn.Module): def __init__(self, input_embed_dim, output_embed_dim): super().__init__() self.input_proj = Linear(input_embed_dim, output_embed_dim, bias=False) self.output_proj = Linear(input_embed_dim + output_embed_dim, output_embed_dim, bias=False) def forward(self, input, source_hids, encoder_padding_mask): # input: bsz x input_embed_dim # source_hids: srclen x bsz x output_embed_dim # x: bsz x output_embed_dim x = self.input_proj(input) # compute attention attn_scores = (source_hids * x.unsqueeze(0)).sum(dim=2) # don't attend over padding if encoder_padding_mask is not None: attn_scores = attn_scores.float().masked_fill_( encoder_padding_mask, float('-inf') ).type_as(attn_scores) # FP16 support: cast to float and back attn_scores = F.softmax(attn_scores, dim=0) # srclen x bsz # sum weighted sources x = (attn_scores.unsqueeze(2) * source_hids).sum(dim=0) x = F.tanh(self.output_proj(torch.cat((x, input), dim=1))) return x, attn_scores class LSTMDecoder(FairseqIncrementalDecoder): """LSTM decoder.""" def __init__( self, dictionary, embed_dim=512, hidden_size=512, out_embed_dim=512, num_layers=1, dropout_in=0.1, dropout_out=0.1, attention=True, encoder_embed_dim=512, encoder_output_units=512, pretrained_embed=None, share_input_output_embed=False, adaptive_softmax_cutoff=None, ): super().__init__(dictionary) self.dropout_in = dropout_in self.dropout_out = dropout_out self.hidden_size = hidden_size self.share_input_output_embed = share_input_output_embed self.need_attn = True self.adaptive_softmax = None num_embeddings = len(dictionary) padding_idx = dictionary.pad() if pretrained_embed is None: self.embed_tokens = Embedding(num_embeddings, embed_dim, padding_idx) else: self.embed_tokens = pretrained_embed self.encoder_output_units = encoder_output_units assert encoder_output_units == hidden_size, \ 'encoder_output_units ({}) != hidden_size ({})'.format(encoder_output_units, hidden_size) # TODO another Linear layer if not equal self.layers = nn.ModuleList([ LSTMCell( input_size=encoder_output_units + embed_dim if layer == 0 else hidden_size, hidden_size=hidden_size, ) for layer in range(num_layers) ]) self.attention = AttentionLayer(encoder_output_units, hidden_size) if attention else None if hidden_size != out_embed_dim: self.additional_fc = Linear(hidden_size, out_embed_dim) if adaptive_softmax_cutoff is not None: # setting adaptive_softmax dropout to dropout_out for now but can be redefined self.adaptive_softmax = AdaptiveSoftmax(num_embeddings, embed_dim, adaptive_softmax_cutoff, dropout=dropout_out) elif not self.share_input_output_embed: self.fc_out = Linear(out_embed_dim, num_embeddings, dropout=dropout_out) def forward(self, prev_output_tokens, encoder_out_dict, incremental_state=None): encoder_out = encoder_out_dict['encoder_out'] encoder_padding_mask = encoder_out_dict['encoder_padding_mask'] if incremental_state is not None: prev_output_tokens = prev_output_tokens[:, -1:] bsz, seqlen = prev_output_tokens.size() # get outputs from encoder encoder_outs, _, _ = encoder_out[:3] srclen = encoder_outs.size(0) # embed tokens x = self.embed_tokens(prev_output_tokens) x = F.dropout(x, p=self.dropout_in, training=self.training) # B x T x C -> T x B x C x = x.transpose(0, 1) # initialize previous states (or get from cache during incremental generation) cached_state = utils.get_incremental_state(self, incremental_state, 'cached_state') if cached_state is not None: prev_hiddens, prev_cells, input_feed = cached_state else: _, encoder_hiddens, encoder_cells = encoder_out[:3] num_layers = len(self.layers) prev_hiddens = [encoder_hiddens[i] for i in range(num_layers)] prev_cells = [encoder_cells[i] for i in range(num_layers)] input_feed = x.data.new(bsz, self.encoder_output_units).zero_() attn_scores = x.data.new(srclen, seqlen, bsz).zero_() outs = [] for j in range(seqlen): # input feeding: concatenate context vector from previous time step input = torch.cat((x[j, :, :], input_feed), dim=1) for i, rnn in enumerate(self.layers): # recurrent cell hidden, cell = rnn(input, (prev_hiddens[i], prev_cells[i])) # hidden state becomes the input to the next layer input = F.dropout(hidden, p=self.dropout_out, training=self.training) # save state for next time step prev_hiddens[i] = hidden prev_cells[i] = cell # apply attention using the last layer's hidden state if self.attention is not None: out, attn_scores[:, j, :] = self.attention(hidden, encoder_outs, encoder_padding_mask) else: out = hidden out = F.dropout(out, p=self.dropout_out, training=self.training) # input feeding input_feed = out # save final output outs.append(out) # cache previous states (no-op except during incremental generation) utils.set_incremental_state( self, incremental_state, 'cached_state', (prev_hiddens, prev_cells, input_feed)) # collect outputs across time steps x = torch.cat(outs, dim=0).view(seqlen, bsz, self.hidden_size) # T x B x C -> B x T x C x = x.transpose(1, 0) # srclen x tgtlen x bsz -> bsz x tgtlen x srclen if not self.training and self.need_attn: attn_scores = attn_scores.transpose(0, 2) else: attn_scores = None # project back to size of vocabulary if self.adaptive_softmax is None: if hasattr(self, 'additional_fc'): x = self.additional_fc(x) x = F.dropout(x, p=self.dropout_out, training=self.training) if self.share_input_output_embed: x = F.linear(x, self.embed_tokens.weight) else: x = self.fc_out(x) return x, attn_scores def reorder_incremental_state(self, incremental_state, new_order): super().reorder_incremental_state(incremental_state, new_order) cached_state = utils.get_incremental_state(self, incremental_state, 'cached_state') if cached_state is None: return def reorder_state(state): if isinstance(state, list): return [reorder_state(state_i) for state_i in state] return state.index_select(0, new_order) new_state = tuple(map(reorder_state, cached_state)) utils.set_incremental_state(self, incremental_state, 'cached_state', new_state) def max_positions(self): """Maximum output length supported by the decoder.""" return int(1e5) # an arbitrary large number def make_generation_fast_(self, need_attn=False, **kwargs): self.need_attn = need_attn def Embedding(num_embeddings, embedding_dim, padding_idx): m = nn.Embedding(num_embeddings, embedding_dim, padding_idx=padding_idx) nn.init.uniform_(m.weight, -0.1, 0.1) nn.init.constant_(m.weight[padding_idx], 0) return m def LSTM(input_size, hidden_size, **kwargs): m = nn.LSTM(input_size, hidden_size, **kwargs) for name, param in m.named_parameters(): if 'weight' in name or 'bias' in name: param.data.uniform_(-0.1, 0.1) return m def LSTMCell(input_size, hidden_size, **kwargs): m = nn.LSTMCell(input_size, hidden_size, **kwargs) for name, param in m.named_parameters(): if 'weight' in name or 'bias' in name: param.data.uniform_(-0.1, 0.1) return m def Linear(in_features, out_features, bias=True, dropout=0): """Linear layer (input: N x T x C)""" m = nn.Linear(in_features, out_features, bias=bias) m.weight.data.uniform_(-0.1, 0.1) if bias: m.bias.data.uniform_(-0.1, 0.1) return m @register_model_architecture('lstm', 'lstm') def base_architecture(args): args.dropout = getattr(args, 'dropout', 0.1) args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 512) args.encoder_embed_path = getattr(args, 'encoder_embed_path', None) args.encoder_hidden_size = getattr(args, 'encoder_hidden_size', args.encoder_embed_dim) args.encoder_layers = getattr(args, 'encoder_layers', 1) args.encoder_bidirectional = getattr(args, 'encoder_bidirectional', False) args.encoder_dropout_in = getattr(args, 'encoder_dropout_in', args.dropout) args.encoder_dropout_out = getattr(args, 'encoder_dropout_out', args.dropout) args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 512) args.decoder_embed_path = getattr(args, 'decoder_embed_path', None) args.decoder_hidden_size = getattr(args, 'decoder_hidden_size', args.decoder_embed_dim) args.decoder_layers = getattr(args, 'decoder_layers', 1) args.decoder_out_embed_dim = getattr(args, 'decoder_out_embed_dim', 512) args.decoder_attention = getattr(args, 'decoder_attention', '1') args.decoder_dropout_in = getattr(args, 'decoder_dropout_in', args.dropout) args.decoder_dropout_out = getattr(args, 'decoder_dropout_out', args.dropout) args.share_decoder_input_output_embed = getattr(args, 'share_decoder_input_output_embed', False) args.share_all_embeddings = getattr(args, 'share_all_embeddings', False) args.adaptive_softmax_cutoff = getattr(args, 'adaptive_softmax_cutoff', '10000,50000,200000') @register_model_architecture('lstm', 'lstm_wiseman_iwslt_de_en') def lstm_wiseman_iwslt_de_en(args): args.dropout = getattr(args, 'dropout', 0.1) args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 256) args.encoder_dropout_in = getattr(args, 'encoder_dropout_in', 0) args.encoder_dropout_out = getattr(args, 'encoder_dropout_out', 0) args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 256) args.decoder_out_embed_dim = getattr(args, 'decoder_out_embed_dim', 256) args.decoder_dropout_in = getattr(args, 'decoder_dropout_in', 0) args.decoder_dropout_out = getattr(args, 'decoder_dropout_out', args.dropout) base_architecture(args) @register_model_architecture('lstm', 'lstm_luong_wmt_en_de') def lstm_luong_wmt_en_de(args): args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 1000) args.encoder_layers = getattr(args, 'encoder_layers', 4) args.encoder_dropout_out = getattr(args, 'encoder_dropout_out', 0) args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 1000) args.decoder_layers = getattr(args, 'decoder_layers', 4) args.decoder_out_embed_dim = getattr(args, 'decoder_out_embed_dim', 1000) args.decoder_dropout_out = getattr(args, 'decoder_dropout_out', 0) base_architecture(args)
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/models/transformer.py
Python
# Modified by Zhuohan Li in May 2019 for macaron-net # # Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import math import torch import torch.nn as nn import torch.nn.functional as F from fairseq import options from fairseq import utils from fairseq.modules import ( AdaptiveSoftmax, CharacterTokenEmbedder, LearnedPositionalEmbedding, MultiheadAttention, SinusoidalPositionalEmbedding ) from . import ( FairseqIncrementalDecoder, FairseqEncoder, FairseqLanguageModel, FairseqModel, register_model, register_model_architecture, FairseqBertModel, FairseqClassifierModel ) def gelu(x): return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0))) class GeLU(nn.Module): def __init__(self): super(GeLU, self).__init__() def forward(self, input): return gelu(input) def _get_activation(s, module=False): if s == 'relu': if module: return nn.ReLU else: return F.relu elif s == 'gelu': if module: return GeLU else: return gelu else: raise NotImplementedError(f"Unrecognized activation {s}") @register_model('transformer') class TransformerModel(FairseqModel): """ Transformer model from `"Attention Is All You Need" (Vaswani, et al, 2017) <https://arxiv.org/abs/1706.03762>`_. Args: encoder (TransformerEncoder): the encoder decoder (TransformerDecoder): the decoder The Transformer model provides the following named architectures and command-line arguments: .. argparse:: :ref: fairseq.models.transformer_parser :prog: """ def __init__(self, encoder, decoder): super().__init__(encoder, decoder) @staticmethod def add_args(parser): """Add model-specific arguments to the parser.""" parser.add_argument('--dropout', type=float, metavar='D', help='dropout probability') parser.add_argument('--attention-dropout', type=float, metavar='D', help='dropout probability for attention weights') parser.add_argument('--relu-dropout', type=float, metavar='D', help='dropout probability after ReLU in FFN') parser.add_argument('--encoder-embed-path', type=str, metavar='STR', help='path to pre-trained encoder embedding') parser.add_argument('--encoder-embed-dim', type=int, metavar='N', help='encoder embedding dimension') parser.add_argument('--encoder-ffn-embed-dim', type=int, metavar='N', help='encoder embedding dimension for FFN') parser.add_argument('--encoder-layers', type=int, metavar='N', help='num encoder layers') parser.add_argument('--encoder-attention-heads', type=int, metavar='N', help='num encoder attention heads') parser.add_argument('--encoder-normalize-before', action='store_true', help='apply layernorm before each encoder block') parser.add_argument('--encoder-learned-pos', action='store_true', help='use learned positional embeddings in the encoder') parser.add_argument('--decoder-embed-path', type=str, metavar='STR', help='path to pre-trained decoder embedding') parser.add_argument('--decoder-embed-dim', type=int, metavar='N', help='decoder embedding dimension') parser.add_argument('--decoder-ffn-embed-dim', type=int, metavar='N', help='decoder embedding dimension for FFN') parser.add_argument('--decoder-layers', type=int, metavar='N', help='num decoder layers') parser.add_argument('--decoder-attention-heads', type=int, metavar='N', help='num decoder attention heads') parser.add_argument('--decoder-learned-pos', action='store_true', help='use learned positional embeddings in the decoder') parser.add_argument('--decoder-normalize-before', action='store_true', help='apply layernorm before each decoder block') parser.add_argument('--share-decoder-input-output-embed', action='store_true', help='share decoder input and output embeddings') parser.add_argument('--share-all-embeddings', action='store_true', help='share encoder, decoder and output embeddings' ' (requires shared dictionary and embed dim)') parser.add_argument('--adaptive-softmax-cutoff', metavar='EXPR', help='comma separated list of adaptive softmax cutoff points. ' 'Must be used with adaptive_loss criterion'), parser.add_argument('--adaptive-softmax-dropout', type=float, metavar='D', help='sets adaptive softmax dropout for the tail projections') parser.add_argument('--act-fn', type=str, metavar='STR', help='name of the activation function') parser.add_argument('--no-normalize-affine', action='store_true', help='do not add affine transformation after layer normalization') parser.add_argument('--macaron', action='store_true', help='use the macaron network') @classmethod def build_model(cls, args, task): """Build a new model instance.""" # make sure all arguments are present in older models base_architecture(args) if not hasattr(args, 'max_source_positions'): args.max_source_positions = 1024 if not hasattr(args, 'max_target_positions'): args.max_target_positions = 1024 src_dict, tgt_dict = task.source_dictionary, task.target_dictionary def build_embedding(dictionary, embed_dim, path=None): num_embeddings = len(dictionary) padding_idx = dictionary.pad() emb = Embedding(num_embeddings, embed_dim, padding_idx) # if provided, load from preloaded dictionaries if path: embed_dict = utils.parse_embedding(path) utils.load_embedding(embed_dict, dictionary, emb) return emb if args.share_all_embeddings: if src_dict != tgt_dict: raise RuntimeError('--share-all-embeddings requires a joined dictionary') if args.encoder_embed_dim != args.decoder_embed_dim: raise RuntimeError( '--share-all-embeddings requires --encoder-embed-dim to match --decoder-embed-dim') if args.decoder_embed_path and ( args.decoder_embed_path != args.encoder_embed_path): raise RuntimeError('--share-all-embeddings not compatible with --decoder-embed-path') encoder_embed_tokens = build_embedding( src_dict, args.encoder_embed_dim, args.encoder_embed_path ) decoder_embed_tokens = encoder_embed_tokens args.share_decoder_input_output_embed = True else: encoder_embed_tokens = build_embedding( src_dict, args.encoder_embed_dim, args.encoder_embed_path ) decoder_embed_tokens = build_embedding( tgt_dict, args.decoder_embed_dim, args.decoder_embed_path ) encoder = TransformerEncoder(args, src_dict, encoder_embed_tokens) decoder = TransformerDecoder(args, tgt_dict, decoder_embed_tokens) return TransformerModel(encoder, decoder) @register_model('transformer_bert') class TransformerBertModel(FairseqBertModel): def __init__(self, encoder, mid_layer, embed_out, feature_dim): super().__init__(encoder, mid_layer, embed_out, feature_dim) @staticmethod def add_args(parser): """Add model-specific arguments to the parser.""" parser.add_argument('--dropout', type=float, metavar='D', help='dropout probability') parser.add_argument('--attention-dropout', type=float, metavar='D', help='dropout probability for attention weights') parser.add_argument('--relu-dropout', type=float, metavar='D', help='dropout probability after ReLU in FFN') parser.add_argument('--encoder-embed-path', type=str, metavar='STR', help='path to pre-trained encoder embedding') parser.add_argument('--encoder-embed-dim', type=int, metavar='N', help='encoder embedding dimension') parser.add_argument('--encoder-ffn-embed-dim', type=int, metavar='N', help='encoder embedding dimension for FFN') parser.add_argument('--encoder-layers', type=int, metavar='N', help='num encoder layers') parser.add_argument('--encoder-attention-heads', type=int, metavar='N', help='num encoder attention heads') parser.add_argument('--encoder-normalize-before', action='store_true', help='apply layernorm before each encoder block') parser.add_argument('--encoder-learned-pos', action='store_true', help='use learned positional embeddings in the encoder') parser.add_argument('--share-all-embeddings', action='store_true', help='share encoder, decoder and output embeddings' ' (requires shared dictionary and embed dim)') parser.add_argument('--act-fn', type=str, metavar='STR', help='name of the activation function') parser.add_argument('--macaron', action='store_true', help='use the macaron network') @classmethod def build_model(cls, args, task): """Build a new model instance.""" # make sure all arguments are present in older models base_bert_architecture(args) if not hasattr(args, 'max_positions'): args.max_positions = 384 args.max_source_positions = args.max_positions dictionary = task.dict def build_embedding(dictionary, embed_dim, path=None): num_embeddings = len(dictionary) padding_idx = dictionary.pad() emb = Embedding(num_embeddings, embed_dim, padding_idx) # if provided, load from preloaded dictionaries if path: embed_dict = utils.parse_embedding(path) utils.load_embedding(embed_dict, dictionary, emb) return emb embed_tokens = build_embedding( dictionary, args.encoder_embed_dim, args.encoder_embed_path ) encoder = TransformerEncoder(args, dictionary, embed_tokens, left_pad=False, require_segment=True) mid_layer = nn.Sequential( nn.Linear(args.encoder_embed_dim, args.encoder_embed_dim), _get_activation(args.act_fn, module=True)(), LayerNorm(args.encoder_embed_dim, elementwise_affine=True) ) if not args.share_all_embeddings: embed_out = nn.Parameter(torch.Tensor(len(dictionary), args.encoder_embed_dim)) nn.init.normal_(embed_out, mean=0, std=args.encoder_embed_dim ** -0.5) return TransformerBertModel(encoder, mid_layer, embed_out, args.encoder_embed_dim) else: return TransformerBertModel(encoder, mid_layer, embed_tokens.weight, args.encoder_embed_dim) @register_model('transformer_classifier') class TransformerClassifierModel(FairseqClassifierModel): def __init__(self, encoder, feature_dim, n_classes): super().__init__(encoder, feature_dim, n_classes) @staticmethod def add_args(parser): """Add model-specific arguments to the parser.""" parser.add_argument('--dropout', type=float, metavar='D', help='dropout probability') parser.add_argument('--attention-dropout', type=float, metavar='D', help='dropout probability for attention weights') parser.add_argument('--relu-dropout', type=float, metavar='D', help='dropout probability after ReLU in FFN') parser.add_argument('--encoder-embed-path', type=str, metavar='STR', help='path to pre-trained encoder embedding') parser.add_argument('--encoder-embed-dim', type=int, metavar='N', help='encoder embedding dimension') parser.add_argument('--encoder-ffn-embed-dim', type=int, metavar='N', help='encoder embedding dimension for FFN') parser.add_argument('--encoder-layers', type=int, metavar='N', help='num encoder layers') parser.add_argument('--encoder-attention-heads', type=int, metavar='N', help='num encoder attention heads') parser.add_argument('--encoder-normalize-before', action='store_true', help='apply layernorm before each encoder block') parser.add_argument('--encoder-learned-pos', action='store_true', help='use learned positional embeddings in the encoder') parser.add_argument('--n-classes', type=int, metavar='N', help='number of classifier classes') parser.add_argument('--act-fn', type=str, metavar='STR', help='name of the activation function') parser.add_argument('--macaron', action='store_true', help='use the macaron network') @classmethod def build_model(cls, args, task): """Build a new model instance.""" # make sure all arguments are present in older models base_classifier_architecture(args) if not hasattr(args, 'max_positions'): args.max_positions = 256 args.max_source_positions = args.max_positions dictionary = task.dict def build_embedding(dictionary, embed_dim, path=None): num_embeddings = len(dictionary) padding_idx = dictionary.pad() emb = Embedding(num_embeddings, embed_dim, padding_idx) # if provided, load from preloaded dictionaries if path: embed_dict = utils.parse_embedding(path) utils.load_embedding(embed_dict, dictionary, emb) return emb embed_tokens = build_embedding( dictionary, args.encoder_embed_dim, args.encoder_embed_path ) encoder = TransformerEncoder(args, dictionary, embed_tokens, left_pad=False, require_segment=True) return TransformerClassifierModel(encoder, args.encoder_embed_dim, args.n_classes) @register_model('transformer_lm') class TransformerLanguageModel(FairseqLanguageModel): def __init__(self, decoder): super().__init__(decoder) @staticmethod def add_args(parser): """Add model-specific arguments to the parser.""" parser.add_argument('--dropout', default=0.1, type=float, metavar='D', help='dropout probability') parser.add_argument('--attention-dropout', default=0., type=float, metavar='D', help='dropout probability for attention weights') parser.add_argument('--relu-dropout', default=0., type=float, metavar='D', help='dropout probability after ReLU in FFN') parser.add_argument('--decoder-embed-dim', type=int, metavar='N', help='decoder embedding dimension') parser.add_argument('--decoder-output-dim', type=int, metavar='N', help='decoder output dimension') parser.add_argument('--decoder-input-dim', type=int, metavar='N', help='decoder input dimension') parser.add_argument('--decoder-ffn-embed-dim', type=int, metavar='N', help='decoder embedding dimension for FFN') parser.add_argument('--decoder-layers', type=int, metavar='N', help='num decoder layers') parser.add_argument('--decoder-attention-heads', type=int, metavar='N', help='num decoder attention heads') parser.add_argument('--decoder-normalize-before', default=False, action='store_true', help='apply layernorm before each decoder block') parser.add_argument('--adaptive-softmax-cutoff', metavar='EXPR', help='comma separated list of adaptive softmax cutoff points. ' 'Must be used with adaptive_loss criterion') parser.add_argument('--adaptive-softmax-dropout', type=float, metavar='D', help='sets adaptive softmax dropout for the tail projections') parser.add_argument('--no-token-positional-embeddings', default=False, action='store_true', help='if set, disables positional embeddings (outside self attention)') parser.add_argument('--share-decoder-input-output-embed', default=False, action='store_true', help='share decoder input and output embeddings') parser.add_argument('--character-embeddings', default=False, action='store_true', help='if set, uses character embedding convolutions to produce token embeddings') parser.add_argument('--character-filters', type=str, metavar='LIST', default='[(1, 64), (2, 128), (3, 192), (4, 256), (5, 256), (6, 256), (7, 256)]', help='size of character embeddings') parser.add_argument('--character-embedding-dim', type=int, metavar='N', default=4, help='size of character embeddings') parser.add_argument('--char-embedder-highway-layers', type=int, metavar='N', default=2, help='number of highway layers for character token embeddder') parser.add_argument('--act-fn', type=str, metavar='STR', help='name of the activation function') parser.add_argument('--macaron', action='store_true', help='use the macaron network') @classmethod def build_model(cls, args, task): """Build a new model instance.""" # make sure all arguments are present in older models base_lm_architecture(args) if not hasattr(args, 'max_source_positions'): args.max_source_positions = args.tokens_per_sample if not hasattr(args, 'max_target_positions'): args.max_target_positions = args.tokens_per_sample if args.character_embeddings: embed_tokens = CharacterTokenEmbedder(task.dictionary, eval(args.character_filters), args.character_embedding_dim, args.decoder_embed_dim, args.char_embedder_highway_layers, ) else: embed_tokens = Embedding(len(task.dictionary), args.decoder_input_dim, task.dictionary.pad()) decoder = TransformerDecoder(args, task.output_dictionary, embed_tokens, no_encoder_attn=True, final_norm=False) return TransformerLanguageModel(decoder) class TransformerEncoder(FairseqEncoder): """ Transformer encoder consisting of *args.encoder_layers* layers. Each layer is a :class:`TransformerEncoderLayer`. Args: args (argparse.Namespace): parsed command-line arguments dictionary (~fairseq.data.Dictionary): encoding dictionary embed_tokens (torch.nn.Embedding): input embedding left_pad (bool, optional): whether the input is left-padded. Default: ``True`` """ def __init__(self, args, dictionary, embed_tokens, left_pad=True, require_segment=False): super().__init__(dictionary) self.dropout = args.dropout embed_dim = embed_tokens.embedding_dim self.padding_idx = embed_tokens.padding_idx self.max_source_positions = args.max_source_positions self.embed_tokens = embed_tokens self.embed_scale = math.sqrt(embed_dim) self.embed_positions = PositionalEmbedding( args.max_source_positions, embed_dim, self.padding_idx, left_pad=left_pad, learned=args.encoder_learned_pos, ) if not args.no_token_positional_embeddings else None self.embed_segment = Embedding(2, embed_dim, self.padding_idx) if require_segment else None self.layers = nn.ModuleList([]) self.layers.extend([ TransformerEncoderLayer(args) for i in range(args.encoder_layers) ]) self.register_buffer('version', torch.Tensor([2])) self.normalize = args.encoder_normalize_before if self.normalize: self.layer_norm = LayerNorm(embed_dim, not args.no_normalize_affine) def forward(self, src_tokens, src_lengths, segment=None, last_layer_mask=None): """ Args: src_tokens (LongTensor): tokens in the source language of shape `(batch, src_len)` src_lengths (torch.LongTensor): lengths of each source sentence of shape `(batch)` segment (LongTensor): segment of the sentence (1 for the first and 0 for the second) Returns: dict: - **encoder_out** (Tensor): the last encoder layer's output of shape `(src_len, batch, embed_dim)` - **encoder_padding_mask** (ByteTensor): the positions of padding elements of shape `(batch, src_len)` """ # embed tokens and positions x = self.embed_scale * self.embed_tokens(src_tokens) if self.embed_positions is not None: x += self.embed_positions(src_tokens) if segment is not None: x += self.embed_segment(segment) x = F.dropout(x, p=self.dropout, training=self.training) # B x T x C -> T x B x C x = x.transpose(0, 1) # compute padding mask encoder_padding_mask = src_tokens.eq(self.padding_idx) if not encoder_padding_mask.any(): encoder_padding_mask = None # encoder layers if last_layer_mask is None: for layer in self.layers: x = layer(x, encoder_padding_mask) else: for layer in self.layers[:-1]: x = layer(x, encoder_padding_mask) x = self.layers[-1](x, encoder_padding_mask, last_layer_mask) if self.normalize: x = self.layer_norm(x) return { 'encoder_out': x, # T x B x C or (B + N) x C 'encoder_padding_mask': encoder_padding_mask, # B x T } def reorder_encoder_out(self, encoder_out, new_order): """ Reorder encoder output according to *new_order*. Args: encoder_out: output from the ``forward()`` method new_order (LongTensor): desired order Returns: *encoder_out* rearranged according to *new_order* """ if encoder_out['encoder_out'] is not None: encoder_out['encoder_out'] = \ encoder_out['encoder_out'].index_select(1, new_order) if encoder_out['encoder_padding_mask'] is not None: encoder_out['encoder_padding_mask'] = \ encoder_out['encoder_padding_mask'].index_select(0, new_order) return encoder_out def max_positions(self): """Maximum input length supported by the encoder.""" if self.embed_positions is None: return self.max_source_positions return min(self.max_source_positions, self.embed_positions.max_positions()) def upgrade_state_dict(self, state_dict): """Upgrade a (possibly old) state dict for new versions of fairseq.""" if isinstance(self.embed_positions, SinusoidalPositionalEmbedding): if 'encoder.embed_positions.weights' in state_dict: del state_dict['encoder.embed_positions.weights'] state_dict['encoder.embed_positions._float_tensor'] = torch.FloatTensor(1) if utils.item(state_dict.get('encoder.version', torch.Tensor([1]))[0]) < 2: # earlier checkpoints did not normalize after the stack of layers self.layer_norm = None self.normalize = False state_dict['encoder.version'] = torch.Tensor([1]) return state_dict class TransformerDecoder(FairseqIncrementalDecoder): """ Transformer decoder consisting of *args.decoder_layers* layers. Each layer is a :class:`TransformerDecoderLayer`. Args: args (argparse.Namespace): parsed command-line arguments dictionary (~fairseq.data.Dictionary): decoding dictionary embed_tokens (torch.nn.Embedding): output embedding no_encoder_attn (bool, optional): whether to attend to encoder outputs. Default: ``False`` left_pad (bool, optional): whether the input is left-padded. Default: ``False`` """ def __init__(self, args, dictionary, embed_tokens, no_encoder_attn=False, left_pad=False, final_norm=True): super().__init__(dictionary) self.dropout = args.dropout self.share_input_output_embed = args.share_decoder_input_output_embed input_embed_dim = embed_tokens.embedding_dim embed_dim = args.decoder_embed_dim output_embed_dim = args.decoder_output_dim padding_idx = embed_tokens.padding_idx self.max_target_positions = args.max_target_positions self.embed_tokens = embed_tokens self.embed_scale = math.sqrt(embed_dim) # todo: try with input_embed_dim self.project_in_dim = Linear(input_embed_dim, embed_dim, bias=False, uniform=False) if embed_dim != input_embed_dim else None self.embed_positions = PositionalEmbedding( args.max_target_positions, embed_dim, padding_idx, left_pad=left_pad, learned=args.decoder_learned_pos, ) if not args.no_token_positional_embeddings else None self.layers = nn.ModuleList([]) self.layers.extend([ TransformerDecoderLayer(args, no_encoder_attn) for _ in range(args.decoder_layers) ]) self.adaptive_softmax = None self.project_out_dim = Linear(embed_dim, output_embed_dim, bias=False, uniform=False) if embed_dim != output_embed_dim else None if args.adaptive_softmax_cutoff is not None: self.adaptive_softmax = AdaptiveSoftmax( len(dictionary), output_embed_dim, options.eval_str_list(args.adaptive_softmax_cutoff, type=int), dropout=args.adaptive_softmax_dropout, ) elif not self.share_input_output_embed: self.embed_out = nn.Parameter(torch.Tensor(len(dictionary), output_embed_dim)) nn.init.normal_(self.embed_out, mean=0, std=output_embed_dim ** -0.5) self.register_buffer('version', torch.Tensor([2])) self.normalize = args.decoder_normalize_before and final_norm if self.normalize: self.layer_norm = LayerNorm(embed_dim, not args.no_normalize_affine) def forward(self, prev_output_tokens, encoder_out=None, incremental_state=None): """ Args: prev_output_tokens (LongTensor): previous decoder outputs of shape `(batch, tgt_len)`, for input feeding/teacher forcing encoder_out (Tensor, optional): output from the encoder, used for encoder-side attention incremental_state (dict): dictionary used for storing state during :ref:`Incremental decoding` Returns: tuple: - the last decoder layer's output of shape `(batch, tgt_len, vocab)` - the last decoder layer's attention weights of shape `(batch, tgt_len, src_len)` """ # embed positions positions = self.embed_positions( prev_output_tokens, incremental_state=incremental_state, ) if self.embed_positions is not None else None if incremental_state is not None: prev_output_tokens = prev_output_tokens[:, -1:] if positions is not None: positions = positions[:, -1:] # embed tokens and positions x = self.embed_scale * self.embed_tokens(prev_output_tokens) if self.project_in_dim is not None: x = self.project_in_dim(x) if positions is not None: x += positions x = F.dropout(x, p=self.dropout, training=self.training) # B x T x C -> T x B x C x = x.transpose(0, 1) attn = None inner_states = [x] # decoder layers for layer in self.layers: x, attn = layer( x, encoder_out['encoder_out'] if encoder_out is not None else None, encoder_out['encoder_padding_mask'] if encoder_out is not None else None, incremental_state, self_attn_mask=self.buffered_future_mask(x) if incremental_state is None else None, ) inner_states.append(x) if self.normalize: x = self.layer_norm(x) # T x B x C -> B x T x C x = x.transpose(0, 1) if self.project_out_dim is not None: x = self.project_out_dim(x) if self.adaptive_softmax is None: # project back to size of vocabulary if self.share_input_output_embed: x = F.linear(x, self.embed_tokens.weight) else: x = F.linear(x, self.embed_out) return x, {'attn': attn, 'inner_states': inner_states} def max_positions(self): """Maximum output length supported by the decoder.""" if self.embed_positions is None: return self.max_target_positions return min(self.max_target_positions, self.embed_positions.max_positions()) def buffered_future_mask(self, tensor): dim = tensor.size(0) if not hasattr(self, '_future_mask') or self._future_mask is None or self._future_mask.device != tensor.device: self._future_mask = torch.triu(utils.fill_with_neg_inf(tensor.new(dim, dim)), 1) if self._future_mask.size(0) < dim: self._future_mask = torch.triu(utils.fill_with_neg_inf(self._future_mask.resize_(dim, dim)), 1) return self._future_mask[:dim, :dim] def upgrade_state_dict(self, state_dict): """Upgrade a (possibly old) state dict for new versions of fairseq.""" if isinstance(self.embed_positions, SinusoidalPositionalEmbedding): if 'decoder.embed_positions.weights' in state_dict: del state_dict['decoder.embed_positions.weights'] state_dict['decoder.embed_positions._float_tensor'] = torch.FloatTensor(1) for i in range(len(self.layers)): # update layer norms layer_norm_map = { '0': 'self_attn_layer_norm', '1': 'encoder_attn_layer_norm', '2': 'final_layer_norm' } for old, new in layer_norm_map.items(): for m in ('weight', 'bias'): k = 'decoder.layers.{}.layer_norms.{}.{}'.format(i, old, m) if k in state_dict: state_dict['decoder.layers.{}.{}.{}'.format(i, new, m)] = state_dict[k] del state_dict[k] if utils.item(state_dict.get('decoder.version', torch.Tensor([1]))[0]) < 2: # earlier checkpoints did not normalize after the stack of layers self.layer_norm = None self.normalize = False state_dict['decoder.version'] = torch.Tensor([1]) return state_dict class TransformerEncoderLayer(nn.Module): """Encoder layer block. In the original paper each operation (multi-head attention or FFN) is postprocessed with: `dropout -> add residual -> layernorm`. In the tensor2tensor code they suggest that learning is more robust when preprocessing each layer with layernorm and postprocessing with: `dropout -> add residual`. We default to the approach in the paper, but the tensor2tensor approach can be enabled by setting *args.encoder_normalize_before* to ``True``. Args: args (argparse.Namespace): parsed command-line arguments """ def __init__(self, args): super().__init__() self.embed_dim = args.encoder_embed_dim self.self_attn = MultiheadAttention( self.embed_dim, args.encoder_attention_heads, dropout=args.attention_dropout, ) self.dropout = args.dropout self.relu_dropout = args.relu_dropout self.normalize_before = args.encoder_normalize_before self.fc1 = Linear(self.embed_dim, args.encoder_ffn_embed_dim) self.fc2 = Linear(args.encoder_ffn_embed_dim, self.embed_dim, nonlinearity='relu') n_layernorm = 2 self.fc_factor = 1.0 self.macaron = getattr(args, "macaron", False) if self.macaron: self.macaron_fc1 = Linear(self.embed_dim, args.encoder_ffn_embed_dim) self.macaron_fc2 = Linear(args.encoder_ffn_embed_dim, self.embed_dim, nonlinearity='relu') self.fc_factor = 0.5 n_layernorm += 1 self.layer_norms = nn.ModuleList([LayerNorm(self.embed_dim, not args.no_normalize_affine) for i in range(n_layernorm)]) self.act_fn = _get_activation(args.act_fn) def forward(self, x, encoder_padding_mask, last_layer_mask=None): """ Args: x (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)` encoder_padding_mask (ByteTensor): binary ByteTensor of shape `(batch, src_len)` where padding elements are indicated by ``1``. Returns: encoded output of shape `(batch, src_len, embed_dim)` """ if self.macaron: residual = x x = self.maybe_layer_norm(2, x, before=True) x = F.relu(self.macaron_fc1(x)) x = F.dropout(x, p=self.relu_dropout, training=self.training) x = self.macaron_fc2(x) x = F.dropout(x, p=self.dropout, training=self.training) x = residual + self.fc_factor * x x = self.maybe_layer_norm(2, x, after=True) residual = x x = self.maybe_layer_norm(0, x, before=True) x, _ = self.self_attn(query=x, key=x, value=x, key_padding_mask=encoder_padding_mask) x = F.dropout(x, p=self.dropout, training=self.training) x = residual + x x = self.maybe_layer_norm(0, x, after=True) if last_layer_mask is not None: x = torch.cat([x[0, ...], x.transpose(0, 1)[last_layer_mask]], dim=0) # (B + N) x C residual = x x = self.maybe_layer_norm(1, x, before=True) x = self.act_fn(self.fc1(x)) x = F.dropout(x, p=self.relu_dropout, training=self.training) x = self.fc2(x) x = F.dropout(x, p=self.dropout, training=self.training) x = residual + self.fc_factor * x x = self.maybe_layer_norm(1, x, after=True) return x def maybe_layer_norm(self, i, x, before=False, after=False): assert before ^ after if after ^ self.normalize_before: return self.layer_norms[i](x) else: return x class TransformerDecoderLayer(nn.Module): """Decoder layer block. In the original paper each operation (multi-head attention, encoder attention or FFN) is postprocessed with: `dropout -> add residual -> layernorm`. In the tensor2tensor code they suggest that learning is more robust when preprocessing each layer with layernorm and postprocessing with: `dropout -> add residual`. We default to the approach in the paper, but the tensor2tensor approach can be enabled by setting *args.decoder_normalize_before* to ``True``. Args: args (argparse.Namespace): parsed command-line arguments no_encoder_attn (bool, optional): whether to attend to encoder outputs. Default: ``False`` """ def __init__(self, args, no_encoder_attn=False): super().__init__() self.embed_dim = args.decoder_embed_dim self.self_attn = MultiheadAttention( self.embed_dim, args.decoder_attention_heads, dropout=args.attention_dropout, ) self.dropout = args.dropout self.relu_dropout = args.relu_dropout self.normalize_before = args.decoder_normalize_before self.self_attn_layer_norm = LayerNorm(self.embed_dim, not args.no_normalize_affine) if no_encoder_attn: self.encoder_attn = None self.encoder_attn_layer_norm = None else: self.encoder_attn = MultiheadAttention( self.embed_dim, args.decoder_attention_heads, dropout=args.attention_dropout, ) self.encoder_attn_layer_norm = LayerNorm(self.embed_dim, not args.no_normalize_affine) self.fc1 = Linear(self.embed_dim, args.decoder_ffn_embed_dim) self.fc2 = Linear(args.decoder_ffn_embed_dim, self.embed_dim, nonlinearity='relu') self.fc_factor = 1.0 self.macaron = getattr(args, "macaron", False) if self.macaron: self.macaron_fc1 = Linear(self.embed_dim, args.encoder_ffn_embed_dim) self.macaron_fc2 = Linear(args.encoder_ffn_embed_dim, self.embed_dim) self.macaron_layer_norm = LayerNorm(self.embed_dim) self.fc_factor = 0.5 self.final_layer_norm = LayerNorm(self.embed_dim, not args.no_normalize_affine) self.need_attn = True self.onnx_trace = False self.act_fn = _get_activation(args.act_fn) def prepare_for_onnx_export_(self): self.onnx_trace = True def forward(self, x, encoder_out, encoder_padding_mask, incremental_state, prev_self_attn_state=None, prev_attn_state=None, self_attn_mask=None, self_attn_padding_mask=None): """ Args: x (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)` encoder_padding_mask (ByteTensor): binary ByteTensor of shape `(batch, src_len)` where padding elements are indicated by ``1``. Returns: encoded output of shape `(batch, src_len, embed_dim)` """ if self.macaron: residual = x x = self.maybe_layer_norm(self.macaron_layer_norm, x, before=True) x = F.relu(self.macaron_fc1(x)) x = F.dropout(x, p=self.relu_dropout, training=self.training) x = self.macaron_fc2(x) x = F.dropout(x, p=self.dropout, training=self.training) x = residual + self.fc_factor * x x = self.maybe_layer_norm(self.macaron_layer_norm, x, after=True) residual = x x = self.maybe_layer_norm(self.self_attn_layer_norm, x, before=True) if prev_self_attn_state is not None: if incremental_state is None: incremental_state = {} prev_key, prev_value = prev_self_attn_state saved_state = {"prev_key": prev_key, "prev_value": prev_value} self.self_attn._set_input_buffer(incremental_state, saved_state) x, _ = self.self_attn( query=x, key=x, value=x, key_padding_mask=self_attn_padding_mask, incremental_state=incremental_state, need_weights=False, attn_mask=self_attn_mask, ) x = F.dropout(x, p=self.dropout, training=self.training) x = residual + x x = self.maybe_layer_norm(self.self_attn_layer_norm, x, after=True) attn = None if self.encoder_attn is not None: residual = x x = self.maybe_layer_norm(self.encoder_attn_layer_norm, x, before=True) if prev_attn_state is not None: if incremental_state is None: incremental_state = {} prev_key, prev_value = prev_attn_state saved_state = {"prev_key": prev_key, "prev_value": prev_value} self.encoder_attn._set_input_buffer(incremental_state, saved_state) x, attn = self.encoder_attn( query=x, key=encoder_out, value=encoder_out, key_padding_mask=encoder_padding_mask, incremental_state=incremental_state, static_kv=True, need_weights=(not self.training and self.need_attn), ) x = F.dropout(x, p=self.dropout, training=self.training) x = residual + x x = self.maybe_layer_norm(self.encoder_attn_layer_norm, x, after=True) residual = x x = self.maybe_layer_norm(self.final_layer_norm, x, before=True) x = self.act_fn(self.fc1(x)) x = F.dropout(x, p=self.relu_dropout, training=self.training) x = self.fc2(x) x = F.dropout(x, p=self.dropout, training=self.training) x = residual + self.fc_factor * x x = self.maybe_layer_norm(self.final_layer_norm, x, after=True) if self.onnx_trace: saved_state = self.self_attn._get_input_buffer(incremental_state) self_attn_state = saved_state["prev_key"], saved_state["prev_value"] return x, attn, self_attn_state return x, attn def maybe_layer_norm(self, layer_norm, x, before=False, after=False): assert before ^ after if after ^ self.normalize_before: return layer_norm(x) else: return x def make_generation_fast_(self, need_attn=False, **kwargs): self.need_attn = need_attn def Embedding(num_embeddings, embedding_dim, padding_idx): m = nn.Embedding(num_embeddings, embedding_dim, padding_idx=padding_idx) nn.init.normal_(m.weight, mean=0, std=embedding_dim ** -0.5) nn.init.constant_(m.weight[padding_idx], 0) return m def LayerNorm(embedding_dim, elementwise_affine=True): m = nn.LayerNorm(embedding_dim, elementwise_affine=elementwise_affine) return m def Linear(in_features, out_features, bias=True, uniform=False, nonlinearity='linear'): m = nn.Linear(in_features, out_features, bias) if uniform: nn.init.kaiming_uniform_(m.weight) else: nn.init.kaiming_normal_(m.weight, nonlinearity=nonlinearity) if bias: nn.init.constant_(m.bias, 0.) return m def PositionalEmbedding(num_embeddings, embedding_dim, padding_idx, left_pad, learned=False): if learned: m = LearnedPositionalEmbedding(num_embeddings + padding_idx + 1, embedding_dim, padding_idx, left_pad) nn.init.normal_(m.weight, mean=0, std=embedding_dim ** -0.5) nn.init.constant_(m.weight[padding_idx], 0) else: m = SinusoidalPositionalEmbedding(embedding_dim, padding_idx, left_pad, num_embeddings + padding_idx + 1) return m @register_model_architecture('transformer_lm', 'transformer_lm') def base_lm_architecture(args): args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 512) args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', 2048) args.decoder_layers = getattr(args, 'decoder_layers', 6) args.decoder_attention_heads = getattr(args, 'decoder_attention_heads', 8) args.adaptive_softmax_cutoff = getattr(args, 'adaptive_softmax_cutoff', None) args.adaptive_softmax_dropout = getattr(args, 'adaptive_softmax_dropout', 0) args.decoder_learned_pos = getattr(args, 'decoder_learned_pos', False) args.character_embeddings = getattr(args, 'character_embeddings', False) args.decoder_output_dim = getattr(args, 'decoder_output_dim', args.decoder_embed_dim) args.decoder_input_dim = getattr(args, 'decoder_input_dim', args.decoder_embed_dim) # The model training is not stable without this args.decoder_normalize_before = True @register_model_architecture('transformer_lm', 'transformer_lm_big') def transformer_lm_big(args): args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 1024) args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', 4096) args.decoder_attention_heads = getattr(args, 'decoder_attention_heads', 16) base_lm_architecture(args) @register_model_architecture('transformer_lm', 'transformer_lm_wiki103') def transformer_lm_wiki103(args): args.dropout = getattr(args, 'dropout', 0.3) transformer_lm_big(args) @register_model_architecture('transformer_lm', 'transformer_lm_gbw') def transformer_lm_gbw(args): args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 512) args.dropout = getattr(args, 'dropout', 0.1) args.attention_dropout = getattr(args, 'attention_dropout', 0.1) transformer_lm_big(args) @register_model_architecture('transformer', 'transformer') def base_architecture(args): args.encoder_embed_path = getattr(args, 'encoder_embed_path', None) args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 512) args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 2048) args.encoder_layers = getattr(args, 'encoder_layers', 6) args.encoder_attention_heads = getattr(args, 'encoder_attention_heads', 8) args.encoder_normalize_before = getattr(args, 'encoder_normalize_before', False) args.encoder_learned_pos = getattr(args, 'encoder_learned_pos', False) args.decoder_embed_path = getattr(args, 'decoder_embed_path', None) args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', args.encoder_embed_dim) args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', args.encoder_ffn_embed_dim) args.decoder_layers = getattr(args, 'decoder_layers', 6) args.decoder_attention_heads = getattr(args, 'decoder_attention_heads', 8) args.decoder_normalize_before = getattr(args, 'decoder_normalize_before', False) args.decoder_learned_pos = getattr(args, 'decoder_learned_pos', False) args.attention_dropout = getattr(args, 'attention_dropout', 0.) args.relu_dropout = getattr(args, 'relu_dropout', 0.) args.dropout = getattr(args, 'dropout', 0.1) args.adaptive_softmax_cutoff = getattr(args, 'adaptive_softmax_cutoff', None) args.adaptive_softmax_dropout = getattr(args, 'adaptive_softmax_dropout', 0) args.share_decoder_input_output_embed = getattr(args, 'share_decoder_input_output_embed', False) args.share_all_embeddings = getattr(args, 'share_all_embeddings', False) args.no_token_positional_embeddings = getattr(args, 'no_token_positional_embeddings', False) args.decoder_output_dim = getattr(args, 'decoder_output_dim', args.decoder_embed_dim) args.decoder_input_dim = getattr(args, 'decoder_input_dim', args.decoder_embed_dim) args.no_normalize_affine = getattr(args, 'no_normalize_affine', False) args.act_fn = getattr(args, 'act_fn', 'relu') @register_model_architecture('transformer', 'transformer_iwslt_de_en') def transformer_iwslt_de_en(args): args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 512) args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 1024) args.encoder_attention_heads = getattr(args, 'encoder_attention_heads', 4) args.encoder_layers = getattr(args, 'encoder_layers', 6) args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 512) args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', 1024) args.decoder_attention_heads = getattr(args, 'decoder_attention_heads', 4) args.decoder_layers = getattr(args, 'decoder_layers', 6) base_architecture(args) @register_model_architecture('transformer', 'transformer_wmt_en_de') def transformer_wmt_en_de(args): base_architecture(args) # parameters used in the "Attention Is All You Need" paper (Vaswani, et al, 2017) @register_model_architecture('transformer', 'transformer_vaswani_wmt_en_de_big') def transformer_vaswani_wmt_en_de_big(args): args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 1024) args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 4096) args.encoder_attention_heads = getattr(args, 'encoder_attention_heads', 16) args.encoder_normalize_before = getattr(args, 'encoder_normalize_before', False) args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 1024) args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', 4096) args.decoder_attention_heads = getattr(args, 'decoder_attention_heads', 16) args.dropout = getattr(args, 'dropout', 0.3) base_architecture(args) @register_model_architecture('transformer', 'transformer_vaswani_wmt_en_fr_big') def transformer_vaswani_wmt_en_fr_big(args): args.dropout = getattr(args, 'dropout', 0.1) transformer_vaswani_wmt_en_de_big(args) @register_model_architecture('transformer', 'transformer_wmt_en_de_big') def transformer_wmt_en_de_big(args): args.attention_dropout = getattr(args, 'attention_dropout', 0.1) transformer_vaswani_wmt_en_de_big(args) # default parameters used in tensor2tensor implementation @register_model_architecture('transformer', 'transformer_wmt_en_de_big_t2t') def transformer_wmt_en_de_big_t2t(args): args.encoder_normalize_before = getattr(args, 'encoder_normalize_before', True) args.decoder_normalize_before = getattr(args, 'decoder_normalize_before', True) args.attention_dropout = getattr(args, 'attention_dropout', 0.1) args.relu_dropout = getattr(args, 'relu_dropout', 0.1) transformer_vaswani_wmt_en_de_big(args) @register_model_architecture('transformer_bert', 'transformer_bert') def base_bert_architecture(args): args.encoder_embed_path = getattr(args, 'encoder_embed_path', None) args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 512) args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 2048) args.encoder_layers = getattr(args, 'encoder_layers', 6) args.encoder_attention_heads = getattr(args, 'encoder_attention_heads', 8) args.encoder_normalize_before = getattr(args, 'encoder_normalize_before', False) args.encoder_learned_pos = getattr(args, 'encoder_learned_pos', False) args.attention_dropout = getattr(args, 'attention_dropout', 0.) args.relu_dropout = getattr(args, 'relu_dropout', 0.) args.dropout = getattr(args, 'dropout', 0.1) args.share_all_embeddings = getattr(args, 'share_all_embeddings', False) args.no_token_positional_embeddings = getattr(args, 'no_token_positional_embeddings', False) @register_model_architecture('transformer_bert', 'transformer_bert_L6_A12') def transformer_bert_L6_A12(args): args.encoder_embed_path = getattr(args, 'encoder_embed_path', None) args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 768) args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 3072) args.encoder_layers = getattr(args, 'encoder_layers', 6) args.encoder_attention_heads = getattr(args, 'encoder_attention_heads', 12) args.encoder_normalize_before = getattr(args, 'encoder_normalize_before', True) args.encoder_learned_pos = getattr(args, 'encoder_learned_pos', False) args.attention_dropout = getattr(args, 'attention_dropout', 0.1) args.relu_dropout = getattr(args, 'relu_dropout', 0.) args.dropout = getattr(args, 'dropout', 0.1) args.share_all_embeddings = getattr(args, 'share_all_embeddings', True) args.no_token_positional_embeddings = getattr(args, 'no_token_positional_embeddings', False) args.act_fn = getattr(args, 'act_fn', 'gelu') args.no_normalize_affine = getattr(args, 'no_normalize_affine', True) @register_model_architecture('transformer_bert', 'transformer_bert_base') def transformer_bert_base(args): args.encoder_embed_path = getattr(args, 'encoder_embed_path', None) args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 768) args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 3072) args.encoder_layers = getattr(args, 'encoder_layers', 12) args.encoder_attention_heads = getattr(args, 'encoder_attention_heads', 12) args.encoder_normalize_before = getattr(args, 'encoder_normalize_before', True) args.encoder_learned_pos = getattr(args, 'encoder_learned_pos', False) args.attention_dropout = getattr(args, 'attention_dropout', 0.1) args.relu_dropout = getattr(args, 'relu_dropout', 0.) args.dropout = getattr(args, 'dropout', 0.1) args.share_all_embeddings = getattr(args, 'share_all_embeddings', True) args.no_token_positional_embeddings = getattr(args, 'no_token_positional_embeddings', False) args.act_fn = getattr(args, 'act_fn', 'gelu') args.no_normalize_affine = getattr(args, 'no_normalize_affine', True) @register_model_architecture('transformer_bert', 'transformer_bert_base_macaron') def transformer_bert_base_macaron(args): args.macaron = getattr(args, 'macaron', True) args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 1536) transformer_bert_base(args) @register_model_architecture('transformer_bert', 'transformer_bert_L6_A12_macaron') def transformer_bert_L6_A12_macaron(args): args.macaron = getattr(args, 'macaron', True) args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 1536) transformer_bert_L6_A12(args) @register_model_architecture('transformer_classifier', 'transformer_classifier') def base_classifier_architecture(args): args.encoder_embed_path = getattr(args, 'encoder_embed_path', None) args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 512) args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 2048) args.encoder_layers = getattr(args, 'encoder_layers', 6) args.encoder_attention_heads = getattr(args, 'encoder_attention_heads', 8) args.encoder_normalize_before = getattr(args, 'encoder_normalize_before', False) args.encoder_learned_pos = getattr(args, 'encoder_learned_pos', False) args.attention_dropout = getattr(args, 'attention_dropout', 0.) args.relu_dropout = getattr(args, 'relu_dropout', 0.) args.dropout = getattr(args, 'dropout', 0.1) args.no_token_positional_embeddings = getattr(args, 'no_token_positional_embeddings', False) args.n_classes = getattr(args, 'n_classes', 1) @register_model_architecture('transformer_classifier', 'transformer_classifier_L6_A12') def transformer_classifier_L6_A12(args): args.encoder_embed_path = getattr(args, 'encoder_embed_path', None) args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 768) args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 3072) args.encoder_layers = getattr(args, 'encoder_layers', 6) args.encoder_attention_heads = getattr(args, 'encoder_attention_heads', 12) args.encoder_normalize_before = getattr(args, 'encoder_normalize_before', True) args.encoder_learned_pos = getattr(args, 'encoder_learned_pos', False) args.attention_dropout = getattr(args, 'attention_dropout', 0.1) args.relu_dropout = getattr(args, 'relu_dropout', 0.) args.dropout = getattr(args, 'dropout', 0.1) args.no_token_positional_embeddings = getattr(args, 'no_token_positional_embeddings', False) args.n_classes = getattr(args, 'n_classes', 1) args.act_fn = getattr(args, 'act_fn', 'gelu') args.no_normalize_affine = getattr(args, 'no_normalize_affine', True) @register_model_architecture('transformer_classifier', 'transformer_classifier_base') def transformer_classifier_base(args): args.encoder_embed_path = getattr(args, 'encoder_embed_path', None) args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 768) args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 3072) args.encoder_layers = getattr(args, 'encoder_layers', 12) args.encoder_attention_heads = getattr(args, 'encoder_attention_heads', 12) args.encoder_normalize_before = getattr(args, 'encoder_normalize_before', True) args.encoder_learned_pos = getattr(args, 'encoder_learned_pos', False) args.attention_dropout = getattr(args, 'attention_dropout', 0.1) args.relu_dropout = getattr(args, 'relu_dropout', 0.) args.dropout = getattr(args, 'dropout', 0.1) args.no_token_positional_embeddings = getattr(args, 'no_token_positional_embeddings', False) args.n_classes = getattr(args, 'n_classes', 1) args.act_fn = getattr(args, 'act_fn', 'gelu') args.no_normalize_affine = getattr(args, 'no_normalize_affine', True) @register_model_architecture('transformer_classifier', 'transformer_classifier_base_macaron') def transformer_classifier_base_macaron(args): args.macaron = getattr(args, 'macaron', True) args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 1536) transformer_classifier_base(args)
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/modules/__init__.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. from .adaptive_softmax import AdaptiveSoftmax from .beamable_mm import BeamableMM from .character_token_embedder import CharacterTokenEmbedder from .conv_tbc import ConvTBC from .downsampled_multihead_attention import DownsampledMultiHeadAttention from .grad_multiply import GradMultiply from .highway import Highway from .learned_positional_embedding import LearnedPositionalEmbedding from .linearized_convolution import LinearizedConvolution from .multihead_attention import MultiheadAttention from .scalar_bias import ScalarBias from .sinusoidal_positional_embedding import SinusoidalPositionalEmbedding __all__ = [ 'AdaptiveSoftmax', 'BeamableMM', 'CharacterTokenEmbedder', 'ConvTBC', 'DownsampledMultiHeadAttention', 'GradMultiply', 'Highway', 'LearnedPositionalEmbedding', 'LinearizedConvolution', 'MultiheadAttention', 'ScalarBias', 'SinusoidalPositionalEmbedding', ]
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/modules/adaptive_softmax.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import torch import torch.nn.functional as F from torch import nn class AdaptiveSoftmax(nn.Module): """ This is an implementation of the efficient softmax approximation for graphical processing units (GPU), described in the paper "Efficient softmax approximation for GPUs" (http://arxiv.org/abs/1609.04309). """ def __init__(self, vocab_size, input_dim, cutoff, dropout): super().__init__() if vocab_size > cutoff[-1]: cutoff = cutoff + [vocab_size] else: assert vocab_size == cutoff[ -1], 'cannot specify cutoff larger than vocab size' output_dim = cutoff[0] + len(cutoff) - 1 self.vocab_size = vocab_size self.cutoff = cutoff self.dropout = dropout self.input_dim = input_dim self.lsm = nn.LogSoftmax(dim=1) self.head = nn.Linear(input_dim, output_dim, bias=False) self._make_tail(True) def init_weights(m): if hasattr(m, 'weight'): nn.init.xavier_uniform_(m.weight) self.apply(init_weights) self.register_buffer('version', torch.LongTensor([1])) # versions prior to 1 had a bug that offset indices on the head by 1 self.buggy_offset = 0 def _make_tail(self, fix_exponent): extra_denom = 1 if fix_exponent else 0 self.tail = nn.ModuleList() for i in range(len(self.cutoff) - 1): self.tail.append( nn.Sequential( nn.Linear(self.input_dim, self.input_dim // 4 ** (i + extra_denom), bias=False), nn.Dropout(self.dropout), nn.Linear(self.input_dim // 4 ** (i + extra_denom), self.cutoff[i + 1] - self.cutoff[i], bias=False) ) ) def upgrade_state_dict_named(self, state_dict, name): version_name = name + '.version' if version_name not in state_dict: self.buggy_offset = 1 self._make_tail(False) state_dict[version_name] = torch.LongTensor([1]) def adapt_target(self, target): """ In order to be efficient, the AdaptiveSoftMax does not compute the scores for all the word of the vocabulary for all the examples. It is thus necessary to call the method adapt_target of the AdaptiveSoftMax layer inside each forward pass. """ target = target.view(-1) new_target = [target.clone()] target_idxs = [] for i in range(len(self.cutoff) - 1): mask = target.ge(self.cutoff[i]).mul(target.lt(self.cutoff[i + 1])) new_target[0][mask] = self.cutoff[0] + i - self.buggy_offset if mask.any(): target_idxs.append(mask.nonzero().squeeze(1)) new_target.append(target[mask].add(-self.cutoff[i])) else: target_idxs.append(None) new_target.append(None) return new_target, target_idxs def forward(self, input, target): """ Args: input: (b x t x d) target: (b x t) Returns: 2 lists: output for each cutoff section and new targets by cut off """ input = input.contiguous().view(-1, input.size(-1)) input = F.dropout(input, p=self.dropout, training=self.training) new_target, target_idxs = self.adapt_target(target) output = [self.head(input)] for i in range(len(target_idxs)): if target_idxs[i] is not None: output.append(self.tail[i](input.index_select(0, target_idxs[i]))) else: output.append(None) return output, new_target def get_log_prob(self, input, target): """ Computes the log probabilities for all the words of the vocabulary, given a 2D tensor of hidden vectors. """ bsz, length, dim = input.size() input = input.contiguous().view(-1, dim) if target is not None: _, target_idxs = self.adapt_target(target) else: target_idxs = None head_y = self.head(input) log_probs = head_y.new_zeros(input.size(0), self.vocab_size) head_sz = self.cutoff[0] + len(self.tail) log_probs[:, :head_sz] = self.lsm(head_y) tail_priors = log_probs[:, self.cutoff[0] - self.buggy_offset: head_sz - self.buggy_offset].clone() for i in range(len(self.tail)): start = self.cutoff[i] end = self.cutoff[i + 1] if target_idxs is None: tail_out = log_probs[:, start:end] tail_out.copy_(self.tail[i](input)) log_probs[:, start:end] = self.lsm(tail_out).add_(tail_priors[:, i, None]) elif target_idxs[i] is not None: idxs = target_idxs[i] tail_out = log_probs[idxs, start:end] tail_out.copy_(self.tail[i](input[idxs])) log_probs[idxs, start:end] = self.lsm(tail_out).add_(tail_priors[idxs, i, None]) log_probs = log_probs.view(bsz, length, -1) return log_probs
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/modules/beamable_mm.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import torch import torch.nn as nn class BeamableMM(nn.Module): """This module provides an optimized MM for beam decoding with attention. It leverage the fact that the source-side of the input is replicated beam times and the target-side of the input is of width one. This layer speeds up inference by replacing the inputs {(bsz x 1 x nhu), (bsz x sz2 x nhu)} with smaller inputs {(bsz/beam x beam x nhu), (bsz/beam x sz2 x nhu)}. """ def __init__(self, beam_size=None): super(BeamableMM, self).__init__() self.beam_size = beam_size def forward(self, input1, input2): if ( not self.training and # test mode self.beam_size is not None and # beam size is set input1.dim() == 3 and # only support batched input input1.size(1) == 1 # single time step update ): bsz, beam = input1.size(0), self.beam_size # bsz x 1 x nhu --> bsz/beam x beam x nhu input1 = input1[:, 0, :].unfold(0, beam, beam).transpose(2, 1) # bsz x sz2 x nhu --> bsz/beam x sz2 x nhu input2 = input2.unfold(0, beam, beam)[:, :, :, 0] # use non batched operation if bsz = beam if input1.size(0) == 1: output = torch.mm(input1[0, :, :], input2[0, :, :]) else: output = input1.bmm(input2) return output.view(bsz, 1, -1) else: return input1.bmm(input2) def set_beam_size(self, beam_size): self.beam_size = beam_size
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/modules/character_token_embedder.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import numpy as np import torch import torch.nn.functional as F from torch import nn from torch.nn.utils.rnn import pad_sequence from typing import List, Tuple from .highway import Highway from fairseq.data import Dictionary class CharacterTokenEmbedder(torch.nn.Module): def __init__( self, vocab: Dictionary, filters: List[Tuple[int, int]], char_embed_dim: int, word_embed_dim: int, highway_layers: int, max_char_len: int = 50, ): super(CharacterTokenEmbedder, self).__init__() self.embedding_dim = word_embed_dim self.char_embeddings = nn.Embedding(257, char_embed_dim, padding_idx=0) self.symbol_embeddings = nn.Parameter(torch.FloatTensor(2, word_embed_dim)) self.eos_idx, self.unk_idx = 0, 1 self.convolutions = nn.ModuleList() for width, out_c in filters: self.convolutions.append( nn.Conv1d(char_embed_dim, out_c, kernel_size=width) ) final_dim = sum(f[1] for f in filters) self.highway = Highway(final_dim, highway_layers) self.projection = nn.Linear(final_dim, word_embed_dim) self.set_vocab(vocab, max_char_len) self.reset_parameters() def set_vocab(self, vocab, max_char_len): word_to_char = torch.LongTensor(len(vocab), max_char_len) truncated = 0 for i in range(len(vocab)): if i < vocab.nspecial: char_idxs = [0] * max_char_len else: chars = vocab[i].encode() # +1 for padding char_idxs = [c + 1 for c in chars] + [0] * (max_char_len - len(chars)) if len(char_idxs) > max_char_len: truncated += 1 char_idxs = char_idxs[:max_char_len] word_to_char[i] = torch.LongTensor(char_idxs) if truncated > 0: print('Truncated {} words longer than {} characters'.format(truncated, max_char_len)) self.vocab = vocab self.word_to_char = word_to_char @property def padding_idx(self): return self.vocab.pad() def reset_parameters(self): nn.init.xavier_normal_(self.char_embeddings.weight) nn.init.xavier_normal_(self.symbol_embeddings) nn.init.xavier_normal_(self.projection.weight) nn.init.constant_(self.char_embeddings.weight[self.char_embeddings.padding_idx], 0.) nn.init.constant_(self.projection.bias, 0.) def forward( self, words: torch.Tensor, ): self.word_to_char = self.word_to_char.type_as(words) flat_words = words.view(-1) word_embs = self._convolve(self.word_to_char[flat_words]) pads = flat_words.eq(self.vocab.pad()) if pads.any(): word_embs[pads] = 0 eos = flat_words.eq(self.vocab.eos()) if eos.any(): word_embs[eos] = self.symbol_embeddings[self.eos_idx] unk = flat_words.eq(self.vocab.unk()) if unk.any(): word_embs[unk] = self.symbol_embeddings[self.unk_idx] return word_embs.view(words.size() + (-1,)) def _convolve( self, char_idxs: torch.Tensor, ): char_embs = self.char_embeddings(char_idxs) char_embs = char_embs.transpose(1, 2) # BTC -> BCT conv_result = [] for i, conv in enumerate(self.convolutions): x = conv(char_embs) x, _ = torch.max(x, -1) x = F.relu(x) conv_result.append(x) conv_result = torch.cat(conv_result, dim=-1) conv_result = self.highway(conv_result) return self.projection(conv_result)
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/modules/conv_tbc.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import torch from torch.nn.modules.utils import _single class ConvTBC(torch.nn.Module): """1D convolution over an input of shape (time x batch x channel) The implementation uses gemm to perform the convolution. This implementation is faster than cuDNN for small kernel sizes. """ def __init__(self, in_channels, out_channels, kernel_size, padding=0): super(ConvTBC, self).__init__() self.in_channels = in_channels self.out_channels = out_channels self.kernel_size = _single(kernel_size) self.padding = _single(padding) self.weight = torch.nn.Parameter(torch.Tensor( self.kernel_size[0], in_channels, out_channels)) self.bias = torch.nn.Parameter(torch.Tensor(out_channels)) def forward(self, input): return torch.conv_tbc(input.contiguous(), self.weight, self.bias, self.padding[0]) def __repr__(self): s = ('{name}({in_channels}, {out_channels}, kernel_size={kernel_size}' ', padding={padding}') if self.bias is None: s += ', bias=False' s += ')' return s.format(name=self.__class__.__name__, **self.__dict__)
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/modules/downsampled_multihead_attention.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. # import math import torch import torch.nn as nn import torch.nn.functional as F from fairseq.modules.scalar_bias import scalar_bias class SingleHeadAttention(nn.Module): """ Single-head attention that supports Gating and Downsampling """ def __init__( self, out_channels, embed_dim, head_dim, head_index, dropout=0., bias=True, project_input=True, gated=False, downsample=False, num_heads=1, ): super().__init__() self.embed_dim = embed_dim self.dropout = dropout self.head_index = head_index self.head_dim = head_dim self.project_input = project_input self.gated = gated self.downsample = downsample self.num_heads = num_heads self.projection = None k_layers = [] v_layers = [] if self.downsample: k_layers.append(Downsample(self.head_index)) v_layers.append(Downsample(self.head_index)) out_proj_size = self.head_dim else: out_proj_size = self.head_dim * self.num_heads if self.gated: k_layers.append(GatedLinear(self.embed_dim, out_proj_size, bias=bias)) self.in_proj_q = GatedLinear(self.embed_dim, out_proj_size, bias=bias) v_layers.append(GatedLinear(self.embed_dim, out_proj_size, bias=bias)) else: k_layers.append(Linear(self.embed_dim, out_proj_size, bias=bias)) self.in_proj_q = Linear(self.embed_dim, out_proj_size, bias=bias) v_layers.append(Linear(self.embed_dim, out_proj_size, bias=bias)) self.in_proj_k = nn.Sequential(*k_layers) self.in_proj_v = nn.Sequential(*v_layers) if self.downsample: self.out_proj = Linear(out_proj_size, self.head_dim, bias=bias) else: self.out_proj = Linear(out_proj_size, out_channels, bias=bias) self.scaling = self.head_dim**-0.5 def forward( self, query, key, value, mask_future_timesteps=False, key_padding_mask=None, use_scalar_bias=False, ): """Input shape: Time x Batch x Channel Self-attention can be implemented by passing in the same arguments for query, key and value. Future timesteps can be masked with the `mask_future_timesteps` argument. Padding elements can be excluded from the key by passing a binary ByteTensor (`key_padding_mask`) with shape: batch x src_len, where padding elements are indicated by 1s. """ src_len, bsz, out_channels = key.size() tgt_len = query.size(0) assert list(query.size()) == [tgt_len, bsz, out_channels] assert key.size() == value.size() if key_padding_mask is not None: assert key_padding_mask.size(0) == bsz assert key_padding_mask.size(1) == src_len if self.downsample: size = bsz else: size = bsz * self.num_heads k = key v = value q = query if self.project_input: q = self.in_proj_q(q) k = self.in_proj_k(k) v = self.in_proj_v(v) src_len = k.size()[0] q *= self.scaling if not self.downsample: q = q.view(tgt_len, size, self.head_dim) k = k.view(src_len, size, self.head_dim) v = v.view(src_len, size, self.head_dim) q = q.transpose(0, 1) k = k.transpose(0, 1) v = v.transpose(0, 1) attn_weights = torch.bmm(q, k.transpose(1, 2)) if mask_future_timesteps: assert query.size() == key.size(), \ 'mask_future_timesteps only applies to self-attention' attn_weights *= torch.tril( attn_weights.data.new([1]).expand(tgt_len, tgt_len).clone(), diagonal=-1, )[:, ::self.head_index + 1 if self.downsample else 1].unsqueeze(0) attn_weights += torch.triu( attn_weights.data.new([-math.inf]).expand(tgt_len, tgt_len).clone(), diagonal=0 )[:, ::self.head_index + 1 if self.downsample else 1].unsqueeze(0) tgt_size = tgt_len if use_scalar_bias: attn_weights = scalar_bias(attn_weights, 2) v = scalar_bias(v, 1) tgt_size += 1 if key_padding_mask is not None: # don't attend to padding symbols if key_padding_mask.max() > 0: if self.downsample: attn_weights = attn_weights.view(bsz, 1, tgt_len, src_len) else: attn_weights = attn_weights.view(size, self.num_heads, tgt_len, src_len) attn_weights = attn_weights.masked_fill( key_padding_mask.unsqueeze(1).unsqueeze(2), -math.inf, ) attn_weights = attn_weights.view(size, tgt_len, src_len) attn_weights = F.softmax(attn_weights, dim=-1) attn_weights = F.dropout(attn_weights, p=self.dropout, training=self.training) attn = torch.bmm(attn_weights, v) if self.downsample: attn = attn.transpose(0, 1).contiguous().view(tgt_len, bsz, self.head_dim) else: attn = attn.transpose(0, 1).contiguous().view(tgt_len, bsz, self.embed_dim) attn = self.out_proj(attn) return attn, attn_weights class DownsampledMultiHeadAttention(nn.ModuleList): """ Multi-headed attention with Gating and Downsampling """ def __init__( self, out_channels, embed_dim, num_heads, dropout=0., bias=True, project_input=True, gated=False, downsample=False, ): self.embed_dim = embed_dim self.num_heads = num_heads self.dropout = dropout self.head_dim = embed_dim // num_heads self.downsample = downsample self.gated = gated self.project_input = project_input assert self.head_dim * num_heads == embed_dim if self.downsample: attention_heads = [] for index in range(self.num_heads): attention_heads.append( SingleHeadAttention( out_channels, self.embed_dim, self.head_dim, index, self.dropout, bias, self.project_input, self.gated, self.downsample, self.num_heads, ) ) super().__init__(modules=attention_heads) self.out_proj = Linear(embed_dim, out_channels, bias=bias) else: # either we have a list of attention heads, or just one attention head # if not being downsampled, we can do the heads with one linear layer instead of separate ones super().__init__() self.attention_module = SingleHeadAttention( out_channels, self.embed_dim, self.head_dim, 1, self.dropout, bias, self.project_input, self.gated, self.downsample, self.num_heads, ) def forward( self, query, key, value, mask_future_timesteps=False, key_padding_mask=None, use_scalar_bias=False, ): src_len, bsz, embed_dim = key.size() tgt_len = query.size(0) assert embed_dim == self.embed_dim assert list(query.size()) == [tgt_len, bsz, embed_dim] assert key.size() == value.size() tgt_size = tgt_len if use_scalar_bias: tgt_size += 1 attn = [] attn_weights = [] if self.downsample: for attention_head_number in range(self.num_heads): # call the forward of each attention head _attn, _attn_weight = self[attention_head_number]( query, key, value, mask_future_timesteps, key_padding_mask, use_scalar_bias, ) attn.append(_attn) attn_weights.append(_attn_weight) full_attn = torch.cat(attn, dim=2) full_attn = self.out_proj(full_attn) return full_attn, attn_weights[0].clone() else: _attn, _attn_weight = self.attention_module( query, key, value, mask_future_timesteps, key_padding_mask, use_scalar_bias, ) attn.append(_attn) attn_weights.append(_attn_weight) full_attn = torch.cat(attn, dim=2) full_attn_weights = torch.cat(attn_weights) full_attn_weights = full_attn_weights.view(bsz, self.num_heads, tgt_size, src_len) full_attn_weights = full_attn_weights.sum(dim=1) / self.num_heads return full_attn, full_attn_weights class Downsample(nn.Module): """ Selects every nth element, where n is the index """ def __init__(self, index): super().__init__() self.index = index def forward(self, x): return x[::self.index+1] def Linear(in_features, out_features, dropout=0., bias=True): """Weight-normalized Linear layer (input: B x T x C)""" m = nn.Linear(in_features, out_features, bias=bias) m.weight.data.normal_(mean=0, std=math.sqrt((1 - dropout) / in_features)) m.bias.data.zero_() return nn.utils.weight_norm(m) def GatedLinear(in_features, out_features, dropout=0., bias=True): """Weight-normalized Linear layer (input: B x T x C) with interspersed GLU units""" return nn.Sequential( Linear(in_features, out_features*4, dropout, bias), nn.GLU(), Linear(out_features*2, out_features*2, dropout, bias), nn.GLU(), Linear(out_features, out_features, dropout, bias) )
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/modules/grad_multiply.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import torch class GradMultiply(torch.autograd.Function): @staticmethod def forward(ctx, x, scale): ctx.scale = scale res = x.new(x) return res @staticmethod def backward(ctx, grad): return grad * ctx.scale, None
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/modules/highway.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import torch import torch.nn.functional as F from torch import nn class Highway(torch.nn.Module): """ A `Highway layer <https://arxiv.org/abs/1505.00387>`_. Adopted from the AllenNLP implementation. """ def __init__( self, input_dim: int, num_layers: int = 1 ): super(Highway, self).__init__() self.input_dim = input_dim self.layers = nn.ModuleList([nn.Linear(input_dim, input_dim * 2) for _ in range(num_layers)]) self.activation = nn.ReLU() self.reset_parameters() def reset_parameters(self): for layer in self.layers: # As per comment in AllenNLP: # We should bias the highway layer to just carry its input forward. We do that by # setting the bias on `B(x)` to be positive, because that means `g` will be biased to # be high, so we will carry the input forward. The bias on `B(x)` is the second half # of the bias vector in each Linear layer. nn.init.constant_(layer.bias[self.input_dim:], 1) nn.init.constant_(layer.bias[:self.input_dim], 0) nn.init.xavier_normal_(layer.weight) def forward( self, x: torch.Tensor ): for layer in self.layers: projection = layer(x) proj_x, gate = projection.chunk(2, dim=-1) proj_x = self.activation(proj_x) gate = F.sigmoid(gate) x = gate * x + (1 - gate) * proj_x return x
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/modules/learned_positional_embedding.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import torch.nn as nn from fairseq import utils class LearnedPositionalEmbedding(nn.Embedding): """This module learns positional embeddings up to a fixed maximum size. Padding symbols are ignored, but it is necessary to specify whether padding is added on the left side (left_pad=True) or right side (left_pad=False). """ def __init__(self, num_embeddings, embedding_dim, padding_idx, left_pad): super().__init__(num_embeddings, embedding_dim, padding_idx) self.left_pad = left_pad def forward(self, input, incremental_state=None): """Input is expected to be of size [bsz x seqlen].""" if incremental_state is not None: # positions is the same for every token when decoding a single step positions = input.data.new(1, 1).fill_(self.padding_idx + input.size(1)) else: positions = utils.make_positions(input.data, self.padding_idx, self.left_pad) return super().forward(positions) def max_positions(self): """Maximum number of supported positions.""" return self.num_embeddings - self.padding_idx - 1
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/modules/linearized_convolution.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import torch import torch.nn.functional as F from fairseq import utils from .conv_tbc import ConvTBC class LinearizedConvolution(ConvTBC): """An optimized version of nn.Conv1d. At training time, this module uses ConvTBC, which is an optimized version of Conv1d. At inference time, it optimizes incremental generation (i.e., one time step at a time) by replacing the convolutions with linear layers. Note that the input order changes from training to inference. """ def __init__(self, in_channels, out_channels, kernel_size, **kwargs): super().__init__(in_channels, out_channels, kernel_size, **kwargs) self._linearized_weight = None self.register_backward_hook(self._clear_linearized_weight) def forward(self, input, incremental_state=None): """ Args: incremental_state: Used to buffer signal; if not None, then input is expected to contain a single frame. If the input order changes between time steps, call reorder_incremental_state. Input: Time x Batch x Channel during training Batch x Time x Channel during inference """ if incremental_state is None: output = super().forward(input) if self.kernel_size[0] > 1 and self.padding[0] > 0: # remove future timesteps added by padding output = output[:-self.padding[0], :, :] return output # reshape weight weight = self._get_linearized_weight() kw = self.kernel_size[0] bsz = input.size(0) # input: bsz x len x dim if kw > 1: input = input.data input_buffer = self._get_input_buffer(incremental_state) if input_buffer is None: input_buffer = input.new(bsz, kw, input.size(2)).zero_() self._set_input_buffer(incremental_state, input_buffer) else: # shift buffer input_buffer[:, :-1, :] = input_buffer[:, 1:, :].clone() # append next input input_buffer[:, -1, :] = input[:, -1, :] input = input_buffer with torch.no_grad(): output = F.linear(input.view(bsz, -1), weight, self.bias) return output.view(bsz, 1, -1) def reorder_incremental_state(self, incremental_state, new_order): input_buffer = self._get_input_buffer(incremental_state) if input_buffer is not None: input_buffer = input_buffer.index_select(0, new_order) self._set_input_buffer(incremental_state, input_buffer) def _get_input_buffer(self, incremental_state): return utils.get_incremental_state(self, incremental_state, 'input_buffer') def _set_input_buffer(self, incremental_state, new_buffer): return utils.set_incremental_state(self, incremental_state, 'input_buffer', new_buffer) def _get_linearized_weight(self): if self._linearized_weight is None: kw = self.kernel_size[0] weight = self.weight.transpose(2, 1).transpose(1, 0).contiguous() assert weight.size() == (self.out_channels, kw, self.in_channels) self._linearized_weight = weight.view(self.out_channels, -1) return self._linearized_weight def _clear_linearized_weight(self, *args): self._linearized_weight = None
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/modules/multihead_attention.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import torch from torch import nn from torch.nn import Parameter import torch.nn.functional as F from fairseq import utils class MultiheadAttention(nn.Module): """Multi-headed attention. See "Attention Is All You Need" for more details. """ def __init__(self, embed_dim, num_heads, dropout=0., bias=True, add_bias_kv=False, add_zero_attn=False): super().__init__() self.embed_dim = embed_dim self.num_heads = num_heads self.dropout = dropout self.head_dim = embed_dim // num_heads assert self.head_dim * num_heads == self.embed_dim, "embed_dim must be divisible by num_heads" self.scaling = self.head_dim ** -0.5 self.in_proj_weight = Parameter(torch.Tensor(3 * embed_dim, embed_dim)) if bias: self.in_proj_bias = Parameter(torch.Tensor(3 * embed_dim)) else: self.register_parameter('in_proj_bias', None) self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias) if add_bias_kv: self.bias_k = Parameter(torch.Tensor(1, 1, embed_dim)) self.bias_v = Parameter(torch.Tensor(1, 1, embed_dim)) else: self.bias_k = self.bias_v = None self.add_zero_attn = add_zero_attn self.reset_parameters() self.onnx_trace = False def prepare_for_onnx_export_(self): self.onnx_trace = True def reset_parameters(self): nn.init.normal_(self.in_proj_weight, std=self.embed_dim ** -0.5) nn.init.normal_(self.out_proj.weight, std=self.embed_dim ** -0.5) if self.in_proj_bias is not None: nn.init.constant_(self.in_proj_bias, 0.) nn.init.constant_(self.out_proj.bias, 0.) if self.bias_k is not None: nn.init.xavier_normal_(self.bias_k) if self.bias_v is not None: nn.init.xavier_normal_(self.bias_v) def forward(self, query, key, value, key_padding_mask=None, incremental_state=None, need_weights=True, static_kv=False, attn_mask=None): """Input shape: Time x Batch x Channel Self-attention can be implemented by passing in the same arguments for query, key and value. Timesteps can be masked by supplying a T x T mask in the `attn_mask` argument. Padding elements can be excluded from the key by passing a binary ByteTensor (`key_padding_mask`) with shape: batch x src_len, where padding elements are indicated by 1s. """ qkv_same = query.data_ptr() == key.data_ptr() == value.data_ptr() kv_same = key.data_ptr() == value.data_ptr() tgt_len, bsz, embed_dim = query.size() assert embed_dim == self.embed_dim assert list(query.size()) == [tgt_len, bsz, embed_dim] assert key.size() == value.size() if incremental_state is not None: saved_state = self._get_input_buffer(incremental_state) if 'prev_key' in saved_state: # previous time steps are cached - no need to recompute # key and value if they are static if static_kv: assert kv_same and not qkv_same key = value = None else: saved_state = None if qkv_same: # self-attention q, k, v = self.in_proj_qkv(query) elif kv_same: # encoder-decoder attention q = self.in_proj_q(query) if key is None: assert value is None k = v = None else: k, v = self.in_proj_kv(key) else: q = self.in_proj_q(query) k = self.in_proj_k(key) v = self.in_proj_v(value) q *= self.scaling if saved_state is not None: if 'prev_key' in saved_state: if static_kv: k = saved_state['prev_key'] else: k = torch.cat((saved_state['prev_key'], k), dim=0) if 'prev_value' in saved_state: if static_kv: v = saved_state['prev_value'] else: v = torch.cat((saved_state['prev_value'], v), dim=0) saved_state['prev_key'] = k saved_state['prev_value'] = v self._set_input_buffer(incremental_state, saved_state) if self.bias_k is not None: assert self.bias_v is not None k = torch.cat([k, self.bias_k.repeat(1, bsz, 1)]) v = torch.cat([v, self.bias_v.repeat(1, bsz, 1)]) if attn_mask is not None: attn_mask = torch.cat([attn_mask, attn_mask.new_zeros(attn_mask.size(0), 1)], dim=1) if key_padding_mask is not None: key_padding_mask = torch.cat( [key_padding_mask, key_padding_mask.new_zeros(key_padding_mask.size(0), 1)], dim=1) src_len = k.size(0) if key_padding_mask is not None: assert key_padding_mask.size(0) == bsz assert key_padding_mask.size(1) == src_len q = q.contiguous().view(tgt_len, bsz * self.num_heads, self.head_dim).transpose(0, 1) k = k.contiguous().view(src_len, bsz * self.num_heads, self.head_dim).transpose(0, 1) v = v.contiguous().view(src_len, bsz * self.num_heads, self.head_dim).transpose(0, 1) if self.add_zero_attn: src_len += 1 k = torch.cat([k, k.new_zeros((k.size(0), 1) + k.size()[2:])], dim=1) v = torch.cat([v, v.new_zeros((v.size(0), 1) + v.size()[2:])], dim=1) if attn_mask is not None: attn_mask = torch.cat([attn_mask, attn_mask.new_zeros(attn_mask.size(0), 1)], dim=1) if key_padding_mask is not None: key_padding_mask = torch.cat([key_padding_mask, key_padding_mask.new_zeros(key_padding_mask.size(0), 1)], dim=1) attn_weights = torch.bmm(q, k.transpose(1, 2)) assert list(attn_weights.size()) == [bsz * self.num_heads, tgt_len, src_len] if attn_mask is not None: attn_weights += attn_mask.unsqueeze(0) if key_padding_mask is not None: # don't attend to padding symbols attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) attn_weights = attn_weights.float().masked_fill( key_padding_mask.unsqueeze(1).unsqueeze(2), float('-inf'), ).type_as(attn_weights) # FP16 support: cast to float and back attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len) attn_weights = F.softmax(attn_weights.float(), dim=-1).type_as(attn_weights) attn_weights = F.dropout(attn_weights, p=self.dropout, training=self.training) attn = torch.bmm(attn_weights, v) assert list(attn.size()) == [bsz * self.num_heads, tgt_len, self.head_dim] attn = attn.transpose(0, 1).contiguous().view(tgt_len, bsz, embed_dim) attn = self.out_proj(attn) if need_weights: # average attention weights over heads attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) attn_weights = attn_weights.sum(dim=1) / self.num_heads else: attn_weights = None return attn, attn_weights def in_proj_qkv(self, query): return self._in_proj(query).chunk(3, dim=-1) def in_proj_kv(self, key): return self._in_proj(key, start=self.embed_dim).chunk(2, dim=-1) def in_proj_q(self, query): return self._in_proj(query, end=self.embed_dim) def in_proj_k(self, key): return self._in_proj(key, start=self.embed_dim, end=2 * self.embed_dim) def in_proj_v(self, value): return self._in_proj(value, start=2 * self.embed_dim) def _in_proj(self, input, start=0, end=None): weight = self.in_proj_weight bias = self.in_proj_bias weight = weight[start:end, :] if bias is not None: bias = bias[start:end] return F.linear(input, weight, bias) def reorder_incremental_state(self, incremental_state, new_order): """Reorder buffered internal state (for incremental generation).""" input_buffer = self._get_input_buffer(incremental_state) if input_buffer is not None: for k in input_buffer.keys(): input_buffer[k] = input_buffer[k].index_select(1, new_order) self._set_input_buffer(incremental_state, input_buffer) def _get_input_buffer(self, incremental_state): return utils.get_incremental_state( self, incremental_state, 'attn_state', ) or {} def _set_input_buffer(self, incremental_state, buffer): utils.set_incremental_state( self, incremental_state, 'attn_state', buffer, )
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/modules/scalar_bias.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. # import torch class ScalarBias(torch.autograd.Function): """ Adds a vector of scalars, used in self-attention mechanism to allow the model to optionally attend to this vector instead of the past """ @staticmethod def forward(ctx, input, dim, bias_init): size = list(input.size()) size[dim] += 1 output = input.new(*size).fill_(bias_init) output.narrow(dim, 1, size[dim] - 1).copy_(input) ctx.dim = dim return output @staticmethod def backward(ctx, grad): return grad.narrow(ctx.dim, 1, grad.size(ctx.dim) - 1), None, None def scalar_bias(input, dim, bias_init=0): return ScalarBias.apply(input, dim, bias_init)
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/modules/sinusoidal_positional_embedding.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import math import torch import torch.nn as nn import torch.onnx.operators from fairseq import utils class SinusoidalPositionalEmbedding(nn.Module): """This module produces sinusoidal positional embeddings of any length. Padding symbols are ignored, but it is necessary to specify whether padding is added on the left side (left_pad=True) or right side (left_pad=False). """ def __init__(self, embedding_dim, padding_idx, left_pad, init_size=1024): super().__init__() self.embedding_dim = embedding_dim self.padding_idx = padding_idx self.left_pad = left_pad self.weights = SinusoidalPositionalEmbedding.get_embedding( init_size, embedding_dim, padding_idx, ) self.onnx_trace = False self.register_buffer('_float_tensor', torch.FloatTensor(1)) def prepare_for_onnx_export_(self): self.onnx_trace = True @staticmethod def get_embedding(num_embeddings, embedding_dim, padding_idx=None): """Build sinusoidal embeddings. This matches the implementation in tensor2tensor, but differs slightly from the description in Section 3.5 of "Attention Is All You Need". """ half_dim = embedding_dim // 2 emb = math.log(10000) / (half_dim - 1) emb = torch.exp(torch.arange(half_dim, dtype=torch.float) * -emb) emb = torch.arange(num_embeddings, dtype=torch.float).unsqueeze(1) * emb.unsqueeze(0) emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1).view(num_embeddings, -1) if embedding_dim % 2 == 1: # zero pad emb = torch.cat([emb, torch.zeros(num_embeddings, 1)], dim=1) if padding_idx is not None: emb[padding_idx, :] = 0 return emb def forward(self, input, incremental_state=None, timestep=None): """Input is expected to be of size [bsz x seqlen].""" bsz, seq_len = torch.onnx.operators.shape_as_tensor(input) max_pos = self.padding_idx + 1 + seq_len if self.weights is None or max_pos > self.weights.size(0): # recompute/expand embeddings if needed self.weights = SinusoidalPositionalEmbedding.get_embedding( max_pos, self.embedding_dim, self.padding_idx, ) self.weights = self.weights.type_as(self._float_tensor) if incremental_state is not None: # positions is the same for every token when decoding a single step pos = (timestep.int() + 1).long() if timestep is not None else seq_len if self.onnx_trace: return self.weights[self.padding_idx + pos, :].unsqueeze(1).repeat(bsz, 1, 1) return self.weights[self.padding_idx + pos, :].expand(bsz, 1, -1) positions = utils.make_positions(input, self.padding_idx, self.left_pad, self.onnx_trace) if self.onnx_trace: flat_embeddings = self.weights.detach().index_select(0, positions.view(-1)) embedding_shape = torch.cat((bsz.view(1), seq_len.view(1), torch.LongTensor([-1]))) embeddings = torch.onnx.operators.reshape_from_tensor_shape(flat_embeddings, embedding_shape) return embeddings return self.weights.index_select(0, positions.view(-1)).view(bsz, seq_len, -1).detach() def max_positions(self): """Maximum number of supported positions.""" return int(1e5) # an arbitrary large number
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/multiprocessing_pdb.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import multiprocessing import os import pdb import sys class MultiprocessingPdb(pdb.Pdb): """A Pdb wrapper that works in a multiprocessing environment. Usage: `from fairseq import pdb; pdb.set_trace()` """ _stdin_fd = sys.stdin.fileno() _stdin = None _stdin_lock = multiprocessing.Lock() def __init__(self): pdb.Pdb.__init__(self, nosigint=True) def _cmdloop(self): stdin_bak = sys.stdin with self._stdin_lock: try: if not self._stdin: self._stdin = os.fdopen(self._stdin_fd) sys.stdin = self._stdin self.cmdloop() finally: sys.stdin = stdin_bak pdb = MultiprocessingPdb()
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/optim/__init__.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import importlib import os from .fairseq_optimizer import FairseqOptimizer from .fp16_optimizer import FP16Optimizer OPTIMIZER_REGISTRY = {} OPTIMIZER_CLASS_NAMES = set() def build_optimizer(args, params): params = list(filter(lambda p: p.requires_grad, params)) return OPTIMIZER_REGISTRY[args.optimizer](args, params) def register_optimizer(name): """Decorator to register a new optimizer.""" def register_optimizer_cls(cls): if name in OPTIMIZER_REGISTRY: raise ValueError('Cannot register duplicate optimizer ({})'.format(name)) if not issubclass(cls, FairseqOptimizer): raise ValueError('Optimizer ({}: {}) must extend FairseqOptimizer'.format(name, cls.__name__)) if cls.__name__ in OPTIMIZER_CLASS_NAMES: # We use the optimizer class name as a unique identifier in # checkpoints, so all optimizer must have unique class names. raise ValueError('Cannot register optimizer with duplicate class name ({})'.format(cls.__name__)) OPTIMIZER_REGISTRY[name] = cls OPTIMIZER_CLASS_NAMES.add(cls.__name__) return cls return register_optimizer_cls # automatically import any Python files in the optim/ directory for file in os.listdir(os.path.dirname(__file__)): if file.endswith('.py') and not file.startswith('_'): module = file[:file.find('.py')] importlib.import_module('fairseq.optim.' + module)
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/optim/adagrad.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import torch.optim from . import FairseqOptimizer, register_optimizer @register_optimizer('adagrad') class Adagrad(FairseqOptimizer): def __init__(self, args, params): super().__init__(args, params) self._optimizer = torch.optim.Adagrad(params, **self.optimizer_config) @property def optimizer_config(self): """ Return a kwarg dictionary that will be used to override optimizer args stored in checkpoints. This allows us to load a checkpoint and resume training using a different set of optimizer args, e.g., with a different learning rate. """ return { 'lr': self.args.lr[0], 'weight_decay': self.args.weight_decay, }
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/optim/adam.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import math import torch import torch.optim from . import FairseqOptimizer, register_optimizer @register_optimizer('adam') class FairseqAdam(FairseqOptimizer): def __init__(self, args, params): super().__init__(args, params) self._optimizer = Adam(params, **self.optimizer_config) @staticmethod def add_args(parser): """Add optimizer-specific arguments to the parser.""" parser.add_argument('--adam-betas', default='(0.9, 0.999)', metavar='B', help='betas for Adam optimizer') parser.add_argument('--adam-eps', type=float, default=1e-8, metavar='D', help='epsilon for Adam optimizer') @property def optimizer_config(self): """ Return a kwarg dictionary that will be used to override optimizer args stored in checkpoints. This allows us to load a checkpoint and resume training using a different set of optimizer args, e.g., with a different learning rate. """ return { 'lr': self.args.lr[0], 'betas': eval(self.args.adam_betas), 'eps': self.args.adam_eps, 'weight_decay': self.args.weight_decay, } class Adam(torch.optim.Optimizer): """Implements Adam algorithm. This implementation is modified from torch.optim.Adam based on: `Fixed Weight Decay Regularization in Adam` (see https://arxiv.org/abs/1711.05101) It has been proposed in `Adam: A Method for Stochastic Optimization`_. Arguments: params (iterable): iterable of parameters to optimize or dicts defining parameter groups lr (float, optional): learning rate (default: 1e-3) betas (Tuple[float, float], optional): coefficients used for computing running averages of gradient and its square (default: (0.9, 0.999)) eps (float, optional): term added to the denominator to improve numerical stability (default: 1e-8) weight_decay (float, optional): weight decay (L2 penalty) (default: 0) amsgrad (boolean, optional): whether to use the AMSGrad variant of this algorithm from the paper `On the Convergence of Adam and Beyond`_ .. _Adam\: A Method for Stochastic Optimization: https://arxiv.org/abs/1412.6980 .. _On the Convergence of Adam and Beyond: https://openreview.net/forum?id=ryQu7f-RZ """ def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0, amsgrad=False): defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay, amsgrad=amsgrad) super(Adam, self).__init__(params, defaults) def step(self, closure=None): """Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() for group in self.param_groups: for p in group['params']: if p.grad is None: continue grad = p.grad.data if grad.is_sparse: raise RuntimeError('Adam does not support sparse gradients, please consider SparseAdam instead') amsgrad = group['amsgrad'] state = self.state[p] # State initialization if len(state) == 0: state['step'] = 0 # Exponential moving average of gradient values state['exp_avg'] = torch.zeros_like(p.data) # Exponential moving average of squared gradient values state['exp_avg_sq'] = torch.zeros_like(p.data) if amsgrad: # Maintains max of all exp. moving avg. of sq. grad. values state['max_exp_avg_sq'] = torch.zeros_like(p.data) exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq'] if amsgrad: max_exp_avg_sq = state['max_exp_avg_sq'] beta1, beta2 = group['betas'] state['step'] += 1 # Decay the first and second moment running average coefficient exp_avg.mul_(beta1).add_(1 - beta1, grad) exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad) if amsgrad: # Maintains the maximum of all 2nd moment running avg. till now torch.max(max_exp_avg_sq, exp_avg_sq, out=max_exp_avg_sq) # Use the max. for normalizing running avg. of gradient denom = max_exp_avg_sq.sqrt().add_(group['eps']) else: denom = exp_avg_sq.sqrt().add_(group['eps']) bias_correction1 = 1 - beta1 ** state['step'] bias_correction2 = 1 - beta2 ** state['step'] step_size = group['lr'] * math.sqrt(bias_correction2) / bias_correction1 if group['weight_decay'] != 0: p.data.add_(-group['weight_decay'] * group['lr'], p.data) p.data.addcdiv_(-step_size, exp_avg, denom) return loss
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/optim/fairseq_optimizer.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import math import torch class FairseqOptimizer(object): def __init__(self, args, params): super().__init__() self.args = args self.params = list(params) @staticmethod def add_args(parser): """Add optimizer-specific arguments to the parser.""" pass @property def optimizer(self): """Return a torch.optim.optimizer.Optimizer instance.""" if not hasattr(self, '_optimizer'): raise NotImplementedError if not isinstance(self._optimizer, torch.optim.Optimizer): raise ValueError('_optimizer must be an instance of torch.optim.Optimizer') return self._optimizer @property def optimizer_config(self): """ Return a kwarg dictionary that will be used to override optimizer args stored in checkpoints. This allows us to load a checkpoint and resume training using a different set of optimizer args, e.g., with a different learning rate. """ raise NotImplementedError def get_lr(self): """Return the current learning rate.""" return self.optimizer.param_groups[0]['lr'] def set_lr(self, lr): """Set the learning rate.""" for param_group in self.optimizer.param_groups: param_group['lr'] = lr def state_dict(self): """Return the optimizer's state dict.""" return self.optimizer.state_dict() def load_state_dict(self, state_dict, optimizer_overrides=None): """Load an optimizer state dict. In general we should prefer the configuration of the existing optimizer instance (e.g., learning rate) over that found in the state_dict. This allows us to resume training from a checkpoint using a new set of optimizer args. """ self.optimizer.load_state_dict(state_dict) if optimizer_overrides is not None and len(optimizer_overrides) > 0: # override learning rate, momentum, etc. with latest values for group in self.optimizer.param_groups: group.update(optimizer_overrides) def backward(self, loss): loss.backward() def multiply_grads(self, c): """Multiplies grads by a constant ``c``.""" for p in self.params: p.grad.data.mul_(c) def clip_grad_norm(self, max_norm): """Clips gradient norm.""" if max_norm > 0: return torch.nn.utils.clip_grad_norm_(self.params, max_norm) else: return math.sqrt(sum(p.grad.data.norm()**2 for p in self.params)) def step(self, closure=None): """Performs a single optimization step.""" self.optimizer.step(closure) def zero_grad(self): """Clears the gradients of all optimized parameters.""" self.optimizer.zero_grad()
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/optim/fp16_optimizer.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import torch from fairseq import optim, utils class DynamicLossScaler: def __init__(self, init_scale=2.**15, scale_factor=2., scale_window=2000): self.loss_scale = init_scale self.scale_factor = scale_factor self.scale_window = scale_window self._iter = 0 self._last_overflow_iter = -1 def update_scale(self, overflow): if overflow: self.loss_scale /= self.scale_factor self._last_overflow_iter = self._iter elif (self._iter - self._last_overflow_iter) % self.scale_window == 0: self.loss_scale *= self.scale_factor self._iter += 1 @staticmethod def has_overflow(grad_norm): # detect inf and nan if grad_norm == float('inf') or grad_norm != grad_norm: return True return False class FP16Optimizer(optim.FairseqOptimizer): def __init__(self, args, params, fp32_optimizer, fp32_params): super().__init__(args, params) self.fp32_optimizer = fp32_optimizer self.fp32_params = fp32_params self.scaler = DynamicLossScaler( init_scale=args.fp16_init_scale, scale_window=(2**14 / args.distributed_world_size), ) @staticmethod def build_optimizer(args, params): # create FP32 copy of parameters and grads total_param_size = sum(p.data.numel() for p in params) fp32_params = params[0].new(0).float().new(total_param_size) offset = 0 for p in params: numel = p.data.numel() fp32_params[offset:offset+numel].copy_(p.data.view(-1)) offset += numel fp32_params = torch.nn.Parameter(fp32_params) fp32_params.grad = fp32_params.data.new(total_param_size) fp32_optimizer = optim.build_optimizer(args, [fp32_params]) return FP16Optimizer(args, params, fp32_optimizer, fp32_params) @property def optimizer(self): return self.fp32_optimizer.optimizer @property def optimizer_config(self): return self.fp32_optimizer.optimizer_config def get_lr(self): return self.fp32_optimizer.get_lr() def set_lr(self, lr): self.fp32_optimizer.set_lr(lr) def state_dict(self): """Return the optimizer's state dict.""" state_dict = self.fp32_optimizer.state_dict() state_dict['loss_scale'] = self.scaler.loss_scale return state_dict def load_state_dict(self, state_dict, optimizer_overrides=None): """Load an optimizer state dict. In general we should prefer the configuration of the existing optimizer instance (e.g., learning rate) over that found in the state_dict. This allows us to resume training from a checkpoint using a new set of optimizer args. """ if 'loss_scale' in state_dict: self.scaler.loss_scale = state_dict['loss_scale'] self.fp32_optimizer.load_state_dict(state_dict, optimizer_overrides) def backward(self, loss): loss = loss * self.scaler.loss_scale loss.backward() self._needs_sync = True def _sync_fp16_grads_to_fp32(self, multiply_grads=1.): if self._needs_sync: # copy FP16 grads to FP32 offset = 0 for p in self.params: if not p.requires_grad: continue grad_data = p.grad.data if p.grad is not None else p.data.new_zeros(p.data.shape) numel = grad_data.numel() self.fp32_params.grad.data[offset:offset+numel].copy_(grad_data.view(-1)) offset += numel # correct for dynamic loss scaler self.fp32_params.grad.data.mul_(multiply_grads / self.scaler.loss_scale) self._needs_sync = False def multiply_grads(self, c): """Multiplies grads by a constant ``c``.""" if self._needs_sync: self._sync_fp16_grads_to_fp32(c) else: self.fp32_params.grad.data.mul_(c) def clip_grad_norm(self, max_norm): """Clips gradient norm and updates dynamic loss scaler.""" self._sync_fp16_grads_to_fp32() grad_norm = utils.clip_grad_norm_(self.fp32_params.grad.data, max_norm) # detect overflow and adjust loss scale overflow = DynamicLossScaler.has_overflow(grad_norm) self.scaler.update_scale(overflow) if overflow: if self.scaler.loss_scale <= self.args.min_loss_scale: raise Exception(( 'Minimum loss scale reached ({}). Your loss is probably exploding. ' 'Try lowering the learning rate, using gradient clipping or ' 'increasing the batch size.' ).format(self.args.min_loss_scale)) raise OverflowError('setting loss scale to: ' + str(self.scaler.loss_scale)) return grad_norm def step(self, closure=None): """Performs a single optimization step.""" self._sync_fp16_grads_to_fp32() self.fp32_optimizer.step(closure) # copy FP32 params back into FP16 model offset = 0 for p in self.params: if not p.requires_grad: continue numel = p.data.numel() p.data.copy_(self.fp32_params.data[offset:offset+numel].view_as(p.data)) offset += numel def zero_grad(self): """Clears the gradients of all optimized parameters.""" self.fp32_optimizer.zero_grad() for p in self.params: if p.grad is not None: p.grad.detach_() p.grad.zero_() self._needs_sync = False
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/optim/lr_scheduler/__init__.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import importlib import os from .fairseq_lr_scheduler import FairseqLRScheduler LR_SCHEDULER_REGISTRY = {} def build_lr_scheduler(args, optimizer): return LR_SCHEDULER_REGISTRY[args.lr_scheduler](args, optimizer) def register_lr_scheduler(name): """Decorator to register a new LR scheduler.""" def register_lr_scheduler_cls(cls): if name in LR_SCHEDULER_REGISTRY: raise ValueError('Cannot register duplicate LR scheduler ({})'.format(name)) if not issubclass(cls, FairseqLRScheduler): raise ValueError('LR Scheduler ({}: {}) must extend FairseqLRScheduler'.format(name, cls.__name__)) LR_SCHEDULER_REGISTRY[name] = cls return cls return register_lr_scheduler_cls # automatically import any Python files in the optim/lr_scheduler/ directory for file in os.listdir(os.path.dirname(__file__)): if file.endswith('.py') and not file.startswith('_'): module = file[:file.find('.py')] importlib.import_module('fairseq.optim.lr_scheduler.' + module)
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/optim/lr_scheduler/cosine_lr_scheduler.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import math from . import FairseqLRScheduler, register_lr_scheduler @register_lr_scheduler('cosine') class CosineSchedule(FairseqLRScheduler): """Assign LR based on a cyclical schedule that follows the cosine function. See https://arxiv.org/pdf/1608.03983.pdf for details We also support a warmup phase where we linearly increase the learning rate from some initial learning rate (`--warmup-init-lr`) until the configured learning rate (`--lr`). During warmup: lrs = torch.linspace(args.warmup_init_lr, args.lr, args.warmup_updates) lr = lrs[update_num] After warmup: lr = lr_min + 0.5*(lr_max - lr_min)*(1 + cos(t_curr / t_i)) where t_curr is current percentage of updates within the current period range t_i is the current period range, which is scaled by t_mul after every iteration """ def __init__(self, args, optimizer): super().__init__(args, optimizer) if len(args.lr) > 1: raise ValueError( 'Cannot use a fixed learning rate schedule with cosine.' ' Consider --lr-scheduler=fixed instead.' ) warmup_end_lr = args.max_lr if args.warmup_init_lr < 0: args.warmup_init_lr = args.lr[0] self.min_lr = args.lr[0] self.max_lr = args.max_lr assert self.max_lr > self.min_lr, 'max_lr must be more than lr' self.t_mult = args.t_mult self.period = args.lr_period_updates if args.warmup_updates > 0: # linearly warmup for the first args.warmup_updates self.lr_step = (warmup_end_lr - args.warmup_init_lr) / args.warmup_updates else: self.lr_step = 1 self.warmup_updates = args.warmup_updates self.lr_shrink = args.lr_shrink # initial learning rate self.lr = args.warmup_init_lr self.optimizer.set_lr(self.lr) @staticmethod def add_args(parser): """Add arguments to the parser for this LR scheduler.""" parser.add_argument('--warmup-updates', default=0, type=int, metavar='N', help='warmup the learning rate linearly for the first N updates') parser.add_argument('--warmup-init-lr', default=-1, type=float, metavar='LR', help='initial learning rate during warmup phase; default is args.lr') parser.add_argument('--max-lr', required=True, type=float, metavar='LR', help='max learning rate, must be more than args.lr') parser.add_argument('--t-mult', default=1, type=float, metavar='LR', help='factor to grow the length of each period') parser.add_argument('--lr-period-updates', default=5000, type=float, metavar='LR', help='initial number of updates per period') def step(self, epoch, val_loss=None): """Update the learning rate at the end of the given epoch.""" super().step(epoch, val_loss) # we don't change the learning rate at epoch boundaries return self.optimizer.get_lr() def step_update(self, num_updates): """Update the learning rate after each update.""" if num_updates < self.args.warmup_updates: self.lr = self.args.warmup_init_lr + num_updates * self.lr_step else: curr_updates = num_updates - self.args.warmup_updates if self.t_mult != 1: i = math.floor(math.log(1 - curr_updates / self.period * (1 - self.t_mult), self.t_mult)) t_i = self.t_mult ** i * self.period t_curr = curr_updates - (1 - self.t_mult ** i) / (1 - self.t_mult) * self.period else: i = math.floor(curr_updates / self.period) t_i = self.period t_curr = curr_updates - (self.period * i) lr_shrink = self.lr_shrink ** i min_lr = self.min_lr * lr_shrink max_lr = self.max_lr * lr_shrink self.lr = min_lr + 0.5 * (max_lr - min_lr) * (1 + math.cos(math.pi * t_curr / t_i)) self.optimizer.set_lr(self.lr) return self.lr
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/optim/lr_scheduler/exp_lr_scheduler.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. from . import FairseqLRScheduler, register_lr_scheduler @register_lr_scheduler('exp') class ExpSchedule(FairseqLRScheduler): def __init__(self, args, optimizer): super().__init__(args, optimizer) if len(args.lr) > 1: raise ValueError( 'Cannot use a fixed learning rate schedule with exp.' ' Consider --lr-scheduler=fixed instead.' ) self.init_lr = args.init_lr self.gamma = args.decay_rate_step self.lr = self.init_lr self.optimizer.set_lr(self.lr) @staticmethod def add_args(parser): parser.add_argument('--init-lr', default=0.0, type=float, metavar='LR', help="initial learning rate") parser.add_argument('--decay-rate-step', default=1.0, type=float, metavar='GAMMA', help="exponent to multiply after each step") def step(self, epoch, val_loss=None): """Update the learning rate at the end of the given epoch.""" super().step(epoch, val_loss) # we don't change the learning rate at epoch boundaries return self.optimizer.get_lr() def step_update(self, num_updates): """Update the learning rate after each update.""" self.lr = self.init_lr * (self.gamma ** num_updates) self.optimizer.set_lr(self.lr) return self.lr
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/optim/lr_scheduler/fairseq_lr_scheduler.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. from .. import FairseqOptimizer class FairseqLRScheduler(object): def __init__(self, args, optimizer): super().__init__() if not isinstance(optimizer, FairseqOptimizer): raise ValueError('optimizer must be an instance of FairseqOptimizer') self.args = args self.optimizer = optimizer self.best = None @staticmethod def add_args(parser): """Add arguments to the parser for this LR scheduler.""" pass def state_dict(self): """Return the LR scheduler state dict.""" return {'best': self.best} def load_state_dict(self, state_dict): """Load an LR scheduler state dict.""" self.best = state_dict['best'] def step(self, epoch, val_loss=None): """Update the learning rate at the end of the given epoch.""" if val_loss is not None: if self.best is None: self.best = val_loss else: self.best = min(self.best, val_loss) def step_update(self, num_updates): """Update the learning rate after each update.""" return self.optimizer.get_lr()
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/optim/lr_scheduler/fixed_schedule.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. from . import FairseqLRScheduler, register_lr_scheduler @register_lr_scheduler('fixed') class FixedSchedule(FairseqLRScheduler): """Decay the LR on a fixed schedule.""" def __init__(self, args, optimizer): super().__init__(args, optimizer) # set defaults args.warmup_updates = getattr(args, 'warmup_updates', 0) or 0 self.lr = args.lr[0] if args.warmup_updates > 0: self.warmup_factor = 1. / args.warmup_updates else: self.warmup_factor = 1 @staticmethod def add_args(parser): """Add arguments to the parser for this LR scheduler.""" parser.add_argument('--force-anneal', '--fa', type=int, metavar='N', help='force annealing at specified epoch') parser.add_argument('--warmup-updates', default=0, type=int, metavar='N', help='warmup the learning rate linearly for the first N updates') def get_next_lr(self, epoch): lrs = self.args.lr if self.args.force_anneal is None or epoch < self.args.force_anneal: # use fixed LR schedule next_lr = lrs[min(epoch, len(lrs) - 1)] else: # annneal based on lr_shrink next_lr = lrs[-1] * self.args.lr_shrink ** (epoch + 1 - self.args.force_anneal) return next_lr def step(self, epoch, val_loss=None): """Update the learning rate at the end of the given epoch.""" super().step(epoch, val_loss) self.lr = self.get_next_lr(epoch) self.optimizer.set_lr(self.warmup_factor * self.lr) return self.optimizer.get_lr() def step_update(self, num_updates): """Update the learning rate after each update.""" if self.args.warmup_updates > 0 and num_updates <= self.args.warmup_updates: self.warmup_factor = num_updates / float(self.args.warmup_updates) self.optimizer.set_lr(self.warmup_factor * self.lr) return self.optimizer.get_lr()
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/optim/lr_scheduler/inverse_square_root_schedule.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. from . import FairseqLRScheduler, register_lr_scheduler @register_lr_scheduler('inverse_sqrt') class InverseSquareRootSchedule(FairseqLRScheduler): """Decay the LR based on the inverse square root of the update number. We also support a warmup phase where we linearly increase the learning rate from some initial learning rate (`--warmup-init-lr`) until the configured learning rate (`--lr`). Thereafter we decay proportional to the number of updates, with a decay factor set to align with the configured learning rate. During warmup: lrs = torch.linspace(args.warmup_init_lr, args.lr, args.warmup_updates) lr = lrs[update_num] After warmup: lr = decay_factor / sqrt(update_num) where decay_factor = args.lr * sqrt(args.warmup_updates) """ def __init__(self, args, optimizer): super().__init__(args, optimizer) if len(args.lr) > 1: raise ValueError( 'Cannot use a fixed learning rate schedule with inverse_sqrt.' ' Consider --lr-scheduler=fixed instead.' ) warmup_end_lr = args.lr[0] if args.warmup_init_lr < 0: args.warmup_init_lr = warmup_end_lr # linearly warmup for the first args.warmup_updates self.lr_step = (warmup_end_lr - args.warmup_init_lr) / args.warmup_updates # then, decay prop. to the inverse square root of the update number self.decay_factor = warmup_end_lr * args.warmup_updates**0.5 # initial learning rate self.lr = args.warmup_init_lr self.optimizer.set_lr(self.lr) @staticmethod def add_args(parser): """Add arguments to the parser for this LR scheduler.""" parser.add_argument('--warmup-updates', default=4000, type=int, metavar='N', help='warmup the learning rate linearly for the first N updates') parser.add_argument('--warmup-init-lr', default=-1, type=float, metavar='LR', help='initial learning rate during warmup phase; default is args.lr') def step(self, epoch, val_loss=None): """Update the learning rate at the end of the given epoch.""" super().step(epoch, val_loss) # we don't change the learning rate at epoch boundaries return self.optimizer.get_lr() def step_update(self, num_updates): """Update the learning rate after each update.""" if num_updates < self.args.warmup_updates: self.lr = self.args.warmup_init_lr + num_updates*self.lr_step else: self.lr = self.decay_factor * num_updates**-0.5 self.optimizer.set_lr(self.lr) return self.lr
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/optim/lr_scheduler/linear_lr_schedule.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. from . import FairseqLRScheduler, register_lr_scheduler @register_lr_scheduler('linear') class LinearSchedule(FairseqLRScheduler): def __init__(self, args, optimizer): super().__init__(args, optimizer) if len(args.lr) > 1: raise ValueError( 'Cannot use a fixed learning rate schedule with inverse_sqrt.' ' Consider --lr-scheduler=fixed instead.' ) max_lr = args.lr[0] if args.warmup_init_lr < 0: args.warmup_init_lr = max_lr self.max_update = args.max_update self.lr_step_warmup = (max_lr - args.warmup_init_lr) / args.warmup_updates self.lr_step_decay = - (max_lr - args.end_lr) / (args.max_update - args.warmup_updates) self.end_lr = args.end_lr # initial learning rate self.lr = args.warmup_init_lr self.optimizer.set_lr(self.lr) @staticmethod def add_args(parser): """Add arguments to the parser for this LR scheduler.""" parser.add_argument('--warmup-updates', default=4000, type=int, metavar='N', help='warmup the learning rate linearly for the first N updates') parser.add_argument('--warmup-init-lr', default=-1, type=float, metavar='LR', help='initial learning rate during warmup phase; default is args.lr') parser.add_argument('--end-lr', default=0.0, type=float, metavar='LR', help='final learning rate; default is 0') def step(self, epoch, val_loss=None): """Update the learning rate at the end of the given epoch.""" super().step(epoch, val_loss) # we don't change the learning rate at epoch boundaries return self.optimizer.get_lr() def step_update(self, num_updates): """Update the learning rate after each update.""" if num_updates < self.args.warmup_updates: self.lr = self.args.warmup_init_lr + num_updates * self.lr_step_warmup else: self.lr = (num_updates - self.max_update) * self.lr_step_decay + self.end_lr self.optimizer.set_lr(self.lr) return self.lr
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/optim/lr_scheduler/reduce_lr_on_plateau.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import torch.optim.lr_scheduler from . import FairseqLRScheduler, register_lr_scheduler @register_lr_scheduler('reduce_lr_on_plateau') class ReduceLROnPlateau(FairseqLRScheduler): """Decay the LR by a factor every time the validation loss plateaus.""" def __init__(self, args, optimizer): super().__init__(args, optimizer) if len(args.lr) > 1: raise ValueError( 'Cannot use a fixed learning rate schedule with reduce_lr_on_plateau.' ' Consider --lr-scheduler=fixed instead.' ) self.lr_scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau( self.optimizer.optimizer, patience=0, factor=args.lr_shrink) def state_dict(self): """Return the LR scheduler state dict.""" return { 'best': self.lr_scheduler.best, 'last_epoch': self.lr_scheduler.last_epoch, } def load_state_dict(self, state_dict): """Load an LR scheduler state dict.""" self.lr_scheduler.best = state_dict['best'] if 'last_epoch' in state_dict: self.lr_scheduler.last_epoch = state_dict['last_epoch'] def step(self, epoch, val_loss=None): """Update the learning rate at the end of the given epoch.""" if val_loss is not None: self.lr_scheduler.step(val_loss, epoch) else: self.lr_scheduler.last_epoch = epoch return self.optimizer.get_lr()
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/optim/lr_scheduler/triangular_lr_scheduler.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import math from . import FairseqLRScheduler, register_lr_scheduler @register_lr_scheduler('triangular') class TriangularSchedule(FairseqLRScheduler): """Assign LR based on a triangular cyclical schedule. See https://arxiv.org/pdf/1506.01186.pdf for details """ def __init__(self, args, optimizer): super().__init__(args, optimizer) if len(args.lr) > 1: raise ValueError( 'Cannot use a fixed learning rate schedule with triangular.' ' Consider --lr-scheduler=fixed instead.' ) lr = args.lr[0] assert args.max_lr > lr, 'max_lr must be more than lr' self.min_lr = lr self.max_lr = args.max_lr self.stepsize = args.lr_period_updates // 2 self.lr_shrink = args.lr_shrink self.shrink_min = args.shrink_min # initial learning rate self.lr = self.min_lr self.optimizer.set_lr(self.lr) @staticmethod def add_args(parser): """Add arguments to the parser for this LR scheduler.""" parser.add_argument('--max-lr', required=True, type=float, metavar='LR', help='max learning rate, must be more than args.lr') parser.add_argument('--lr-period-updates', default=5000, type=float, metavar='LR', help='initial number of updates per period (cycle length)') parser.add_argument('--shrink-min', action='store_true', help='if set, also shrinks min lr') def step(self, epoch, val_loss=None): """Update the learning rate at the end of the given epoch.""" super().step(epoch, val_loss) # we don't change the learning rate at epoch boundaries return self.optimizer.get_lr() def step_update(self, num_updates): """Update the learning rate after each update.""" cycle = math.floor(num_updates / (2 * self.stepsize)) lr_shrink = self.lr_shrink ** cycle max_lr = self.max_lr * lr_shrink if self.shrink_min: min_lr = self.min_lr * lr_shrink else: min_lr = self.min_lr x = abs(num_updates / self.stepsize - 2 * (cycle + 1) + 1) self.lr = min_lr + (max_lr - min_lr) * max(0, (1 - x)) self.optimizer.set_lr(self.lr) return self.lr
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/optim/nag.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. from torch.optim.optimizer import Optimizer, required from . import FairseqOptimizer, register_optimizer @register_optimizer('nag') class FairseqNAG(FairseqOptimizer): def __init__(self, args, params): super().__init__(args, params) self._optimizer = NAG(params, **self.optimizer_config) @property def optimizer_config(self): """ Return a kwarg dictionary that will be used to override optimizer args stored in checkpoints. This allows us to load a checkpoint and resume training using a different set of optimizer args, e.g., with a different learning rate. """ return { 'lr': self.args.lr[0], 'momentum': self.args.momentum, 'weight_decay': self.args.weight_decay, } class NAG(Optimizer): def __init__(self, params, lr=required, momentum=0, weight_decay=0): defaults = dict(lr=lr, lr_old=lr, momentum=momentum, weight_decay=weight_decay) super(NAG, self).__init__(params, defaults) def step(self, closure=None): """Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() for group in self.param_groups: weight_decay = group['weight_decay'] momentum = group['momentum'] lr = group['lr'] lr_old = group.get('lr_old', lr) lr_correct = lr / lr_old for p in group['params']: if p.grad is None: continue d_p = p.grad.data param_state = self.state[p] if 'momentum_buffer' not in param_state: param_state['momentum_buffer'] = d_p.clone().zero_() buf = param_state['momentum_buffer'] if weight_decay != 0: p.data.mul_(1 - lr * weight_decay) p.data.add_(momentum * momentum * lr_correct, buf) p.data.add_(-(1 + momentum) * lr, d_p) buf.mul_(momentum * lr_correct).add_(-lr, d_p) group['lr_old'] = lr return loss
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/optim/sgd.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import torch.optim from . import FairseqOptimizer, register_optimizer @register_optimizer('sgd') class SGD(FairseqOptimizer): def __init__(self, args, params): super().__init__(args, params) self._optimizer = torch.optim.SGD(params, **self.optimizer_config) @property def optimizer_config(self): """ Return a kwarg dictionary that will be used to override optimizer args stored in checkpoints. This allows us to load a checkpoint and resume training using a different set of optimizer args, e.g., with a different learning rate. """ return { 'lr': self.args.lr[0], 'momentum': self.args.momentum, 'weight_decay': self.args.weight_decay, }
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/options.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import argparse import torch from fairseq.criterions import CRITERION_REGISTRY from fairseq.models import ARCH_MODEL_REGISTRY, ARCH_CONFIG_REGISTRY from fairseq.optim import OPTIMIZER_REGISTRY from fairseq.optim.lr_scheduler import LR_SCHEDULER_REGISTRY from fairseq.tasks import TASK_REGISTRY def get_training_parser(default_task='translation'): parser = get_parser('Trainer', default_task) add_dataset_args(parser, train=True) add_distributed_training_args(parser) add_model_args(parser) add_optimization_args(parser) add_checkpoint_args(parser) return parser def get_generation_parser(interactive=False, default_task='translation'): parser = get_parser('Generation', default_task) add_dataset_args(parser, gen=True) add_generation_args(parser) if interactive: add_interactive_args(parser) return parser def get_interactive_generation_parser(default_task='translation'): return get_generation_parser(interactive=True, default_task=default_task) def get_eval_lm_parser(default_task='language_modeling'): parser = get_parser('Evaluate Language Model', default_task) add_dataset_args(parser, gen=True) add_eval_lm_args(parser) return parser def get_inference_parser(default_task='glue'): parser = get_parser('Inference', default_task) add_dataset_args(parser, gen=True) add_inference_args(parser) return parser def eval_str_list(x, type=float): if x is None: return None if isinstance(x, str): x = eval(x) try: return list(map(type, x)) except TypeError: return [type(x)] def eval_bool(x, default=False): if x is None: return default try: return bool(eval(x)) except TypeError: return default def parse_args_and_arch(parser, input_args=None, parse_known=False): # The parser doesn't know about model/criterion/optimizer-specific args, so # we parse twice. First we parse the model/criterion/optimizer, then we # parse a second time after adding the *-specific arguments. # If input_args is given, we will parse those args instead of sys.argv. args, _ = parser.parse_known_args(input_args) # Add model-specific args to parser. if hasattr(args, 'arch'): model_specific_group = parser.add_argument_group( 'Model-specific configuration', # Only include attributes which are explicitly given as command-line # arguments or which have default values. argument_default=argparse.SUPPRESS, ) ARCH_MODEL_REGISTRY[args.arch].add_args(model_specific_group) # Add *-specific args to parser. if hasattr(args, 'criterion'): CRITERION_REGISTRY[args.criterion].add_args(parser) if hasattr(args, 'optimizer'): OPTIMIZER_REGISTRY[args.optimizer].add_args(parser) if hasattr(args, 'lr_scheduler'): LR_SCHEDULER_REGISTRY[args.lr_scheduler].add_args(parser) if hasattr(args, 'task'): TASK_REGISTRY[args.task].add_args(parser) # Parse a second time. if parse_known: args, extra = parser.parse_known_args(input_args) else: args = parser.parse_args(input_args) extra = None # Post-process args. if hasattr(args, 'lr'): args.lr = eval_str_list(args.lr, type=float) if hasattr(args, 'update_freq'): args.update_freq = eval_str_list(args.update_freq, type=int) if hasattr(args, 'max_sentences_valid') and args.max_sentences_valid is None: args.max_sentences_valid = args.max_sentences # Apply architecture configuration. if hasattr(args, 'arch'): ARCH_CONFIG_REGISTRY[args.arch](args) if parse_known: return args, extra else: return args def get_parser(desc, default_task='translation'): parser = argparse.ArgumentParser() parser.add_argument('--no-progress-bar', action='store_true', help='disable progress bar') parser.add_argument('--log-interval', type=int, default=1000, metavar='N', help='log progress every N batches (when progress bar is disabled)') parser.add_argument('--log-format', default=None, help='log format to use', choices=['json', 'none', 'simple', 'tqdm']) parser.add_argument('--seed', default=1, type=int, metavar='N', help='pseudo random number generator seed') parser.add_argument('--fp16', action='store_true', help='use FP16') parser.add_argument('--fp16-init-scale', default=2**7, type=int, help='default FP16 loss scale') # Task definitions can be found under fairseq/tasks/ parser.add_argument( '--task', metavar='TASK', default=default_task, choices=TASK_REGISTRY.keys(), help='task', ) return parser def add_dataset_args(parser, train=False, gen=False): group = parser.add_argument_group('Dataset and data loading') group.add_argument('--skip-invalid-size-inputs-valid-test', action='store_true', help='ignore too long or too short lines in valid and test set') group.add_argument('--max-tokens', type=int, metavar='N', help='maximum number of tokens in a batch') group.add_argument('--max-sentences', '--batch-size', type=int, metavar='N', help='maximum number of sentences in a batch') if train: group.add_argument('--train-subset', default='train', metavar='SPLIT', choices=['train', 'valid', 'test'], help='data subset to use for training (train, valid, test)') group.add_argument('--valid-subset', default='valid', metavar='SPLIT', help='comma separated list of data subsets to use for validation' ' (train, valid, valid1, test, test1)') group.add_argument('--max-sentences-valid', type=int, metavar='N', help='maximum number of sentences in a validation batch' ' (defaults to --max-sentences)') if gen: group.add_argument('--gen-subset', default='test', metavar='SPLIT', help='data subset to generate (train, valid, test)') group.add_argument('--num-shards', default=1, type=int, metavar='N', help='shard generation over N shards') group.add_argument('--shard-id', default=0, type=int, metavar='ID', help='id of the shard to generate (id < num_shards)') return group def add_distributed_training_args(parser): group = parser.add_argument_group('Distributed training') group.add_argument('--distributed-world-size', type=int, metavar='N', default=torch.cuda.device_count(), help='total number of GPUs across all nodes (default: all visible GPUs)') group.add_argument('--distributed-rank', default=0, type=int, help='rank of the current worker') group.add_argument('--distributed-backend', default='nccl', type=str, help='distributed backend') group.add_argument('--distributed-init-method', default=None, type=str, help='typically tcp://hostname:port that will be used to ' 'establish initial connetion') group.add_argument('--distributed-port', default=-1, type=int, help='port number (not required if using --distributed-init-method)') group.add_argument('--device-id', default=0, type=int, help='which GPU to use (usually configured automatically)') group.add_argument('--ddp-backend', default='c10d', type=str, choices=['c10d', 'no_c10d'], help='DistributedDataParallel backend') group.add_argument('--bucket-cap-mb', default=150, type=int, metavar='MB', help='bucket size for reduction') return group def add_optimization_args(parser): group = parser.add_argument_group('Optimization') group.add_argument('--max-epoch', '--me', default=0, type=int, metavar='N', help='force stop training at specified epoch') group.add_argument('--max-update', '--mu', default=0, type=int, metavar='N', help='force stop training at specified update') group.add_argument('--clip-norm', default=25, type=float, metavar='NORM', help='clip threshold of gradients') group.add_argument('--sentence-avg', action='store_true', help='normalize gradients by the number of sentences in a batch' ' (default is to normalize by number of tokens)') group.add_argument('--update-freq', default='1', metavar='N', help='update parameters every N_i batches, when in epoch i') # Optimizer definitions can be found under fairseq/optim/ group.add_argument('--optimizer', default='nag', metavar='OPT', choices=OPTIMIZER_REGISTRY.keys(), help='Optimizer') group.add_argument('--lr', '--learning-rate', default='0.25', metavar='LR_1,LR_2,...,LR_N', help='learning rate for the first N epochs; all epochs >N using LR_N' ' (note: this may be interpreted differently depending on --lr-scheduler)') group.add_argument('--momentum', default=0.99, type=float, metavar='M', help='momentum factor') group.add_argument('--weight-decay', '--wd', default=0.0, type=float, metavar='WD', help='weight decay') # Learning rate schedulers can be found under fairseq/optim/lr_scheduler/ group.add_argument('--lr-scheduler', default='reduce_lr_on_plateau', choices=LR_SCHEDULER_REGISTRY.keys(), help='Learning Rate Scheduler') group.add_argument('--lr-shrink', default=0.1, type=float, metavar='LS', help='learning rate shrink factor for annealing, lr_new = (lr * lr_shrink)') group.add_argument('--min-lr', default=1e-5, type=float, metavar='LR', help='minimum learning rate') group.add_argument('--min-loss-scale', default=1e-4, type=float, metavar='D', help='minimum loss scale (for FP16 training)') return group def add_checkpoint_args(parser): group = parser.add_argument_group('Checkpointing') group.add_argument('--save-dir', metavar='DIR', default='checkpoints', help='path to save checkpoints') group.add_argument('--restore-file', default='checkpoint_last.pt', help='filename in save-dir from which to load checkpoint') group.add_argument('--reset-optimizer', action='store_true', help='if set, does not load optimizer state from the checkpoint') group.add_argument('--reset-lr-scheduler', action='store_true', help='if set, does not load lr scheduler state from the checkpoint') group.add_argument('--optimizer-overrides', default="{}", type=str, metavar='DICT', help='a dictionary used to override optimizer args when loading a checkpoint') group.add_argument('--save-interval', type=int, default=1, metavar='N', help='save a checkpoint every N epochs') group.add_argument('--save-interval-updates', type=int, default=0, metavar='N', help='save a checkpoint (and validate) every N updates') group.add_argument('--keep-interval-updates', type=int, default=-1, metavar='N', help='keep last N checkpoints saved with --save-interval-updates') group.add_argument('--no-save', action='store_true', help='don\'t save models or checkpoints') group.add_argument('--no-epoch-checkpoints', action='store_true', help='only store last and best checkpoints') group.add_argument('--validate-interval', type=int, default=1, metavar='N', help='validate every N epochs') group.add_argument('--load-bert', metavar='PATH', type=str, help='pretrained bert encoder to load from file') group.add_argument('--load-type', metavar='TYPE', default="all", type=str, help='which part pretrained bert encoder to load ("all", "no_fc", "no_out", "no_out_no_fc")') return group def add_common_eval_args(group): group.add_argument('--path', metavar='FILE', help='path(s) to model file(s), colon separated') group.add_argument('--remove-bpe', nargs='?', const='@@ ', default=None, help='remove BPE tokens before scoring') group.add_argument('--cpu', action='store_true', help='generate on CPU') group.add_argument('--quiet', action='store_true', help='only print final scores') def add_eval_lm_args(parser): group = parser.add_argument_group('LM Evaluation') add_common_eval_args(group) group.add_argument('--output-word-probs', action='store_true', help='if set, outputs words and their predicted log probabilities to standard output') group.add_argument('--output-word-stats', action='store_true', help='if set, outputs word statistics such as word count, average probability, etc') def add_generation_args(parser): group = parser.add_argument_group('Generation') add_common_eval_args(group) group.add_argument('--beam', default=5, type=int, metavar='N', help='beam size') group.add_argument('--nbest', default=1, type=int, metavar='N', help='number of hypotheses to output') group.add_argument('--max-len-a', default=0, type=float, metavar='N', help=('generate sequences of maximum length ax + b, ' 'where x is the source length')) group.add_argument('--max-len-b', default=200, type=int, metavar='N', help=('generate sequences of maximum length ax + b, ' 'where x is the source length')) group.add_argument('--min-len', default=1, type=float, metavar='N', help=('minimum generation length')) group.add_argument('--no-early-stop', action='store_true', help=('continue searching even after finalizing k=beam ' 'hypotheses; this is more correct, but increases ' 'generation time by 50%%')) group.add_argument('--unnormalized', action='store_true', help='compare unnormalized hypothesis scores') group.add_argument('--no-beamable-mm', action='store_true', help='don\'t use BeamableMM in attention layers') group.add_argument('--lenpen', default=1, type=float, help='length penalty: <1.0 favors shorter, >1.0 favors longer sentences') group.add_argument('--unkpen', default=0, type=float, help='unknown word penalty: <0 produces more unks, >0 produces fewer') group.add_argument('--replace-unk', nargs='?', const=True, default=None, help='perform unknown replacement (optionally with alignment dictionary)') group.add_argument('--score-reference', action='store_true', help='just score the reference translation') group.add_argument('--prefix-size', default=0, type=int, metavar='PS', help='initialize generation by target prefix of given length') group.add_argument('--sampling', action='store_true', help='sample hypotheses instead of using beam search') group.add_argument('--sampling-topk', default=-1, type=int, metavar='PS', help='sample from top K likely next words instead of all words') group.add_argument('--sampling-temperature', default=1, type=float, metavar='N', help='temperature for random sampling') group.add_argument('--diverse-beam-groups', default=1, type=int, metavar='N', help='number of groups for Diverse Beam Search') group.add_argument('--diverse-beam-strength', default=0.5, type=float, metavar='N', help='strength of diversity penalty for Diverse Beam Search') group.add_argument('--print-alignment', action='store_true', help='if set, uses attention feedback to compute and print alignment to source tokens') group.add_argument('--model-overrides', default="{}", type=str, metavar='DICT', help='a dictionary used to override model args at generation that were used during model training') return group def add_interactive_args(parser): group = parser.add_argument_group('Interactive') group.add_argument('--buffer-size', default=0, type=int, metavar='N', help='read this many sentences into a buffer before processing them') def add_inference_args(parser): group = parser.add_argument_group('Inference') add_common_eval_args(group) group.add_argument('--output', type=str, metavar='PATH', help='path of inference output') return group def add_model_args(parser): group = parser.add_argument_group('Model configuration') # Model definitions can be found under fairseq/models/ # # The model architecture can be specified in several ways. # In increasing order of priority: # 1) model defaults (lowest priority) # 2) --arch argument # 3) --encoder/decoder-* arguments (highest priority) group.add_argument( '--arch', '-a', default='fconv', metavar='ARCH', required=True, choices=ARCH_MODEL_REGISTRY.keys(), help='Model Architecture', ) # Criterion definitions can be found under fairseq/criterions/ group.add_argument( '--criterion', default='cross_entropy', metavar='CRIT', choices=CRITERION_REGISTRY.keys(), help='Training Criterion', ) return group
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/progress_bar.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. """ Wrapper around various loggers and progress bars (e.g., tqdm). """ from collections import OrderedDict import json from numbers import Number import sys import os from tqdm import tqdm from fairseq.meters import AverageMeter def build_progress_bar(args, iterator, epoch=None, prefix=None, default='tqdm', no_progress_bar='none'): if args.log_format is None: args.log_format = no_progress_bar if args.no_progress_bar else default if args.log_format == 'tqdm' and not sys.stderr.isatty(): args.log_format = 'simple' if args.log_format == 'json': bar = json_progress_bar(iterator, epoch, prefix, args.log_interval) elif args.log_format == 'none': bar = noop_progress_bar(iterator, epoch, prefix) elif args.log_format == 'simple': bar = simple_progress_bar(iterator, epoch, prefix, args.log_interval, args.save_dir) elif args.log_format == 'tqdm': bar = tqdm_progress_bar(iterator, epoch, prefix) else: raise ValueError('Unknown log format: {}'.format(args.log_format)) return bar class progress_bar(object): """Abstract class for progress bars.""" def __init__(self, iterable, epoch=None, prefix=None): self.iterable = iterable self.epoch = epoch self.prefix = '' if epoch is not None: self.prefix += '| epoch {:03d}'.format(epoch) if prefix is not None: self.prefix += ' | {}'.format(prefix) def __enter__(self): return self def __exit__(self, *exc): return False def __iter__(self): raise NotImplementedError def log(self, stats): """Log intermediate stats according to log_interval.""" raise NotImplementedError def print(self, stats): """Print end-of-epoch stats.""" raise NotImplementedError def _str_commas(self, stats): return ', '.join(key + '=' + stats[key].strip() for key in stats.keys()) def _str_pipes(self, stats): return ' | '.join(key + ' ' + stats[key].strip() for key in stats.keys()) def _format_stats(self, stats): postfix = OrderedDict(stats) # Preprocess stats according to datatype for key in postfix.keys(): # Number: limit the length of the string if isinstance(postfix[key], Number): postfix[key] = '{:g}'.format(postfix[key]) # Meter: display both current and average value elif isinstance(postfix[key], AverageMeter): postfix[key] = '{:.2f} ({:.2f})'.format( postfix[key].val, postfix[key].avg) # Else for any other type, try to get the string conversion elif not isinstance(postfix[key], str): postfix[key] = str(postfix[key]) # Else if it's a string, don't need to preprocess anything return postfix class json_progress_bar(progress_bar): """Log output in JSON format.""" def __init__(self, iterable, epoch=None, prefix=None, log_interval=1000): super().__init__(iterable, epoch, prefix) self.log_interval = log_interval self.stats = None def __iter__(self): size = float(len(self.iterable)) for i, obj in enumerate(self.iterable): yield obj if self.stats is not None and i > 0 and \ self.log_interval is not None and i % self.log_interval == 0: update = self.epoch - 1 + float(i / size) if self.epoch is not None else None stats = self._format_stats(self.stats, epoch=self.epoch, update=update) print(json.dumps(stats), flush=True) def log(self, stats): """Log intermediate stats according to log_interval.""" self.stats = stats def print(self, stats): """Print end-of-epoch stats.""" self.stats = stats stats = self._format_stats(self.stats, epoch=self.epoch) print(json.dumps(stats), flush=True) def _format_stats(self, stats, epoch=None, update=None): postfix = OrderedDict() if epoch is not None: postfix['epoch'] = epoch if update is not None: postfix['update'] = update # Preprocess stats according to datatype for key in stats.keys(): # Meter: display both current and average value if isinstance(stats[key], AverageMeter): postfix[key] = stats[key].val postfix[key + '_avg'] = stats[key].avg else: postfix[key] = stats[key] return postfix class noop_progress_bar(progress_bar): """No logging.""" def __init__(self, iterable, epoch=None, prefix=None): super().__init__(iterable, epoch, prefix) def __iter__(self): for obj in self.iterable: yield obj def log(self, stats): """Log intermediate stats according to log_interval.""" pass def print(self, stats): """Print end-of-epoch stats.""" pass class simple_progress_bar(progress_bar): """A minimal logger for non-TTY environments.""" def __init__(self, iterable, epoch=None, prefix=None, log_interval=1000, save_dir=os.path.curdir): super().__init__(iterable, epoch, prefix) self.log_interval = log_interval self.stats = None self.log_file = open(os.path.join(save_dir, "log.txt"), "a", encoding="utf-8") def __iter__(self): size = len(self.iterable) for i, obj in enumerate(self.iterable): yield obj if self.stats is not None and i > 0 and \ self.log_interval is not None and i % self.log_interval == 0: postfix = self._str_commas(self.stats) print('{}: {:5d} / {:d} {}'.format(self.prefix, i, size, postfix), flush=True) def log(self, stats): """Log intermediate stats according to log_interval.""" self.stats = self._format_stats(stats) def print(self, stats): """Print end-of-epoch stats.""" postfix = self._str_pipes(self._format_stats(stats)) print('{} | {}'.format(self.prefix, postfix), flush=True) self.log_file.write(f"{self.prefix} | {postfix}\n") self.log_file.flush() class tqdm_progress_bar(progress_bar): """Log to tqdm.""" def __init__(self, iterable, epoch=None, prefix=None): super().__init__(iterable, epoch, prefix) self.tqdm = tqdm(iterable, self.prefix, leave=False) def __iter__(self): return iter(self.tqdm) def log(self, stats): """Log intermediate stats according to log_interval.""" self.tqdm.set_postfix(self._format_stats(stats), refresh=False) def print(self, stats): """Print end-of-epoch stats.""" postfix = self._str_pipes(self._format_stats(stats)) self.tqdm.write('{} | {}'.format(self.tqdm.desc, postfix))
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/search.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import torch class Search(object): def __init__(self, tgt_dict): self.pad = tgt_dict.pad() self.unk = tgt_dict.unk() self.eos = tgt_dict.eos() self.vocab_size = len(tgt_dict) self.scores_buf = None self.indices_buf = None self.beams_buf = None def _init_buffers(self, t): if self.scores_buf is None: self.scores_buf = t.new() self.indices_buf = torch.LongTensor().to(device=t.device) self.beams_buf = torch.LongTensor().to(device=t.device) def step(self, step, lprobs, scores, beam_size): """Take a single search step. Args: step: the current search step, starting at 0 lprobs: (bsz x input_beam_size x vocab_size) the model's log-probabilities over the vocabulary at the current step scores: (bsz x input_beam_size x step) the historical model scores of each hypothesis up to this point Return: A tuple of (scores, indices, beams) where: scores: (bsz x output_beam_size) the scores of the chosen elements; output_beam_size can be larger than input_beam_size, e.g., we may return 2*input_beam_size to account for EOS indices: (bsz x output_beam_size) the indices of the chosen elements beams: (bsz x output_beam_size) the hypothesis ids of the chosen elements, in the range [0, input_beam_size) """ raise NotImplementedError class BeamSearch(Search): def __init__(self, tgt_dict): super().__init__(tgt_dict) def step(self, step, lprobs, scores): super()._init_buffers(lprobs) bsz, beam_size, vocab_size = lprobs.size() if step == 0: # at the first step all hypotheses are equally likely, so use # only the first beam lprobs = lprobs[:, ::beam_size, :].contiguous() else: # make probs contain cumulative scores for each hypothesis lprobs.add_(scores[:, :, step - 1].unsqueeze(-1)) torch.topk( lprobs.view(bsz, -1), k=min( # Take the best 2 x beam_size predictions. We'll choose the first # beam_size of these which don't predict eos to continue with. beam_size * 2, lprobs.view(bsz, -1).size(1) - 1, # -1 so we never select pad ), out=(self.scores_buf, self.indices_buf), ) torch.div(self.indices_buf, vocab_size, out=self.beams_buf) self.indices_buf.fmod_(vocab_size) return self.scores_buf, self.indices_buf, self.beams_buf class DiverseBeamSearch(Search): """Diverse Beam Search. See "Diverse Beam Search: Decoding Diverse Solutions from Neural Sequence Models" for details. We only implement the Hamming Diversity penalty here, which performed best in the original paper. """ def __init__(self, tgt_dict, num_groups, diversity_strength): super().__init__(tgt_dict) self.num_groups = num_groups self.diversity_strength = -diversity_strength self.diversity_buf = None self.beam = BeamSearch(tgt_dict) def step(self, step, lprobs, scores): super()._init_buffers(lprobs) bsz, beam_size, vocab_size = lprobs.size() if beam_size % self.num_groups != 0: raise ValueError( 'DiverseBeamSearch requires --beam to be divisible by the number of groups' ) group_size = beam_size // self.num_groups # initialize diversity penalty if self.diversity_buf is None: self.diversity_buf = lprobs.new() torch.zeros(lprobs[:, 0, :].size(), out=self.diversity_buf) scores_G, indices_G, beams_G = [], [], [] for g in range(self.num_groups): lprobs_g = lprobs[:, g::self.num_groups, :] scores_g = scores[:, g::self.num_groups, :] if step > 0 else None # apply diversity penalty if g > 0: lprobs_g = torch.add(lprobs_g, self.diversity_strength, self.diversity_buf.unsqueeze(1)) else: lprobs_g = lprobs_g.contiguous() scores_buf, indices_buf, beams_buf = self.beam.step(step, lprobs_g, scores_g) beams_buf.mul_(self.num_groups).add_(g) scores_G.append(scores_buf.clone()) indices_G.append(indices_buf.clone()) beams_G.append(beams_buf.clone()) # update diversity penalty self.diversity_buf.scatter_add_( 1, indices_buf, self.diversity_buf.new_ones(indices_buf.size()) ) # interleave results from different groups self.scores_buf = torch.stack(scores_G, dim=2, out=self.scores_buf).view(bsz, -1) self.indices_buf = torch.stack(indices_G, dim=2, out=self.indices_buf).view(bsz, -1) self.beams_buf = torch.stack(beams_G, dim=2, out=self.beams_buf).view(bsz, -1) return self.scores_buf, self.indices_buf, self.beams_buf class Sampling(Search): def __init__(self, tgt_dict, sampling_topk=-1, sampling_temperature=1.): super().__init__(tgt_dict) self.sampling_topk = sampling_topk self.sampling_temperature = sampling_temperature def step(self, step, lprobs, scores): super()._init_buffers(lprobs) bsz, beam_size, vocab_size = lprobs.size() if step == 0: # at the first step all hypotheses are equally likely, so use # only the first beam lprobs = lprobs[:, ::beam_size, :].contiguous() # we exclude the first two vocab items, one of which is pad assert self.pad == 1, 'sampling assumes the first two symbols can be ignored' lprobs_nopad = lprobs[:, :, 2:] # only sample from top-k candidates if self.sampling_topk > 0: lprobs_nopad, topk_indices = lprobs_nopad.topk(self.sampling_topk) # sampling temperature if self.sampling_temperature != 1.: lprobs_nopad = lprobs_nopad.div_(self.sampling_temperature) # sample probs_nopad = lprobs_nopad.exp_() if step == 0: self.indices_buf = torch.multinomial( probs_nopad.view(bsz, -1), beam_size, replacement=True, out=self.indices_buf, ).view(bsz, beam_size) else: self.indices_buf = torch.multinomial( probs_nopad.view(bsz * beam_size, -1), 1, replacement=True, out=self.indices_buf, ).view(bsz, beam_size) if step == 0: # expand to beam size probs_nopad = probs_nopad.expand(bsz, beam_size, -1) # gather scores torch.gather( probs_nopad, dim=2, index=self.indices_buf.unsqueeze(-1), out=self.scores_buf, ) self.scores_buf = self.scores_buf.log_().view(bsz, -1) # remap indices if using top-k sampling if self.sampling_topk > 0: self.indices_buf = torch.gather( topk_indices.expand(bsz, beam_size, -1), dim=2, index=self.indices_buf.unsqueeze(-1), ).squeeze(2) # remap indices since we excluded the first two vocab items self.indices_buf.add_(2) if step == 0: self.beams_buf = self.indices_buf.new_zeros(bsz, beam_size) else: self.beams_buf = torch.arange(0, beam_size, out=self.beams_buf).repeat(bsz, 1) # make scores cumulative self.scores_buf.add_( torch.gather( scores[:, :, step - 1], dim=1, index=self.beams_buf, ) ) return self.scores_buf, self.indices_buf, self.beams_buf
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/sequence_generator.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import math import torch from fairseq import search, utils from fairseq.models import FairseqIncrementalDecoder class SequenceGenerator(object): def __init__( self, models, tgt_dict, beam_size=1, minlen=1, maxlen=None, stop_early=True, normalize_scores=True, len_penalty=1, unk_penalty=0, retain_dropout=False, sampling=False, sampling_topk=-1, sampling_temperature=1, diverse_beam_groups=-1, diverse_beam_strength=0.5, ): """Generates translations of a given source sentence. Args: min/maxlen: The length of the generated output will be bounded by minlen and maxlen (not including the end-of-sentence marker). stop_early: Stop generation immediately after we finalize beam_size hypotheses, even though longer hypotheses might have better normalized scores. normalize_scores: Normalize scores by the length of the output. """ self.models = models self.pad = tgt_dict.pad() self.unk = tgt_dict.unk() self.eos = tgt_dict.eos() self.vocab_size = len(tgt_dict) self.beam_size = beam_size self.minlen = minlen max_decoder_len = min(m.max_decoder_positions() for m in self.models) max_decoder_len -= 1 # we define maxlen not including the EOS marker self.maxlen = max_decoder_len if maxlen is None else min(maxlen, max_decoder_len) self.stop_early = stop_early self.normalize_scores = normalize_scores self.len_penalty = len_penalty self.unk_penalty = unk_penalty self.retain_dropout = retain_dropout assert sampling_topk < 0 or sampling, '--sampling-topk requires --sampling' if sampling: self.search = search.Sampling(tgt_dict, sampling_topk, sampling_temperature) elif diverse_beam_groups > 0: self.search = search.DiverseBeamSearch(tgt_dict, diverse_beam_groups, diverse_beam_strength) else: self.search = search.BeamSearch(tgt_dict) def cuda(self): for model in self.models: model.cuda() return self def generate_batched_itr( self, data_itr, beam_size=None, maxlen_a=0.0, maxlen_b=None, cuda=False, timer=None, prefix_size=0, ): """Iterate over a batched dataset and yield individual translations. Args: maxlen_a/b: generate sequences of maximum length ax + b, where x is the source sentence length. cuda: use GPU for generation timer: StopwatchMeter for timing generations. """ if maxlen_b is None: maxlen_b = self.maxlen for sample in data_itr: s = utils.move_to_cuda(sample) if cuda else sample if 'net_input' not in s: continue input = s['net_input'] # model.forward normally channels prev_output_tokens into the decoder # separately, but SequenceGenerator directly calls model.encoder encoder_input = { k: v for k, v in input.items() if k != 'prev_output_tokens' } srclen = encoder_input['src_tokens'].size(1) if timer is not None: timer.start() with torch.no_grad(): hypos = self.generate( encoder_input, beam_size=beam_size, maxlen=int(maxlen_a*srclen + maxlen_b), prefix_tokens=s['target'][:, :prefix_size] if prefix_size > 0 else None, ) if timer is not None: timer.stop(sum(len(h[0]['tokens']) for h in hypos)) for i, id in enumerate(s['id'].data): # remove padding src = utils.strip_pad(input['src_tokens'].data[i, :], self.pad) ref = utils.strip_pad(s['target'].data[i, :], self.pad) if s['target'] is not None else None yield id, src, ref, hypos[i] def generate(self, encoder_input, beam_size=None, maxlen=None, prefix_tokens=None): """Generate a batch of translations. Args: encoder_input: dictionary containing the inputs to model.encoder.forward beam_size: int overriding the beam size. defaults to self.beam_size max_len: maximum length of the generated sequence prefix_tokens: force decoder to begin with these tokens """ with torch.no_grad(): return self._generate(encoder_input, beam_size, maxlen, prefix_tokens) def _generate(self, encoder_input, beam_size=None, maxlen=None, prefix_tokens=None): """See generate""" src_tokens = encoder_input['src_tokens'] bsz, srclen = src_tokens.size() maxlen = min(maxlen, self.maxlen) if maxlen is not None else self.maxlen # the max beam size is the dictionary size - 1, since we never select pad beam_size = beam_size if beam_size is not None else self.beam_size beam_size = min(beam_size, self.vocab_size - 1) encoder_outs = [] incremental_states = {} for model in self.models: if not self.retain_dropout: model.eval() if isinstance(model.decoder, FairseqIncrementalDecoder): incremental_states[model] = {} else: incremental_states[model] = None # compute the encoder output for each beam encoder_out = model.encoder(**encoder_input) new_order = torch.arange(bsz).view(-1, 1).repeat(1, beam_size).view(-1) new_order = new_order.to(src_tokens.device) encoder_out = model.encoder.reorder_encoder_out(encoder_out, new_order) encoder_outs.append(encoder_out) # initialize buffers scores = src_tokens.data.new(bsz * beam_size, maxlen + 1).float().fill_(0) scores_buf = scores.clone() tokens = src_tokens.data.new(bsz * beam_size, maxlen + 2).fill_(self.pad) tokens_buf = tokens.clone() tokens[:, 0] = self.eos attn, attn_buf = None, None nonpad_idxs = None # list of completed sentences finalized = [[] for i in range(bsz)] finished = [False for i in range(bsz)] worst_finalized = [{'idx': None, 'score': -math.inf} for i in range(bsz)] num_remaining_sent = bsz # number of candidate hypos per step cand_size = 2 * beam_size # 2 x beam size in case half are EOS # offset arrays for converting between different indexing schemes bbsz_offsets = (torch.arange(0, bsz) * beam_size).unsqueeze(1).type_as(tokens) cand_offsets = torch.arange(0, cand_size).type_as(tokens) # helper function for allocating buffers on the fly buffers = {} def buffer(name, type_of=tokens): # noqa if name not in buffers: buffers[name] = type_of.new() return buffers[name] def is_finished(sent, step, unfinalized_scores=None): """ Check whether we've finished generation for a given sentence, by comparing the worst score among finalized hypotheses to the best possible score among unfinalized hypotheses. """ assert len(finalized[sent]) <= beam_size if len(finalized[sent]) == beam_size: if self.stop_early or step == maxlen or unfinalized_scores is None: return True # stop if the best unfinalized score is worse than the worst # finalized one best_unfinalized_score = unfinalized_scores[sent].max() if self.normalize_scores: best_unfinalized_score /= maxlen ** self.len_penalty if worst_finalized[sent]['score'] >= best_unfinalized_score: return True return False def finalize_hypos(step, bbsz_idx, eos_scores, unfinalized_scores=None): """ Finalize the given hypotheses at this step, while keeping the total number of finalized hypotheses per sentence <= beam_size. Note: the input must be in the desired finalization order, so that hypotheses that appear earlier in the input are preferred to those that appear later. Args: step: current time step bbsz_idx: A vector of indices in the range [0, bsz*beam_size), indicating which hypotheses to finalize eos_scores: A vector of the same size as bbsz_idx containing scores for each hypothesis unfinalized_scores: A vector containing scores for all unfinalized hypotheses """ assert bbsz_idx.numel() == eos_scores.numel() # clone relevant token and attention tensors tokens_clone = tokens.index_select(0, bbsz_idx) tokens_clone = tokens_clone[:, 1:step + 2] # skip the first index, which is EOS tokens_clone[:, step] = self.eos attn_clone = attn.index_select(0, bbsz_idx)[:, :, 1:step+2] if attn is not None else None # compute scores per token position pos_scores = scores.index_select(0, bbsz_idx)[:, :step+1] pos_scores[:, step] = eos_scores # convert from cumulative to per-position scores pos_scores[:, 1:] = pos_scores[:, 1:] - pos_scores[:, :-1] # normalize sentence-level scores if self.normalize_scores: eos_scores /= (step + 1) ** self.len_penalty cum_unfin = [] prev = 0 for f in finished: if f: prev += 1 else: cum_unfin.append(prev) sents_seen = set() for i, (idx, score) in enumerate(zip(bbsz_idx.tolist(), eos_scores.tolist())): unfin_idx = idx // beam_size sent = unfin_idx + cum_unfin[unfin_idx] sents_seen.add((sent, unfin_idx)) def get_hypo(): if attn_clone is not None: # remove padding tokens from attn scores hypo_attn = attn_clone[i][nonpad_idxs[sent]] _, alignment = hypo_attn.max(dim=0) else: hypo_attn = None alignment = None return { 'tokens': tokens_clone[i], 'score': score, 'attention': hypo_attn, # src_len x tgt_len 'alignment': alignment, 'positional_scores': pos_scores[i], } if len(finalized[sent]) < beam_size: finalized[sent].append(get_hypo()) elif not self.stop_early and score > worst_finalized[sent]['score']: # replace worst hypo for this sentence with new/better one worst_idx = worst_finalized[sent]['idx'] if worst_idx is not None: finalized[sent][worst_idx] = get_hypo() # find new worst finalized hypo for this sentence idx, s = min(enumerate(finalized[sent]), key=lambda r: r[1]['score']) worst_finalized[sent] = { 'score': s['score'], 'idx': idx, } newly_finished = [] for sent, unfin_idx in sents_seen: # check termination conditions for this sentence if not finished[sent] and is_finished(sent, step, unfinalized_scores): finished[sent] = True newly_finished.append(unfin_idx) return newly_finished reorder_state = None batch_idxs = None for step in range(maxlen + 1): # one extra step for EOS marker # reorder decoder internal states based on the prev choice of beams if reorder_state is not None: if batch_idxs is not None: # update beam indices to take into account removed sentences corr = batch_idxs - torch.arange(batch_idxs.numel()).type_as(batch_idxs) reorder_state.view(-1, beam_size).add_(corr.unsqueeze(-1) * beam_size) for i, model in enumerate(self.models): if isinstance(model.decoder, FairseqIncrementalDecoder): model.decoder.reorder_incremental_state(incremental_states[model], reorder_state) encoder_outs[i] = model.encoder.reorder_encoder_out(encoder_outs[i], reorder_state) lprobs, avg_attn_scores = self._decode(tokens[:, :step + 1], encoder_outs, incremental_states) lprobs[:, self.pad] = -math.inf # never select pad lprobs[:, self.unk] -= self.unk_penalty # apply unk penalty # Record attention scores if avg_attn_scores is not None: if attn is None: attn = scores.new(bsz * beam_size, src_tokens.size(1), maxlen + 2) attn_buf = attn.clone() nonpad_idxs = src_tokens.ne(self.pad) attn[:, :, step + 1].copy_(avg_attn_scores) scores = scores.type_as(lprobs) scores_buf = scores_buf.type_as(lprobs) eos_bbsz_idx = buffer('eos_bbsz_idx') eos_scores = buffer('eos_scores', type_of=scores) if step < maxlen: if prefix_tokens is not None and step < prefix_tokens.size(1): probs_slice = lprobs.view(bsz, -1, lprobs.size(-1))[:, 0, :] cand_scores = torch.gather( probs_slice, dim=1, index=prefix_tokens[:, step].view(-1, 1).data ).expand(-1, cand_size) cand_indices = prefix_tokens[:, step].view(-1, 1).expand(bsz, cand_size).data cand_beams = torch.zeros_like(cand_indices) else: cand_scores, cand_indices, cand_beams = self.search.step( step, lprobs.view(bsz, -1, self.vocab_size), scores.view(bsz, beam_size, -1)[:, :, :step], ) else: # make probs contain cumulative scores for each hypothesis lprobs.add_(scores[:, step - 1].unsqueeze(-1)) # finalize all active hypotheses once we hit maxlen # pick the hypothesis with the highest prob of EOS right now torch.sort( lprobs[:, self.eos], descending=True, out=(eos_scores, eos_bbsz_idx), ) num_remaining_sent -= len(finalize_hypos( step, eos_bbsz_idx, eos_scores)) assert num_remaining_sent == 0 break # cand_bbsz_idx contains beam indices for the top candidate # hypotheses, with a range of values: [0, bsz*beam_size), # and dimensions: [bsz, cand_size] cand_bbsz_idx = cand_beams.add(bbsz_offsets) # finalize hypotheses that end in eos eos_mask = cand_indices.eq(self.eos) finalized_sents = set() if step >= self.minlen: # only consider eos when it's among the top beam_size indices torch.masked_select( cand_bbsz_idx[:, :beam_size], mask=eos_mask[:, :beam_size], out=eos_bbsz_idx, ) if eos_bbsz_idx.numel() > 0: torch.masked_select( cand_scores[:, :beam_size], mask=eos_mask[:, :beam_size], out=eos_scores, ) finalized_sents = finalize_hypos( step, eos_bbsz_idx, eos_scores, cand_scores) num_remaining_sent -= len(finalized_sents) assert num_remaining_sent >= 0 if num_remaining_sent == 0: break assert step < maxlen if len(finalized_sents) > 0: new_bsz = bsz - len(finalized_sents) # construct batch_idxs which holds indices of batches to keep for the next pass batch_mask = cand_indices.new_ones(bsz) batch_mask[cand_indices.new(finalized_sents)] = 0 batch_idxs = batch_mask.nonzero().squeeze(-1) eos_mask = eos_mask[batch_idxs] cand_beams = cand_beams[batch_idxs] bbsz_offsets.resize_(new_bsz, 1) cand_bbsz_idx = cand_beams.add(bbsz_offsets) cand_scores = cand_scores[batch_idxs] cand_indices = cand_indices[batch_idxs] if prefix_tokens is not None: prefix_tokens = prefix_tokens[batch_idxs] scores = scores.view(bsz, -1)[batch_idxs].view(new_bsz * beam_size, -1) scores_buf.resize_as_(scores) tokens = tokens.view(bsz, -1)[batch_idxs].view(new_bsz * beam_size, -1) tokens_buf.resize_as_(tokens) if attn is not None: attn = attn.view(bsz, -1)[batch_idxs].view(new_bsz * beam_size, attn.size(1), -1) attn_buf.resize_as_(attn) bsz = new_bsz else: batch_idxs = None # set active_mask so that values > cand_size indicate eos hypos # and values < cand_size indicate candidate active hypos. # After, the min values per row are the top candidate active hypos active_mask = buffer('active_mask') torch.add( eos_mask.type_as(cand_offsets) * cand_size, cand_offsets[:eos_mask.size(1)], out=active_mask, ) # get the top beam_size active hypotheses, which are just the hypos # with the smallest values in active_mask active_hypos, _ignore = buffer('active_hypos'), buffer('_ignore') torch.topk( active_mask, k=beam_size, dim=1, largest=False, out=(_ignore, active_hypos) ) active_bbsz_idx = buffer('active_bbsz_idx') torch.gather( cand_bbsz_idx, dim=1, index=active_hypos, out=active_bbsz_idx, ) active_scores = torch.gather( cand_scores, dim=1, index=active_hypos, out=scores[:, step].view(bsz, beam_size), ) active_bbsz_idx = active_bbsz_idx.view(-1) active_scores = active_scores.view(-1) # copy tokens and scores for active hypotheses torch.index_select( tokens[:, :step + 1], dim=0, index=active_bbsz_idx, out=tokens_buf[:, :step + 1], ) torch.gather( cand_indices, dim=1, index=active_hypos, out=tokens_buf.view(bsz, beam_size, -1)[:, :, step + 1], ) if step > 0: torch.index_select( scores[:, :step], dim=0, index=active_bbsz_idx, out=scores_buf[:, :step], ) torch.gather( cand_scores, dim=1, index=active_hypos, out=scores_buf.view(bsz, beam_size, -1)[:, :, step], ) # copy attention for active hypotheses if attn is not None: torch.index_select( attn[:, :, :step + 2], dim=0, index=active_bbsz_idx, out=attn_buf[:, :, :step + 2], ) # swap buffers tokens, tokens_buf = tokens_buf, tokens scores, scores_buf = scores_buf, scores if attn is not None: attn, attn_buf = attn_buf, attn # reorder incremental state in decoder reorder_state = active_bbsz_idx # sort by score descending for sent in range(len(finalized)): finalized[sent] = sorted(finalized[sent], key=lambda r: r['score'], reverse=True) return finalized def _decode(self, tokens, encoder_outs, incremental_states): if len(self.models) == 1: return self._decode_one(tokens, self.models[0], encoder_outs[0], incremental_states, log_probs=True) avg_probs = None avg_attn = None for model, encoder_out in zip(self.models, encoder_outs): probs, attn = self._decode_one(tokens, model, encoder_out, incremental_states, log_probs=False) if avg_probs is None: avg_probs = probs else: avg_probs.add_(probs) if attn is not None: if avg_attn is None: avg_attn = attn else: avg_attn.add_(attn) avg_probs.div_(len(self.models)) avg_probs.log_() if avg_attn is not None: avg_attn.div_(len(self.models)) return avg_probs, avg_attn def _decode_one(self, tokens, model, encoder_out, incremental_states, log_probs): with torch.no_grad(): if incremental_states[model] is not None: decoder_out = list(model.decoder(tokens, encoder_out, incremental_state=incremental_states[model])) else: decoder_out = list(model.decoder(tokens, encoder_out)) decoder_out[0] = decoder_out[0][:, -1, :] attn = decoder_out[1] if type(attn) is dict: attn = attn['attn'] if attn is not None: if type(attn) is dict: attn = attn['attn'] attn = attn[:, -1, :] probs = model.get_normalized_probs(decoder_out, log_probs=log_probs) return probs, attn
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/sequence_scorer.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import torch from fairseq import utils class SequenceScorer(object): """Scores the target for a given source sentence.""" def __init__(self, models, tgt_dict): self.models = models self.pad = tgt_dict.pad() def cuda(self): for model in self.models: model.cuda() return self def score_batched_itr(self, data_itr, cuda=False, timer=None): """Iterate over a batched dataset and yield scored translations.""" for sample in data_itr: s = utils.move_to_cuda(sample) if cuda else sample if timer is not None: timer.start() pos_scores, attn = self.score(s) for i, id in enumerate(s['id'].data): # remove padding from ref src = utils.strip_pad(s['net_input']['src_tokens'].data[i, :], self.pad) ref = utils.strip_pad(s['target'].data[i, :], self.pad) if s['target'] is not None else None tgt_len = ref.numel() pos_scores_i = pos_scores[i][:tgt_len] score_i = pos_scores_i.sum() / tgt_len if attn is not None: attn_i = attn[i] _, alignment = attn_i.max(dim=0) else: attn_i = alignment = None hypos = [{ 'tokens': ref, 'score': score_i, 'attention': attn_i, 'alignment': alignment, 'positional_scores': pos_scores_i, }] if timer is not None: timer.stop(s['ntokens']) # return results in the same format as SequenceGenerator yield id, src, ref, hypos def score(self, sample): """Score a batch of translations.""" net_input = sample['net_input'] # compute scores for each model in the ensemble avg_probs = None avg_attn = None for model in self.models: with torch.no_grad(): model.eval() decoder_out = model.forward(**net_input) attn = decoder_out[1] probs = model.get_normalized_probs(decoder_out, log_probs=False, sample=sample).data if avg_probs is None: avg_probs = probs else: avg_probs.add_(probs) if attn is not None: attn = attn.data if avg_attn is None: avg_attn = attn else: avg_attn.add_(attn) avg_probs.div_(len(self.models)) avg_probs.log_() if avg_attn is not None: avg_attn.div_(len(self.models)) avg_probs = avg_probs.gather( dim=2, index=sample['target'].data.unsqueeze(-1), ) return avg_probs.squeeze(2), avg_attn
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/tasks/__init__.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import argparse import importlib import os from .fairseq_task import FairseqTask TASK_REGISTRY = {} TASK_CLASS_NAMES = set() def setup_task(args): return TASK_REGISTRY[args.task].setup_task(args) def register_task(name): """ New tasks can be added to fairseq with the :func:`~fairseq.tasks.register_task` function decorator. For example:: @register_task('classification') class ClassificationTask(FairseqTask): (...) .. note:: All Tasks must implement the :class:`~fairseq.tasks.FairseqTask` interface. Please see the Args: name (str): the name of the task """ def register_task_cls(cls): if name in TASK_REGISTRY: raise ValueError('Cannot register duplicate task ({})'.format(name)) if not issubclass(cls, FairseqTask): raise ValueError('Task ({}: {}) must extend FairseqTask'.format(name, cls.__name__)) if cls.__name__ in TASK_CLASS_NAMES: raise ValueError('Cannot register task with duplicate class name ({})'.format(cls.__name__)) TASK_REGISTRY[name] = cls TASK_CLASS_NAMES.add(cls.__name__) return cls return register_task_cls # automatically import any Python files in the tasks/ directory for file in os.listdir(os.path.dirname(__file__)): if file.endswith('.py') and not file.startswith('_'): task_name = file[:file.find('.py')] importlib.import_module('fairseq.tasks.' + task_name) # expose `task_parser` for sphinx if task_name in TASK_REGISTRY: parser = argparse.ArgumentParser(add_help=False) group_task = parser.add_argument_group('Task name') group_task.add_argument( '--task', metavar=task_name, help='Enable this task with: ``--task=' + task_name + '``' ) group_args = parser.add_argument_group('Additional command-line arguments') TASK_REGISTRY[task_name].add_args(group_args) globals()[task_name + '_parser'] = parser
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/tasks/bert.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import itertools import os import numpy as np from torch.utils.data import ConcatDataset from fairseq import options from fairseq.data import ( Dictionary, BertDictionary, IndexedInMemoryDataset, IndexedRawTextDataset, BertDataset ) from . import FairseqTask, register_task @register_task('bert') class BertTask(FairseqTask): """ Translate from one (source) language to another (target) language. Args: src_dict (Dictionary): dictionary for the source language tgt_dict (Dictionary): dictionary for the target language .. note:: The translation task is compatible with :mod:`train.py <train>`, :mod:`generate.py <generate>` and :mod:`interactive.py <interactive>`. The translation task provides the following additional command-line arguments: .. argparse:: :ref: fairseq.tasks.translation_parser :prog: """ @staticmethod def add_args(parser): """Add task-specific arguments to the parser.""" parser.add_argument('data', nargs='+', help='path(s) to data directorie(s)') parser.add_argument('--raw-text', action='store_true', help='load raw text dataset') parser.add_argument('--left-pad', default='False', type=str, metavar='BOOL', help='pad the sentence on the left') parser.add_argument('--max-positions', default=384, type=int, metavar='N', help='max number of tokens in the sequence') parser.add_argument('--masked-lm-prob', default=0.15, type=float, metavar='P', help='masked LM probability') parser.add_argument('--mlm-mask-prob', default=0.8, type=float, metavar='P', help='probability to mask a word in MLM') parser.add_argument('--mlm-random-prob', default=0.1, type=float, metavar='P', help='probability to replace with a random word') def __init__(self, args, dictionary): super().__init__(args) self.dict = dictionary @classmethod def setup_task(cls, args, **kwargs): """Setup the task (e.g., load dictionaries). Args: args (argparse.Namespace): parsed command-line arguments """ args.left_pad = options.eval_bool(args.left_pad) # load dictionaries dictionary = BertDictionary.load(os.path.join(args.data[0], 'dict.txt')) print('| dictionary: {} types'.format(len(dictionary))) return cls(args, dictionary) def load_dataset(self, split, combine=False): """Load a given dataset split. Args: split (str): name of the split (e.g., train, valid, test) """ def split_exists(split, data_path): filename = os.path.join(data_path, split) if self.args.raw_text and IndexedRawTextDataset.exists(filename): return True elif not self.args.raw_text and IndexedInMemoryDataset.exists(filename): return True return False def indexed_dataset(path, dictionary): if self.args.raw_text: return IndexedRawTextDataset(path, dictionary) elif IndexedInMemoryDataset.exists(path): return IndexedInMemoryDataset(path, fix_lua_indexing=True) return None datasets = [] data_paths = self.args.data for data_path in data_paths: for k in itertools.count(): split_k = split + (str(k) if k > 0 else '') if split_exists(split_k, data_path): prefix = os.path.join(data_path, split_k) else: if k > 0: break else: raise FileNotFoundError('Dataset not found: {} ({})'.format(split, data_path)) datasets.append(indexed_dataset(prefix, self.dict)) print('| {} {} {} examples'.format(data_path, split_k, len(datasets[-1]))) if not combine: break if len(datasets) == 1: dataset = datasets[0] sizes = dataset.sizes else: if self.args.upsample_primary > 1: datasets.extend([datasets[0]] * (self.args.upsample_primary - 1)) dataset = ConcatDataset(datasets) sizes = np.concatenate([ds.sizes for ds in datasets]) self.datasets[split] = BertDataset( dataset, sizes, self.dict, self.args.left_pad, self.args.max_positions ) def max_positions(self): """Return the max sentence length allowed by the task.""" return self.args.max_positions @property def source_dictionary(self): """Return the source :class:`~fairseq.data.Dictionary`.""" return self.dict @property def target_dictionary(self): """Return the target :class:`~fairseq.data.Dictionary`.""" return self.dict
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/tasks/fairseq_task.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. from fairseq.data import data_utils, FairseqDataset, iterators class FairseqTask(object): """ Tasks store dictionaries and provide helpers for loading/iterating over Datasets, initializing the Model/Criterion and calculating the loss. """ @staticmethod def add_args(parser): """Add task-specific arguments to the parser.""" pass def __init__(self, args): self.args = args self.datasets = {} @classmethod def setup_task(cls, args, **kwargs): """Setup the task (e.g., load dictionaries). Args: args (argparse.Namespace): parsed command-line arguments """ return cls(args) def load_dataset(self, split, combine=False): """Load a given dataset split. Args: split (str): name of the split (e.g., train, valid, test) """ raise NotImplementedError def dataset(self, split): """ Return a loaded dataset split. Args: split (str): name of the split (e.g., train, valid, test) Returns: a :class:`~fairseq.data.FairseqDataset` corresponding to *split* """ from fairseq.data import FairseqDataset if split not in self.datasets: raise KeyError('Dataset not loaded: ' + split) if not isinstance(self.datasets[split], FairseqDataset): raise TypeError('Datasets are expected to be of type FairseqDataset') return self.datasets[split] def get_batch_iterator( self, dataset, max_tokens=None, max_sentences=None, max_positions=None, ignore_invalid_inputs=False, required_batch_size_multiple=1, seed=1, num_shards=1, shard_id=0, ): """ Get an iterator that yields batches of data from the given dataset. Args: dataset (~fairseq.data.FairseqDataset): dataset to batch max_tokens (int, optional): max number of tokens in each batch. Default: ``None`` max_sentences (int, optional): max number of sentences in each batch. Default: ``None`` max_positions (optional): max sentence length supported by the model. Default: ``None`` ignore_invalid_inputs (bool, optional): don't raise Exception for sentences that are too long. Default: ``False`` required_batch_size_multiple (int, optional): require batch size to be a multiple of N. Default: ``1`` seed (int, optional): seed for random number generator for reproducibility. Default: ``1`` num_shards (int, optional): shard the data iterator into N shards. Default: ``1`` shard_id (int, optional): which shard of the data iterator to return. Default: ``0`` Returns: ~fairseq.iterators.EpochBatchIterator: a batched iterator over the given dataset split """ assert isinstance(dataset, FairseqDataset) # get indices ordered by example size with data_utils.numpy_seed(seed): indices = dataset.ordered_indices() # filter examples that are too large indices = data_utils.filter_by_size( indices, dataset.size, max_positions, raise_exception=(not ignore_invalid_inputs), ) # create mini-batches with given size constraints batch_sampler = data_utils.batch_by_size( indices, dataset.num_tokens, max_tokens=max_tokens, max_sentences=max_sentences, required_batch_size_multiple=required_batch_size_multiple, ) # return a reusable, sharded iterator return iterators.EpochBatchIterator( dataset=dataset, collate_fn=dataset.collater, batch_sampler=batch_sampler, seed=seed, num_shards=num_shards, shard_id=shard_id, ) def build_model(self, args): """ Build the :class:`~fairseq.models.BaseFairseqModel` instance for this task. Args: args (argparse.Namespace): parsed command-line arguments Returns: a :class:`~fairseq.models.BaseFairseqModel` instance """ from fairseq import models return models.build_model(args, self) def build_criterion(self, args): """ Build the :class:`~fairseq.criterions.FairseqCriterion` instance for this task. Args: args (argparse.Namespace): parsed command-line arguments Returns: a :class:`~fairseq.criterions.FairseqCriterion` instance """ from fairseq import criterions return criterions.build_criterion(args, self) def get_loss(self, model, criterion, sample): """ Return the loss as computed by *criterion* for the given *model* and *sample*. Args: model (~fairseq.models.BaseFairseqModel): the model criterion (~fairseq.criterions.FairseqCriterion): the criterion sample (dict): the mini-batch. The format is defined by the :class:`~fairseq.data.FairseqDataset`. """ return criterion(model, sample) def max_positions(self): """Return the max input length allowed by the task.""" return None @property def source_dictionary(self): """Return the source :class:`~fairseq.data.Dictionary` (if applicable for this task).""" raise NotImplementedError @property def target_dictionary(self): """Return the target :class:`~fairseq.data.Dictionary` (if applicable for this task).""" raise NotImplementedError
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/tasks/glue.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import itertools import os import torch import numpy as np from torch.utils.data import ConcatDataset from fairseq import options from fairseq.data import ( BertDictionary, IndexedInMemoryDataset, IndexedRawTextDataset, GlueSingleDataset, GluePairDataset ) from . import FairseqTask, register_task @register_task('glue_single') class GlueSingleTask(FairseqTask): @staticmethod def add_args(parser): """Add task-specific arguments to the parser.""" parser.add_argument('data', nargs='+', help='path(s) to data directorie(s)') parser.add_argument('--raw-text', action='store_true', help='load raw text dataset') parser.add_argument('--left-pad', default='False', type=str, metavar='BOOL', help='pad the sentence on the left') parser.add_argument('--max-positions', default=384, type=int, metavar='N', help='max number of tokens in the sequence') def __init__(self, args, dictionary): super().__init__(args) self.dict = dictionary @classmethod def setup_task(cls, args, **kwargs): """Setup the task (e.g., load dictionaries). Args: args (argparse.Namespace): parsed command-line arguments """ args.left_pad = options.eval_bool(args.left_pad) # load dictionaries dictionary = BertDictionary.load(os.path.join(args.data[0], 'dict.txt')) print('| dictionary: {} types'.format(len(dictionary))) return cls(args, dictionary) def load_dataset(self, split, combine=False): """Load a given dataset split. Args: split (str): name of the split (e.g., train, valid, test) """ def split_exists(split, data_path): filename = os.path.join(data_path, split) if self.args.raw_text and IndexedRawTextDataset.exists(filename): return True elif not self.args.raw_text and IndexedInMemoryDataset.exists(filename): return True return False def indexed_dataset(path, dictionary): if self.args.raw_text: return IndexedRawTextDataset(path, dictionary) elif IndexedInMemoryDataset.exists(path): return IndexedInMemoryDataset(path, fix_lua_indexing=True) return None datasets, labels = [], [] data_paths = self.args.data for data_path in data_paths: for k in itertools.count(): split_k = split + (str(k) if k > 0 else '') if split_exists(split_k, data_path) and (os.path.exists(os.path.join(data_path, split_k + "_labels.pt")) or split == 'test'): prefix = os.path.join(data_path, split_k) else: if k > 0: break else: raise FileNotFoundError('Dataset not found: {} ({})'.format(split, data_path)) datasets.append(indexed_dataset(prefix, self.dict)) if split == 'test': # TODO: make it more good-looking labels.append(torch.zeros(1000000)) else: labels.append(torch.load(os.path.join(data_path, split + "_labels.pt"))) print('| {} {} {} examples'.format(data_path, split_k, len(datasets[-1]))) if not combine: break if len(datasets) == 1: dataset = datasets[0] label = labels[0] sizes = dataset.sizes else: if self.args.upsample_primary > 1: datasets.extend([datasets[0]] * (self.args.upsample_primary - 1)) dataset = ConcatDataset(datasets) label = torch.cat(labels) sizes = np.concatenate([ds.sizes for ds in datasets]) self.datasets[split] = GlueSingleDataset( dataset, sizes, self.dict, label, self.args.left_pad, self.args.max_positions ) def max_positions(self): """Return the max sentence length allowed by the task.""" return self.args.max_positions @property def source_dictionary(self): """Return the source :class:`~fairseq.data.Dictionary`.""" return self.dict @property def target_dictionary(self): """Return the target :class:`~fairseq.data.Dictionary`.""" return self.dict @register_task('glue_pair') class GluePairTask(FairseqTask): @staticmethod def add_args(parser): """Add task-specific arguments to the parser.""" parser.add_argument('data', nargs='+', help='path(s) to data directorie(s)') parser.add_argument('--raw-text', action='store_true', help='load raw text dataset') parser.add_argument('--left-pad', default='False', type=str, metavar='BOOL', help='pad the sentence on the left') parser.add_argument('--max-positions', default=384, type=int, metavar='N', help='max number of tokens in the sequence') parser.add_argument('--symmetric', action='store_true', help='whether or not the sentence pair is symmetric') def __init__(self, args, dictionary): super().__init__(args) self.dict = dictionary @classmethod def setup_task(cls, args, **kwargs): """Setup the task (e.g., load dictionaries). Args: args (argparse.Namespace): parsed command-line arguments """ args.left_pad = options.eval_bool(args.left_pad) # load dictionaries dictionary = BertDictionary.load(os.path.join(args.data[0], 'dict.txt')) print('| dictionary: {} types'.format(len(dictionary))) return cls(args, dictionary) def load_dataset(self, split, combine=False): """Load a given dataset split. Args: split (str): name of the split (e.g., train, valid, test) """ def split_exists(split, data_path): filename = os.path.join(data_path, split) if self.args.raw_text and IndexedRawTextDataset.exists(filename): return True elif not self.args.raw_text and IndexedInMemoryDataset.exists(filename): return True return False def indexed_dataset(path, dictionary): if self.args.raw_text: return IndexedRawTextDataset(path, dictionary) elif IndexedInMemoryDataset.exists(path): return IndexedInMemoryDataset(path, fix_lua_indexing=True) return None datasets, labels = [], [] data_paths = self.args.data for data_path in data_paths: for k in itertools.count(): split_k = split + (str(k) if k > 0 else '') if split_exists(split_k, data_path) and (os.path.exists(os.path.join(data_path, split_k + "_labels.pt")) or split == 'test'): prefix = os.path.join(data_path, split_k) else: if k > 0: break else: raise FileNotFoundError('Dataset not found: {} ({})'.format(split, data_path)) datasets.append(indexed_dataset(prefix, self.dict)) if split == 'test': # TODO: make it more good-looking labels.append(torch.zeros(1000000)) else: labels.append(torch.load(os.path.join(data_path, split + "_labels.pt"))) print('| {} {} {} examples'.format(data_path, split_k, len(datasets[-1]))) if not combine: break if len(datasets) == 1: dataset = datasets[0] label = labels[0] sizes = dataset.sizes else: if self.args.upsample_primary > 1: datasets.extend([datasets[0]] * (self.args.upsample_primary - 1)) dataset = ConcatDataset(datasets) label = torch.cat(labels) sizes = np.concatenate([ds.sizes for ds in datasets]) self.datasets[split] = GluePairDataset( dataset, sizes, self.dict, label, self.args.left_pad, self.args.max_positions, symmetric=split == 'train' and self.args.symmetric ) def max_positions(self): """Return the max sentence length allowed by the task.""" return self.args.max_positions @property def source_dictionary(self): """Return the source :class:`~fairseq.data.Dictionary`.""" return self.dict @property def target_dictionary(self): """Return the target :class:`~fairseq.data.Dictionary`.""" return self.dict
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/tasks/language_modeling.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import itertools import numpy as np import os from torch.utils.data import ConcatDataset from fairseq.data import ( Dictionary, IndexedInMemoryDataset, IndexedRawTextDataset, MonolingualDataset, TokenBlockDataset, TruncatedDictionary ) from . import FairseqTask, register_task @register_task('language_modeling') class LanguageModelingTask(FairseqTask): """ Train a language model. Args: dictionary (Dictionary): the dictionary for the input of the language model output_dictionary (Dictionary): the dictionary for the output of the language model. In most cases it will be the same as dictionary, but could possibly be a more limited version of the dictionary (if --output-dictionary-size is used). targets (List[str]): list of the target types that the language model should predict. Can be one of "self", "future", and "past". Defaults to "future". .. note:: The language modeling task is compatible with :mod:`train.py <train>`, :mod:`generate.py <generate>`, :mod:`interactive.py <interactive>` and :mod:`eval_lm.py <eval_lm>`. The language modeling task provides the following additional command-line arguments: .. argparse:: :ref: fairseq.tasks.language_modeling_parser :prog: """ @staticmethod def add_args(parser): """Add task-specific arguments to the parser.""" parser.add_argument('data', help='path to data directory') parser.add_argument('--sample-break-mode', choices=['none', 'complete', 'eos'], help='If omitted or "none", fills each sample with tokens-per-sample ' 'tokens. If set to "complete", splits samples only at the end ' 'of sentence, but may include multiple sentences per sample. ' 'If set to "eos", includes only one sentence per sample.') parser.add_argument('--tokens-per-sample', default=1024, type=int, help='max number of tokens per sample for LM dataset') parser.add_argument('--raw-text', default=False, action='store_true', help='load raw text dataset') parser.add_argument('--output-dictionary-size', default=-1, type=int, help='limit the size of output dictionary') parser.add_argument('--self-target', action='store_true', help='include self target') parser.add_argument('--future-target', action='store_true', help='include future target') parser.add_argument('--past-target', action='store_true', help='include past target') def __init__(self, args, dictionary, output_dictionary, targets=None): super().__init__(args) self.dictionary = dictionary self.output_dictionary = output_dictionary if targets is None: targets = ['future'] self.targets = targets @classmethod def setup_task(cls, args, **kwargs): """Setup the task (e.g., load dictionaries). Args: args (argparse.Namespace): parsed command-line arguments """ dictionary = Dictionary.load(os.path.join(args.data, 'dict.txt')) print('| dictionary: {} types'.format(len(dictionary))) output_dictionary = dictionary if args.output_dictionary_size >= 0: output_dictionary = TruncatedDictionary(dictionary, args.output_dictionary_size) # upgrade old checkpoints if hasattr(args, 'exclude_self_target'): args.self_target = not args.exclude_self_target targets = [] if args.self_target: targets.append('self') if args.future_target: targets.append('future') if args.past_target: targets.append('past') if len(targets) == 0: # standard language modeling targets = ['future'] return cls(args, dictionary, output_dictionary, targets=targets) def build_model(self, args): model = super().build_model(args) for target in self.targets: if target not in model.supported_targets: raise ValueError('Unsupported language modeling target: {}'.format(target)) return model def load_dataset(self, split, combine=False): """Load a given dataset split. Args: split (str): name of the split (e.g., train, valid, test) """ loaded_datasets = [] for k in itertools.count(): split_k = split + (str(k) if k > 0 else '') path = os.path.join(self.args.data, split_k) if self.args.raw_text and IndexedRawTextDataset.exists(path): ds = IndexedRawTextDataset(path, self.dictionary) tokens = [t for l in ds.tokens_list for t in l] elif not self.args.raw_text and IndexedInMemoryDataset.exists(path): ds = IndexedInMemoryDataset(path, fix_lua_indexing=True) tokens = ds.buffer else: if k > 0: break else: raise FileNotFoundError('Dataset not found: {} ({})'.format(split, self.args.data)) loaded_datasets.append( TokenBlockDataset( tokens, ds.sizes, self.args.tokens_per_sample, pad=self.dictionary.pad(), eos=self.dictionary.eos(), break_mode=self.args.sample_break_mode, include_targets=True, )) print('| {} {} {} examples'.format(self.args.data, split_k, len(loaded_datasets[-1]))) if not combine: break if len(loaded_datasets) == 1: dataset = loaded_datasets[0] sizes = dataset.sizes else: dataset = ConcatDataset(loaded_datasets) sizes = np.concatenate([ds.sizes for ds in loaded_datasets]) add_eos_for_other_targets = self.args.sample_break_mode is not None and self.args.sample_break_mode != 'none' self.datasets[split] = MonolingualDataset( dataset, sizes, self.dictionary, self.output_dictionary, add_eos_for_other_targets=add_eos_for_other_targets, shuffle=False, targets=self.targets, ) @property def target_dictionary(self): """Return the :class:`~fairseq.data.Dictionary` for the language model.""" return self.output_dictionary
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/tasks/translation.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import itertools import numpy as np import os from torch.utils.data import ConcatDataset from fairseq import options from fairseq.data import ( data_utils, Dictionary, LanguagePairDataset, IndexedInMemoryDataset, IndexedRawTextDataset, ) from . import FairseqTask, register_task @register_task('translation') class TranslationTask(FairseqTask): """ Translate from one (source) language to another (target) language. Args: src_dict (Dictionary): dictionary for the source language tgt_dict (Dictionary): dictionary for the target language .. note:: The translation task is compatible with :mod:`train.py <train>`, :mod:`generate.py <generate>` and :mod:`interactive.py <interactive>`. The translation task provides the following additional command-line arguments: .. argparse:: :ref: fairseq.tasks.translation_parser :prog: """ @staticmethod def add_args(parser): """Add task-specific arguments to the parser.""" parser.add_argument('data', nargs='+', help='path(s) to data directorie(s)') parser.add_argument('-s', '--source-lang', default=None, metavar='SRC', help='source language') parser.add_argument('-t', '--target-lang', default=None, metavar='TARGET', help='target language') parser.add_argument('--raw-text', action='store_true', help='load raw text dataset') parser.add_argument('--left-pad-source', default='True', type=str, metavar='BOOL', help='pad the source on the left') parser.add_argument('--left-pad-target', default='False', type=str, metavar='BOOL', help='pad the target on the left') parser.add_argument('--max-source-positions', default=1024, type=int, metavar='N', help='max number of tokens in the source sequence') parser.add_argument('--max-target-positions', default=1024, type=int, metavar='N', help='max number of tokens in the target sequence') parser.add_argument('--upsample-primary', default=1, type=int, help='amount to upsample primary dataset') def __init__(self, args, src_dict, tgt_dict): super().__init__(args) self.src_dict = src_dict self.tgt_dict = tgt_dict @classmethod def setup_task(cls, args, **kwargs): """Setup the task (e.g., load dictionaries). Args: args (argparse.Namespace): parsed command-line arguments """ args.left_pad_source = options.eval_bool(args.left_pad_source) args.left_pad_target = options.eval_bool(args.left_pad_target) # find language pair automatically if args.source_lang is None or args.target_lang is None: args.source_lang, args.target_lang = data_utils.infer_language_pair(args.data[0]) if args.source_lang is None or args.target_lang is None: raise Exception('Could not infer language pair, please provide it explicitly') # load dictionaries src_dict = Dictionary.load(os.path.join(args.data[0], 'dict.{}.txt'.format(args.source_lang))) tgt_dict = Dictionary.load(os.path.join(args.data[0], 'dict.{}.txt'.format(args.target_lang))) assert src_dict.pad() == tgt_dict.pad() assert src_dict.eos() == tgt_dict.eos() assert src_dict.unk() == tgt_dict.unk() print('| [{}] dictionary: {} types'.format(args.source_lang, len(src_dict))) print('| [{}] dictionary: {} types'.format(args.target_lang, len(tgt_dict))) return cls(args, src_dict, tgt_dict) def load_dataset(self, split, combine=False): """Load a given dataset split. Args: split (str): name of the split (e.g., train, valid, test) """ def split_exists(split, src, tgt, lang, data_path): filename = os.path.join(data_path, '{}.{}-{}.{}'.format(split, src, tgt, lang)) if self.args.raw_text and IndexedRawTextDataset.exists(filename): return True elif not self.args.raw_text and IndexedInMemoryDataset.exists(filename): return True return False def indexed_dataset(path, dictionary): if self.args.raw_text: return IndexedRawTextDataset(path, dictionary) elif IndexedInMemoryDataset.exists(path): return IndexedInMemoryDataset(path, fix_lua_indexing=True) return None src_datasets = [] tgt_datasets = [] data_paths = self.args.data for data_path in data_paths: for k in itertools.count(): split_k = split + (str(k) if k > 0 else '') # infer langcode src, tgt = self.args.source_lang, self.args.target_lang if split_exists(split_k, src, tgt, src, data_path): prefix = os.path.join(data_path, '{}.{}-{}.'.format(split_k, src, tgt)) elif split_exists(split_k, tgt, src, src, data_path): prefix = os.path.join(data_path, '{}.{}-{}.'.format(split_k, tgt, src)) else: if k > 0: break else: raise FileNotFoundError('Dataset not found: {} ({})'.format(split, data_path)) src_datasets.append(indexed_dataset(prefix + src, self.src_dict)) tgt_datasets.append(indexed_dataset(prefix + tgt, self.tgt_dict)) print('| {} {} {} examples'.format(data_path, split_k, len(src_datasets[-1]))) if not combine: break assert len(src_datasets) == len(tgt_datasets) if len(src_datasets) == 1: src_dataset, tgt_dataset = src_datasets[0], tgt_datasets[0] src_sizes = src_dataset.sizes tgt_sizes = tgt_dataset.sizes else: if self.args.upsample_primary > 1: src_datasets.extend([src_datasets[0]] * (self.args.upsample_primary - 1)) tgt_datasets.extend([tgt_datasets[0]] * (self.args.upsample_primary - 1)) src_dataset = ConcatDataset(src_datasets) tgt_dataset = ConcatDataset(tgt_datasets) src_sizes = np.concatenate([ds.sizes for ds in src_datasets]) tgt_sizes = np.concatenate([ds.sizes for ds in tgt_datasets]) self.datasets[split] = LanguagePairDataset( src_dataset, src_sizes, self.src_dict, tgt_dataset, tgt_sizes, self.tgt_dict, left_pad_source=self.args.left_pad_source, left_pad_target=self.args.left_pad_target, max_source_positions=self.args.max_source_positions, max_target_positions=self.args.max_target_positions, ) def max_positions(self): """Return the max sentence length allowed by the task.""" return (self.args.max_source_positions, self.args.max_target_positions) @property def source_dictionary(self): """Return the source :class:`~fairseq.data.Dictionary`.""" return self.src_dict @property def target_dictionary(self): """Return the target :class:`~fairseq.data.Dictionary`.""" return self.tgt_dict
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/tokenizer.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. from collections import Counter import os, re import torch from multiprocessing import Pool SPACE_NORMALIZER = re.compile(r"\s+") def tokenize_line(line): line = SPACE_NORMALIZER.sub(" ", line) line = line.strip() return line.split() def safe_readline(f): pos = f.tell() while True: try: return f.readline() except UnicodeDecodeError: pos -= 1 f.seek(pos) # search where this character begins class Tokenizer: @staticmethod def add_file_to_dictionary_single_worker(filename, tokenize, eos_word, worker_id=0, num_workers=1): counter = Counter() with open(filename, 'r') as f: size = os.fstat(f.fileno()).st_size chunk_size = size // num_workers offset = worker_id * chunk_size end = offset + chunk_size f.seek(offset) if offset > 0: safe_readline(f) # drop first incomplete line line = f.readline() while line: for word in tokenize(line): counter.update([word]) counter.update([eos_word]) if f.tell() > end: break line = f.readline() return counter @staticmethod def add_file_to_dictionary(filename, dict, tokenize, num_workers): def merge_result(counter): for w, c in counter.items(): dict.add_symbol(w, c) if num_workers > 1: pool = Pool(processes=num_workers) results = [] for worker_id in range(num_workers): results.append(pool.apply_async( Tokenizer.add_file_to_dictionary_single_worker, (filename, tokenize, dict.eos_word, worker_id, num_workers) )) pool.close() pool.join() for r in results: merge_result(r.get()) else: merge_result(Tokenizer.add_file_to_dictionary_single_worker(filename, tokenize, dict.eos_word)) @staticmethod def binarize(filename, dict, consumer, tokenize=tokenize_line, append_eos=True, reverse_order=False, offset=0, end=-1): nseq, ntok = 0, 0 replaced = Counter() def replaced_consumer(word, idx): if idx == dict.unk_index and word != dict.unk_word: replaced.update([word]) with open(filename, 'r') as f: f.seek(offset) # next(f) breaks f.tell(), hence readline() must be used line = safe_readline(f) while line: if end > 0 and f.tell() > end: break ids = Tokenizer.tokenize( line=line, dict=dict, tokenize=tokenize, add_if_not_exist=False, consumer=replaced_consumer, append_eos=append_eos, reverse_order=reverse_order, ) nseq += 1 ntok += len(ids) consumer(ids) line = f.readline() return {'nseq': nseq, 'nunk': sum(replaced.values()), 'ntok': ntok, 'replaced': replaced} @staticmethod def find_offsets(filename, num_chunks): with open(filename, 'r') as f: size = os.fstat(f.fileno()).st_size chunk_size = size // num_chunks offsets = [0 for _ in range(num_chunks + 1)] for i in range(1, num_chunks): f.seek(chunk_size * i) safe_readline(f) offsets[i] = f.tell() return offsets @staticmethod def tokenize(line, dict, tokenize=tokenize_line, add_if_not_exist=True, consumer=None, append_eos=True, reverse_order=False): words = tokenize(line) if reverse_order: words = list(reversed(words)) nwords = len(words) ids = torch.IntTensor(nwords + 1 if append_eos else nwords) for i, word in enumerate(words): if add_if_not_exist: idx = dict.add_symbol(word) else: idx = dict.index(word) if consumer is not None: consumer(word, idx) ids[i] = idx if append_eos: ids[nwords] = dict.eos_index return ids
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/trainer.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. """ Train a network across multiple GPUs. """ from collections import defaultdict, OrderedDict import contextlib from itertools import chain import torch from fairseq import distributed_utils, models, optim, utils from fairseq.meters import AverageMeter, StopwatchMeter, TimeMeter from fairseq.optim import lr_scheduler class Trainer(object): """Main class for data parallel training. This class supports synchronous distributed data parallel training, where multiple workers each have a full model replica and gradients are accumulated across workers before each update. We use :class:`~torch.nn.parallel.DistributedDataParallel` to handle communication of the gradients across workers. """ def __init__(self, args, task, model, criterion, dummy_batch): if not torch.cuda.is_available(): raise NotImplementedError('Training on CPU is not supported') self.args = args self.task = task # copy model and criterion to current device self.criterion = criterion.cuda() if args.fp16: self._model = model.half().cuda() else: self._model = model.cuda() # initialize meters self.meters = OrderedDict() self.meters['train_loss'] = AverageMeter() self.meters['train_nll_loss'] = AverageMeter() self.meters['valid_loss'] = AverageMeter() self.meters['valid_nll_loss'] = AverageMeter() self.meters['train_acc'] = AverageMeter() self.meters['valid_acc'] = AverageMeter() self.meters['wps'] = TimeMeter() # words per second self.meters['ups'] = TimeMeter() # updates per second self.meters['wpb'] = AverageMeter() # words per batch self.meters['bsz'] = AverageMeter() # sentences per batch self.meters['gnorm'] = AverageMeter() # gradient norm self.meters['clip'] = AverageMeter() # % of updates clipped self.meters['oom'] = AverageMeter() # out of memory if args.fp16: self.meters['loss_scale'] = AverageMeter() # dynamic loss scale self.meters['wall'] = TimeMeter() # wall time in seconds self.meters['train_wall'] = StopwatchMeter() # train wall time in seconds self.cache = OrderedDict() self.cache['valid_x'] = [] self.cache['valid_y'] = [] self.cache['valid_tp'] = [] self.cache['valid_tn'] = [] self.cache['valid_fp'] = [] self.cache['valid_fn'] = [] self._dummy_batch = dummy_batch self._num_updates = 0 self._optim_history = None self._optimizer = None self._wrapped_model = None @property def model(self): if self._wrapped_model is None: if self.args.distributed_world_size > 1: self._wrapped_model = models.DistributedFairseqModel( self.args, self._model, ) else: self._wrapped_model = self._model return self._wrapped_model @property def optimizer(self): if self._optimizer is None: self._build_optimizer() return self._optimizer def _build_optimizer(self): if self.args.fp16: if torch.cuda.get_device_capability(0)[0] < 7: print('| WARNING: your device does NOT support faster training with --fp16, ' 'please switch to FP32 which is likely to be faster') params = list(filter(lambda p: p.requires_grad, self.model.parameters())) self._optimizer = optim.FP16Optimizer.build_optimizer(self.args, params) else: if torch.cuda.get_device_capability(0)[0] >= 7: print('| NOTICE: your device may support faster training with --fp16') self._optimizer = optim.build_optimizer(self.args, self.model.parameters()) self.lr_scheduler = lr_scheduler.build_lr_scheduler(self.args, self._optimizer) def save_checkpoint(self, filename, extra_state): """Save all training state in a checkpoint file.""" if distributed_utils.is_master(self.args): # only save one checkpoint extra_state['train_meters'] = self.meters utils.save_state( filename, self.args, self.get_model(), self.criterion, self.optimizer, self.lr_scheduler, self._num_updates, self._optim_history, extra_state, ) def load_checkpoint(self, filename, reset_optimizer=False, reset_lr_scheduler=False, optimizer_overrides=None): """Load all training state from a checkpoint file.""" extra_state, self._optim_history, last_optim_state = \ utils.load_model_state(filename, self.get_model()) if last_optim_state is not None and not reset_optimizer: # rebuild optimizer after loading model, since params may have changed self._build_optimizer() # only reload optimizer and lr_scheduler if they match last_optim = self._optim_history[-1] assert last_optim['criterion_name'] == self.criterion.__class__.__name__, \ 'criterion does not match; please reset the optimizer (--reset-optimizer)' assert last_optim['optimizer_name'] == self.optimizer.__class__.__name__, \ 'optimizer does not match; please reset the optimizer (--reset-optimizer)' if not reset_lr_scheduler: self.lr_scheduler.load_state_dict(last_optim['lr_scheduler_state']) self.optimizer.load_state_dict(last_optim_state, optimizer_overrides) self._num_updates = last_optim['num_updates'] if extra_state is not None and 'train_meters' in extra_state: self.meters.update(extra_state['train_meters']) del extra_state['train_meters'] # reset TimeMeters, since their start times don't make sense anymore for meter in self.meters.values(): if isinstance(meter, TimeMeter): meter.reset() return extra_state def train_step(self, samples, dummy_batch=False): """Do forward, backward and parameter update.""" # Set seed based on args.seed and the update number so that we get # reproducible results when resuming from checkpoints seed = self.args.seed + self.get_num_updates() torch.manual_seed(seed) torch.cuda.manual_seed(seed) self.model.train() self.zero_grad() if not dummy_batch: self.meters['train_wall'].start() # forward and backward pass logging_outputs, sample_sizes, ooms = [], [], 0 for i, sample in enumerate(samples): sample = self._prepare_sample(sample) if sample is None: # when sample is None, run forward/backward on a dummy batch # and ignore the resulting gradients sample = self._prepare_sample(self._dummy_batch) ignore_grad = True else: ignore_grad = False try: # forward loss, sample_size, logging_output = self.task.get_loss( self.model, self.criterion, sample, ) if ignore_grad: loss *= 0 if self.args.distributed_world_size > 1: # only all-reduce gradients in the last backwards pass if i < len(samples) - 1: self.model.need_reduction = False else: self.model.need_reduction = True # backward self.optimizer.backward(loss) if not ignore_grad: logging_outputs.append(logging_output) sample_sizes.append(sample_size) except RuntimeError as e: if 'out of memory' in str(e): print('| WARNING: ran out of memory, skipping batch') ooms += 1 self.zero_grad() else: raise e if dummy_batch: return None # gather logging outputs from all replicas if self.args.distributed_world_size > 1: logging_outputs, sample_sizes, ooms = zip(*distributed_utils.all_gather_list( [logging_outputs, sample_sizes, ooms], )) logging_outputs = list(chain.from_iterable(logging_outputs)) sample_sizes = list(chain.from_iterable(sample_sizes)) ooms = sum(ooms) if ooms == self.args.distributed_world_size: print('| WARNING: OOM in all workers, skipping update') self.zero_grad() return None # aggregate logging outputs and sample sizes logging_output = self.criterion.__class__.aggregate_logging_outputs(logging_outputs) sample_size = self.criterion.__class__.grad_denom(sample_sizes) if not all(k in logging_output for k in ['ntokens', 'nsentences']): raise Exception(( 'Please update the {}.aggregate_logging_outputs() method to ' 'return ntokens and nsentences' ).format(self.criterion.__class__.__name__)) try: # normalize grads by sample size self.optimizer.multiply_grads(self.args.distributed_world_size / float(sample_size)) # clip grads grad_norm = self.optimizer.clip_grad_norm(self.args.clip_norm) # take an optimization step self.optimizer.step() self._num_updates += 1 # update learning rate self.lr_scheduler.step_update(self._num_updates) # update meters ntokens = logging_output.get('ntokens', 0) nsentences = logging_output.get('nsentences', 0) self.meters['wps'].update(ntokens) self.meters['ups'].update(1.) self.meters['wpb'].update(ntokens) self.meters['bsz'].update(nsentences) self.meters['gnorm'].update(grad_norm) self.meters['clip'].update( 1. if grad_norm > self.args.clip_norm and self.args.clip_norm > 0 else 0. ) self.meters['oom'].update(ooms) self.meters['train_loss'].update(logging_output.get('loss', 0), sample_size) if 'acc' in logging_output: self.meters['train_acc'].update(logging_output.get('acc', 0), sample_size) elif 'nsp_acc' in logging_output: self.meters['train_acc'].update(logging_output.get('nsp_acc', 0), nsentences) if 'nll_loss' in logging_output: self.meters['train_nll_loss'].update(logging_output.get('nll_loss', 0), ntokens) elif 'mlm_loss' in logging_output: self.meters['train_nll_loss'].update(logging_output.get('mlm_loss', 0), sample_size) except OverflowError as e: print('| WARNING: overflow detected, ' + str(e)) self.zero_grad() logging_output = None if self.args.fp16: self.meters['loss_scale'].reset() self.meters['loss_scale'].update(self.optimizer.scaler.loss_scale) self.meters['train_wall'].stop() return logging_output def valid_step(self, sample, raise_oom=False): """Do forward pass in evaluation mode.""" with torch.no_grad(): self.model.eval() sample = self._prepare_sample(sample) if sample is None: sample = self._prepare_sample(self._dummy_batch) ignore_results = True else: ignore_results = False try: _loss, sample_size, logging_output = self.task.get_loss( self.model, self.criterion, sample, ) except RuntimeError as e: if 'out of memory' in str(e) and not raise_oom: print('| WARNING: ran out of memory, retrying batch') for p in self.model.parameters(): if p.grad is not None: del p.grad # free some memory torch.cuda.empty_cache() return self.valid_step(sample, raise_oom=True) else: raise e if ignore_results: logging_output, sample_size = {}, 0 # gather logging outputs from all replicas if self.args.distributed_world_size > 1: logging_output, sample_size = zip(*distributed_utils.all_gather_list( [logging_output, sample_size], )) logging_output = list(logging_output) sample_size = list(sample_size) else: logging_output = [logging_output] sample_size = [sample_size] # aggregate logging outputs and sample sizes logging_output = self.criterion.__class__.aggregate_logging_outputs(logging_output) sample_size = self.criterion.__class__.grad_denom(sample_size) # update meters for validation ntokens = logging_output.get('ntokens', 0) nsentences = logging_output.get('nsentences', 0) self.meters['valid_loss'].update(logging_output.get('loss', 0), sample_size) if 'acc' in logging_output: self.meters['valid_acc'].update(logging_output.get('acc', 0), sample_size) elif 'nsp_acc' in logging_output: self.meters['train_acc'].update(logging_output.get('nsp_acc', 0), nsentences) if 'nll_loss' in logging_output: self.meters['valid_nll_loss'].update(logging_output.get('nll_loss', 0), ntokens) elif 'mlm_loss' in logging_output: self.meters['train_nll_loss'].update(logging_output.get('mlm_loss', 0), sample_size) if 'x' in logging_output: self.cache['valid_x'].append(logging_output['x']) if 'y' in logging_output: self.cache['valid_y'].append(logging_output['y']) if 'tp' in logging_output: self.cache['valid_tp'].append(logging_output['tp']) if 'tn' in logging_output: self.cache['valid_tn'].append(logging_output['tn']) if 'fp' in logging_output: self.cache['valid_fp'].append(logging_output['fp']) if 'fn' in logging_output: self.cache['valid_fn'].append(logging_output['fn']) return logging_output def dummy_train_step(self, dummy_batch): """Dummy training step for warming caching allocator.""" self.train_step(dummy_batch, dummy_batch=True) self.zero_grad() def zero_grad(self): self.optimizer.zero_grad() def lr_step(self, epoch, val_loss=None): """Adjust the learning rate based on the validation loss.""" return self.lr_scheduler.step(epoch, val_loss) def lr_step_update(self, num_updates): """Update the learning rate after each update.""" return self.lr_scheduler.step_update(num_updates) def get_lr(self): """Get the current learning rate.""" return self.optimizer.get_lr() def get_model(self): """Get the (non-wrapped) model instance.""" return self._model def get_meter(self, name): """Get a specific meter by name.""" if name not in self.meters: return None return self.meters[name] def get_num_updates(self): """Get the number of parameters updates.""" return self._num_updates def _prepare_sample(self, sample): if sample is None or len(sample) == 0: return None return utils.move_to_cuda(sample)
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/fairseq/utils.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. from collections import defaultdict, OrderedDict import logging import os import re import torch import traceback from torch.serialization import default_restore_location def torch_persistent_save(*args, **kwargs): for i in range(3): try: return torch.save(*args, **kwargs) except Exception: if i == 2: logging.error(traceback.format_exc()) def convert_state_dict_type(state_dict, ttype=torch.FloatTensor): if isinstance(state_dict, dict): cpu_dict = OrderedDict() for k, v in state_dict.items(): cpu_dict[k] = convert_state_dict_type(v) return cpu_dict elif isinstance(state_dict, list): return [convert_state_dict_type(v) for v in state_dict] elif torch.is_tensor(state_dict): return state_dict.type(ttype) else: return state_dict def save_state(filename, args, model, criterion, optimizer, lr_scheduler, num_updates, optim_history=None, extra_state=None): if optim_history is None: optim_history = [] if extra_state is None: extra_state = {} state_dict = { 'args': args, 'model': model.state_dict() if model else {}, 'optimizer_history': optim_history + [ { 'criterion_name': criterion.__class__.__name__, 'optimizer_name': optimizer.__class__.__name__, 'lr_scheduler_state': lr_scheduler.state_dict(), 'num_updates': num_updates, } ], 'last_optimizer_state': convert_state_dict_type(optimizer.state_dict()), 'extra_state': extra_state, } torch_persistent_save(state_dict, filename) def load_model_state(filename, model): if not os.path.exists(filename): return None, [], None state = torch.load(filename, map_location=lambda s, l: default_restore_location(s, 'cpu')) state = _upgrade_state_dict(state) model.upgrade_state_dict(state['model']) # load model parameters try: model.load_state_dict(state['model'], strict=True) except Exception: raise Exception('Cannot load model parameters from checkpoint, ' 'please ensure that the architectures match') return state['extra_state'], state['optimizer_history'], state['last_optimizer_state'] def load_bert_state(filename, model, args): assert os.path.exists(filename), f"File {filename} not found." state = torch.load(filename, map_location=lambda s, l: default_restore_location(s, 'cpu')) state = _upgrade_state_dict(state) state['model'] = _upgrade_state_dict_bert(state['model'], args) model.upgrade_state_dict(state['model']) # load model parameters model.load_state_dict(state['model'], strict=False) return state['extra_state'], state['optimizer_history'], state['last_optimizer_state'] def _upgrade_state_dict_bert(state, args): load_type = getattr(args, "load_type", "all") if "no_fc" in load_type: fc_pattern = re.compile(r"(encoder|decoder)\.layers\.[0-9]+\.fc[0-9]+\.(weight|bias)") state = {k: v for k, v in state.items() if not fc_pattern.match(k)} if "no_out" in load_type: state['decoder.embed_tokens.weight'] = state['embed_out'] del state['embed_out'] del state['classifier.weight'] del state['classifier.bias'] return state def _upgrade_state_dict(state): """Helper for upgrading old model checkpoints.""" # add optimizer_history if 'optimizer_history' not in state: state['optimizer_history'] = [ { 'criterion_name': 'CrossEntropyCriterion', 'best_loss': state['best_loss'], }, ] state['last_optimizer_state'] = state['optimizer'] del state['optimizer'] del state['best_loss'] # move extra_state into sub-dictionary if 'epoch' in state and 'extra_state' not in state: state['extra_state'] = { 'epoch': state['epoch'], 'batch_offset': state['batch_offset'], 'val_loss': state['val_loss'], } del state['epoch'] del state['batch_offset'] del state['val_loss'] # reduce optimizer history's memory usage (only keep the last state) if 'optimizer' in state['optimizer_history'][-1]: state['last_optimizer_state'] = state['optimizer_history'][-1]['optimizer'] for optim_hist in state['optimizer_history']: del optim_hist['optimizer'] # record the optimizer class name if 'optimizer_name' not in state['optimizer_history'][-1]: state['optimizer_history'][-1]['optimizer_name'] = 'FairseqNAG' # move best_loss into lr_scheduler_state if 'lr_scheduler_state' not in state['optimizer_history'][-1]: state['optimizer_history'][-1]['lr_scheduler_state'] = { 'best': state['optimizer_history'][-1]['best_loss'], } del state['optimizer_history'][-1]['best_loss'] # keep track of number of updates if 'num_updates' not in state['optimizer_history'][-1]: state['optimizer_history'][-1]['num_updates'] = 0 # old model checkpoints may not have separate source/target positions if hasattr(state['args'], 'max_positions') and not hasattr(state['args'], 'max_source_positions'): state['args'].max_source_positions = state['args'].max_positions state['args'].max_target_positions = state['args'].max_positions # use stateful training data iterator if 'train_iterator' not in state['extra_state']: state['extra_state']['train_iterator'] = { 'epoch': state['extra_state']['epoch'], 'iterations_in_epoch': state['extra_state'].get('batch_offset', 0), } return state def load_ensemble_for_inference(filenames, task, model_arg_overrides=None): """Load an ensemble of models for inference. model_arg_overrides allows you to pass a dictionary model_arg_overrides -- {'arg_name': arg} -- to override model args that were used during model training """ # load model architectures and weights states = [] for filename in filenames: if not os.path.exists(filename): raise IOError('Model file not found: {}'.format(filename)) state = torch.load(filename, map_location=lambda s, l: default_restore_location(s, 'cpu')) state = _upgrade_state_dict(state) states.append(state) ensemble = [] for state in states: args = state['args'] if model_arg_overrides is not None: args = _override_model_args(args, model_arg_overrides) # build model for ensemble model = task.build_model(args) model.upgrade_state_dict(state['model']) model.load_state_dict(state['model'], strict=True) ensemble.append(model) return ensemble, args def _override_model_args(args, model_arg_overrides): # Uses model_arg_overrides {'arg_name': arg} to override model args for arg_name, arg_val in model_arg_overrides.items(): setattr(args, arg_name, arg_val) return args def move_to_cuda(sample): if len(sample) == 0: return {} def _move_to_cuda(maybe_tensor): if torch.is_tensor(maybe_tensor): return maybe_tensor.cuda() elif isinstance(maybe_tensor, dict): return { key: _move_to_cuda(value) for key, value in maybe_tensor.items() } elif isinstance(maybe_tensor, list): return [_move_to_cuda(x) for x in maybe_tensor] else: return maybe_tensor return _move_to_cuda(sample) INCREMENTAL_STATE_INSTANCE_ID = defaultdict(lambda: 0) def _get_full_incremental_state_key(module_instance, key): module_name = module_instance.__class__.__name__ # assign a unique ID to each module instance, so that incremental state is # not shared across module instances if not hasattr(module_instance, '_fairseq_instance_id'): INCREMENTAL_STATE_INSTANCE_ID[module_name] += 1 module_instance._fairseq_instance_id = INCREMENTAL_STATE_INSTANCE_ID[module_name] return '{}.{}.{}'.format(module_name, module_instance._fairseq_instance_id, key) def get_incremental_state(module, incremental_state, key): """Helper for getting incremental state for an nn.Module.""" full_key = _get_full_incremental_state_key(module, key) if incremental_state is None or full_key not in incremental_state: return None return incremental_state[full_key] def set_incremental_state(module, incremental_state, key, value): """Helper for setting incremental state for an nn.Module.""" if incremental_state is not None: full_key = _get_full_incremental_state_key(module, key) incremental_state[full_key] = value def load_align_dict(replace_unk): if replace_unk is None: align_dict = None elif isinstance(replace_unk, str): # Load alignment dictionary for unknown word replacement if it was passed as an argument. align_dict = {} with open(replace_unk, 'r') as f: for line in f: cols = line.split() align_dict[cols[0]] = cols[1] else: # No alignment dictionary provided but we still want to perform unknown word replacement by copying the # original source word. align_dict = {} return align_dict def print_embed_overlap(embed_dict, vocab_dict): embed_keys = set(embed_dict.keys()) vocab_keys = set(vocab_dict.symbols) overlap = len(embed_keys & vocab_keys) print("| Found {}/{} types in embedding file.".format(overlap, len(vocab_dict))) def parse_embedding(embed_path): """Parse embedding text file into a dictionary of word and embedding tensors. The first line can have vocabulary size and dimension. The following lines should contain word and embedding separated by spaces. Example: 2 5 the -0.0230 -0.0264 0.0287 0.0171 0.1403 at -0.0395 -0.1286 0.0275 0.0254 -0.0932 """ embed_dict = {} with open(embed_path) as f_embed: next(f_embed) # skip header for line in f_embed: pieces = line.rstrip().split(" ") embed_dict[pieces[0]] = torch.Tensor([float(weight) for weight in pieces[1:]]) return embed_dict def load_embedding(embed_dict, vocab, embedding): for idx in range(len(vocab)): token = vocab[idx] if token in embed_dict: embedding.weight.data[idx] = embed_dict[token] return embedding def replace_unk(hypo_str, src_str, alignment, align_dict, unk): from fairseq import tokenizer # Tokens are strings here hypo_tokens = tokenizer.tokenize_line(hypo_str) # TODO: Very rare cases where the replacement is '<eos>' should be handled gracefully src_tokens = tokenizer.tokenize_line(src_str) + ['<eos>'] for i, ht in enumerate(hypo_tokens): if ht == unk: src_token = src_tokens[alignment[i]] # Either take the corresponding value in the aligned dictionary or just copy the original value. hypo_tokens[i] = align_dict.get(src_token, src_token) return ' '.join(hypo_tokens) def post_process_prediction(hypo_tokens, src_str, alignment, align_dict, tgt_dict, remove_bpe): from fairseq import tokenizer hypo_str = tgt_dict.string(hypo_tokens, remove_bpe) if align_dict is not None: hypo_str = replace_unk(hypo_str, src_str, alignment, align_dict, tgt_dict.unk_string()) if align_dict is not None or remove_bpe is not None: # Convert back to tokens for evaluating with unk replacement or without BPE # Note that the dictionary can be modified inside the method. hypo_tokens = tokenizer.Tokenizer.tokenize(hypo_str, tgt_dict, add_if_not_exist=True) return hypo_tokens, hypo_str, alignment def make_positions(tensor, padding_idx, left_pad, onnx_trace=False): """Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols are ignored, but it is necessary to specify whether padding is added on the left side (left_pad=True) or right side (left_pad=False). """ if onnx_trace: range_buf = torch._dim_arange(like=tensor, dim=1) + padding_idx + 1 mask = tensor.ne(padding_idx) positions = range_buf.expand_as(tensor) if left_pad: positions = positions - mask.size(1) + mask.long().sum(dim=1).unsqueeze(1) return positions * mask.long() + positions * (1 - mask.long()) max_pos = padding_idx + 1 + tensor.size(1) if not hasattr(make_positions, 'range_buf'): make_positions.range_buf = tensor.new() make_positions.range_buf = make_positions.range_buf.type_as(tensor) if make_positions.range_buf.numel() < max_pos: torch.arange(padding_idx + 1, max_pos, out=make_positions.range_buf) mask = tensor.ne(padding_idx) positions = make_positions.range_buf[:tensor.size(1)].expand_as(tensor) if left_pad: positions = positions - mask.size(1) + mask.long().sum(dim=1).unsqueeze(1) return tensor.clone().masked_scatter_(mask, positions[mask]) def strip_pad(tensor, pad): return tensor[tensor.ne(pad)] def buffered_arange(max): if not hasattr(buffered_arange, 'buf'): buffered_arange.buf = torch.LongTensor() if max > buffered_arange.buf.numel(): torch.arange(max, out=buffered_arange.buf) return buffered_arange.buf[:max] def convert_padding_direction(src_tokens, padding_idx, right_to_left=False, left_to_right=False): assert right_to_left ^ left_to_right pad_mask = src_tokens.eq(padding_idx) if not pad_mask.any(): # no padding, return early return src_tokens if left_to_right and not pad_mask[:, 0].any(): # already right padded return src_tokens if right_to_left and not pad_mask[:, -1].any(): # already left padded return src_tokens max_len = src_tokens.size(1) range = buffered_arange(max_len).type_as(src_tokens).expand_as(src_tokens) num_pads = pad_mask.long().sum(dim=1, keepdim=True) if right_to_left: index = torch.remainder(range - num_pads, max_len) else: index = torch.remainder(range + num_pads, max_len) return src_tokens.gather(1, index) def item(tensor): if hasattr(tensor, 'item'): return tensor.item() if hasattr(tensor, '__getitem__'): return tensor[0] return tensor def clip_grad_norm_(tensor, max_norm): grad_norm = item(torch.norm(tensor)) if grad_norm > max_norm > 0: clip_coef = max_norm / (grad_norm + 1e-6) tensor.mul_(clip_coef) return grad_norm def fill_with_neg_inf(t): """FP16-compatible function that fills a tensor with -inf.""" return t.float().fill_(float('-inf')).type_as(t) def checkpoint_paths(path, pattern=r'checkpoint(\d+)\.pt'): """Retrieves all checkpoints found in `path` directory. Checkpoints are identified by matching filename to the specified pattern. If the pattern contains groups, the result will be sorted by the first group in descending order. """ pt_regexp = re.compile(pattern) files = os.listdir(path) entries = [] for i, f in enumerate(files): m = pt_regexp.fullmatch(f) if m is not None: idx = int(m.group(1)) if len(m.groups()) > 0 else i entries.append((idx, m.group(0))) return [os.path.join(path, x[1]) for x in sorted(entries, reverse=True)] def resolve_max_positions(*args): """Resolve max position constraints from multiple sources.""" def nullsafe_min(l): minim = None for item in l: if minim is None: minim = item elif item is not None and item < minim: minim = item return minim max_positions = None for arg in args: if max_positions is None: max_positions = arg elif arg is not None: if isinstance(arg, float) or isinstance(arg, int): max_positions = min(max_positions, arg) else: max_positions = tuple( map(nullsafe_min, zip(max_positions, arg)) ) return max_positions
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/generate.py
Python
#!/usr/bin/env python3 -u # Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. """ Translate pre-processed data with a trained model. """ import torch from fairseq import bleu, data, options, progress_bar, tasks, tokenizer, utils from fairseq.meters import StopwatchMeter, TimeMeter from fairseq.sequence_generator import SequenceGenerator from fairseq.sequence_scorer import SequenceScorer def main(args): assert args.path is not None, '--path required for generation!' assert not args.sampling or args.nbest == args.beam, \ '--sampling requires --nbest to be equal to --beam' assert args.replace_unk is None or args.raw_text, \ '--replace-unk requires a raw text dataset (--raw-text)' if args.max_tokens is None and args.max_sentences is None: args.max_tokens = 12000 print(args) use_cuda = torch.cuda.is_available() and not args.cpu # Load dataset splits task = tasks.setup_task(args) task.load_dataset(args.gen_subset) print('| {} {} {} examples'.format(args.data, args.gen_subset, len(task.dataset(args.gen_subset)))) # Set dictionaries src_dict = task.source_dictionary tgt_dict = task.target_dictionary # Load ensemble print('| loading model(s) from {}'.format(args.path)) models, _ = utils.load_ensemble_for_inference(args.path.split(':'), task, model_arg_overrides=eval(args.model_overrides)) # Optimize ensemble for generation for model in models: model.make_generation_fast_( beamable_mm_beam_size=None if args.no_beamable_mm else args.beam, need_attn=args.print_alignment, ) if args.fp16: model.half() # Load alignment dictionary for unknown word replacement # (None if no unknown word replacement, empty if no path to align dictionary) align_dict = utils.load_align_dict(args.replace_unk) # Load dataset (possibly sharded) itr = task.get_batch_iterator( dataset=task.dataset(args.gen_subset), max_tokens=args.max_tokens, max_sentences=args.max_sentences, max_positions=utils.resolve_max_positions( task.max_positions(), *[model.max_positions() for model in models] ), ignore_invalid_inputs=args.skip_invalid_size_inputs_valid_test, required_batch_size_multiple=8, num_shards=args.num_shards, shard_id=args.shard_id, ).next_epoch_itr(shuffle=False) # Initialize generator gen_timer = StopwatchMeter() if args.score_reference: translator = SequenceScorer(models, task.target_dictionary) else: translator = SequenceGenerator( models, task.target_dictionary, beam_size=args.beam, minlen=args.min_len, stop_early=(not args.no_early_stop), normalize_scores=(not args.unnormalized), len_penalty=args.lenpen, unk_penalty=args.unkpen, sampling=args.sampling, sampling_topk=args.sampling_topk, sampling_temperature=args.sampling_temperature, diverse_beam_groups=args.diverse_beam_groups, diverse_beam_strength=args.diverse_beam_strength, ) if use_cuda: translator.cuda() # Generate and compute BLEU score scorer = bleu.Scorer(tgt_dict.pad(), tgt_dict.eos(), tgt_dict.unk()) num_sentences = 0 has_target = True with progress_bar.build_progress_bar(args, itr) as t: if args.score_reference: translations = translator.score_batched_itr(t, cuda=use_cuda, timer=gen_timer) else: translations = translator.generate_batched_itr( t, maxlen_a=args.max_len_a, maxlen_b=args.max_len_b, cuda=use_cuda, timer=gen_timer, prefix_size=args.prefix_size, ) wps_meter = TimeMeter() for sample_id, src_tokens, target_tokens, hypos in translations: # Process input and ground truth has_target = target_tokens is not None target_tokens = target_tokens.int().cpu() if has_target else None # Either retrieve the original sentences or regenerate them from tokens. if align_dict is not None: src_str = task.dataset(args.gen_subset).src.get_original_text(sample_id) target_str = task.dataset(args.gen_subset).tgt.get_original_text(sample_id) else: src_str = src_dict.string(src_tokens, args.remove_bpe) if has_target: target_str = tgt_dict.string(target_tokens, args.remove_bpe, escape_unk=True) if not args.quiet: print('S-{}\t{}'.format(sample_id, src_str)) if has_target: print('T-{}\t{}'.format(sample_id, target_str)) # Process top predictions for i, hypo in enumerate(hypos[:min(len(hypos), args.nbest)]): hypo_tokens, hypo_str, alignment = utils.post_process_prediction( hypo_tokens=hypo['tokens'].int().cpu(), src_str=src_str, alignment=hypo['alignment'].int().cpu() if hypo['alignment'] is not None else None, align_dict=align_dict, tgt_dict=tgt_dict, remove_bpe=args.remove_bpe, ) if not args.quiet: print('H-{}\t{}\t{}'.format(sample_id, hypo['score'], hypo_str)) print('P-{}\t{}'.format( sample_id, ' '.join(map( lambda x: '{:.4f}'.format(x), hypo['positional_scores'].tolist(), )) )) if args.print_alignment: print('A-{}\t{}'.format( sample_id, ' '.join(map(lambda x: str(utils.item(x)), alignment)) )) # Score only the top hypothesis if has_target and i == 0: if align_dict is not None or args.remove_bpe is not None: # Convert back to tokens for evaluation with unk replacement and/or without BPE target_tokens = tokenizer.Tokenizer.tokenize( target_str, tgt_dict, add_if_not_exist=True) scorer.add(target_tokens, hypo_tokens) wps_meter.update(src_tokens.size(0)) t.log({'wps': round(wps_meter.avg)}) num_sentences += 1 print('| Translated {} sentences ({} tokens) in {:.1f}s ({:.2f} sentences/s, {:.2f} tokens/s)'.format( num_sentences, gen_timer.n, gen_timer.sum, num_sentences / gen_timer.sum, 1. / gen_timer.avg)) if has_target: print('| Generate {} with beam={}: {}'.format(args.gen_subset, args.beam, scorer.result_string())) if __name__ == '__main__': parser = options.get_generation_parser() args = options.parse_args_and_arch(parser) main(args)
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/inference.py
Python
#!/usr/bin/env python3 -u # Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. """ Evaluate the perplexity of a trained language model. """ import os import torch import torch.nn.functional as F from fairseq import options, progress_bar, tasks, utils def main(parsed_args): assert parsed_args.path is not None, '--path required for evaluation!' print(parsed_args) use_cuda = torch.cuda.is_available() and not parsed_args.cpu task = tasks.setup_task(parsed_args) # Load ensemble print('| loading model(s) from {}'.format(parsed_args.path)) models, args = utils.load_ensemble_for_inference(parsed_args.path.split(':'), task) args.__dict__.update(parsed_args.__dict__) print(args) task.args = args # Load dataset splits task.load_dataset(args.gen_subset) print('| {} {} {} examples'.format(args.data, args.gen_subset, len(task.dataset(args.gen_subset)))) # Optimize ensemble for generation and set the source and dest dicts on the model (required by scorer) for model in models: model.make_generation_fast_() if use_cuda: model.cuda() if args.fp16: model.half() assert len(models) > 0 itr = task.get_batch_iterator( dataset=task.dataset(args.gen_subset), max_tokens=args.max_tokens or 10000, max_sentences=args.max_sentences, max_positions=utils.resolve_max_positions(*[ model.max_positions() for model in models ]), num_shards=args.num_shards, shard_id=args.shard_id, ignore_invalid_inputs=args.skip_invalid_size_inputs_valid_test, ).next_epoch_itr(shuffle=False) with progress_bar.build_progress_bar(args, itr, no_progress_bar='simple') as progress: with open(args.output, 'w', encoding='utf-8') as fo: if args.criterion == 'mean_squared_error': ans = torch.empty(len(task.dataset(args.gen_subset)), dtype=torch.float) else: ans = torch.empty(len(task.dataset(args.gen_subset)), dtype=torch.long) with torch.no_grad(): for model in models: model.eval() for sample in progress: if use_cuda: sample = utils.move_to_cuda(sample) if args.criterion.endswith('binary'): probs = torch.stack([F.sigmoid(model(**sample['net_input']).view(-1)) for model in models], dim=0).mean(dim=0) preds = torch.stack([sample['id'], (probs >= 0.5).long()], dim=1) elif args.criterion == 'mean_squared_error': probs = torch.stack([model(**sample['net_input']).view(-1) for model in models], dim=0).mean(dim=0) preds = list(zip(*[sample['id'], probs])) else: probs = torch.stack([model.get_normalized_probs(model(**sample['net_input']), log_probs=False) for model in models], dim=0).mean(dim=0) preds = torch.stack([sample['id'], probs.argmax(dim=-1)], dim=1) for i, y in preds: ans[i] = y for y in ans: fo.write(f"{y}\n") if __name__ == '__main__': parser = options.get_inference_parser() args = options.parse_args_and_arch(parser) main(args)
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta