DeBERTA : Decoding-Enhanced BERT with Disentangled Attentiontaeseon ryu
오늘 소개해 드릴 논문은 구글의 BERT와 페이스북 현재 메타의 RoBERTa를 기반으로 만들어진 모델입니다. RoBERTa + Disentangled Attention과 enhanced mask decode
두가지의 핵심 기술로 RoBERTa를 더욱 개선 시킨 모델이라고 이해하시면 될 것 같습니다. 추가적으로 Scale Invariant Fine Tuning을 도입하여 RoBERTa를 상당히 많은 테스크에서, NLU 테스크에서는 RoBERTa, BERT이상의 성능을 보여준 논문이기도 합니다.
논문의 자세한 리뷰부터, 백그라운드 지식까지, 자연어처리팀 진명훈님이 도와주셨습니다.
This document outlines the requirements for an expert system project for a computer science course. Students must build an expert system in Prolog on a domain of their choosing, using concepts covered in class like knowledge acquisition and the expert system development life cycle. The project must include an inference engine, user interface, explanations, knowledge base containing rules and facts, and working memory to represent the current problem state. The final report must cover the background, problem, objectives, significance, scope, limitations, and include diagrams and the Prolog code.
Hilbert Huang Transform (HHT) and Empirical Mode Decomposition (EMD) are algorithms for analyzing data from non-linear and non-stationary systems. EMD decomposes signals into Intrinsic Mode Functions (IMFs) through a process called sifting. The sifting process identifies local extrema and decomposes the signal into IMFs until a monotonic residual function remains. HHT then applies the Hilbert transform to each IMF to obtain the instantaneous frequency. While traditional methods assume linearity and stationarity, HHT is suitable for real-world non-linear and non-stationary signals through the EMD sifting process.
Удянский Николай Александрович - судимый мошенник, криптоаферистssuserad0d22
Сын лейтенанта Шмидта Удянский Николай Александрович: краткое жизнеописание афериста из Харькова
Сын лейтенанта Шмидта Удянский Николай Александрович: краткое жизнеописание афериста из Харькова
Сын лейтенанта Шмидта Удянский Николай Александрович: краткое жизнеописание афериста из Харькова
Имели ли Вы честь услышать о блокчейн-платформе WeWay, а о бизнесмене, у которого никогда не было бизнеса Николае Удянском?
Держу пари, что нет. Никогда не слышали и это похвально. Жаль, что вскоре услышите, исходя из потраченных на пиар денег. Сей персонаж Удянский Николай Александрович щедро посыпает СМИ благостным пометом о себе любимом и не стесняется зачищать сомнительные порталы с однозначной репутацией.
Недавно исчезла статья на сайте недорогого киевского многостаночника Wikibaza — Удянский Николай Александрович аферист Bitcoin Ultimatum и Coinsbit: британские СМИ. А вместе с ней исчезло клоны на других сайтах. Сколько отдал за очищение репутации Николай Удянский можно только догадываться.
Сейчас дорогие и не очень СМИ тиражируют статьи про то, как Удянский Н.А. прикрылся российской Юлой. Очередной высер перл Удянского гласит: Украинская IT-компания Prof-IT, соучредителем которой является бизнесмен Николай Удянский, и международная компания Yoola, основателем которой является Фуад Фатуллаев разработали блокчейн-платформу WeWay. Дальше бла-бла-бла. Как заезженная пластинка довольного афериста. Учитывая, что принадлежащая Николаю Удянскому компания Prof-IT является прачечной средней паршивости, статья нагоняет вселенскую грусть.
Что скрывает прожженный Николай Удянский?
Читайте ещё:Житель Москвы пожаловался на кафе консуматоров на Проспекте Мира
А вычищает этот харьковский герой с деньгами покойного Кернеса тексты куда более интересные, раскрывающие лишь небольшую толику афер Удянского. О них подробно написали журналисты из Великобритании еще в начале года: читаем статью Nikolai Udianskyi rolls out his Ultimatum Bitcoin scam as alt-season looms. Ниже скриншоты удаленного материала с Wikibaza:
Китай, в пределах своей территории, запретил все криптовалютные операции, включая те, которые не приводят к обмену валют на «настоящие» деньги. Отказало КНР и в обслуживании криптовалютных фирм. И запретило гражданам проводить любые операции как с компаниями, так и с валютами. Какие последствия в этом для Bitcoin Ultimatum, детища Удянского Николая Александровича? Да никаких: любой реальный проект это бы убило. Но Биткоин Ультиматум, штаб-квартира которого вроде как находится в Гонг-Конге, это не затронуло. По одной простой причине: затопить можно реальный проект, а не матерое надувательство, которое задумал Николай Удянский. Как известно, если нет проекта — то нет и проблемы.
Подробней в презентации!
IP Lab Manual for Kerala University 3 Year UG ProgrammeSAFAD ISMAIL
This document provides a lab manual for programming in C language. It contains the syllabus, objectives, outcomes and details of various experiments to be performed in the lab. The syllabus is divided into two parts - the first part covers basic C programming concepts like data types, operators, control structures etc. through 15 experiments. The second part deals with arrays, pointers, structures, files, functions etc. through various other experiments. It also provides information on setting up the programming environment in Linux using GCC compiler or Turbo C/C++ in Windows and the basic structure of a C program. The objectives are to introduce programming fundamentals and impart writing skills in C. The outcomes include understanding programming logic, writing algorithms, using data structures
The document discusses capsule networks, a type of neural network proposed by Geoff Hinton in 2017 as an alternative to convolutional neural networks (CNNs) for computer vision tasks. Capsule networks aim to address some limitations of CNNs, such as their inability to capture spatial relationships and pose information. The key concepts discussed include dynamic routing between capsules, which allows for parts-based representation, and equivariance, where capsules can learn transformation properties like position and orientation. The document provides an overview of a capsule network architecture and routing algorithm proposed in a 2017 paper by Sabour et al.
Cygwin and OpenSSL Installation Guide provides instructions for installing Cygwin and OpenSSL on Windows. It explains what Cygwin and OpenSSL are, how to download and install Cygwin, including selecting necessary packages like gcc and make. It then explains what OpenSSL is and its implemented algorithms and standards. Finally, it outlines the steps to download the OpenSSL source code, compile and install it on Cygwin.
How to operate on tree data structures using multiple parallel threads of execution. Parallel algorithms allows for achieving higher performance on multi-core machines, but getting the correct result from parallel execution can be tricky. This set of slides illustrates a few primary algorithms that operate on tree data structures in parallel.
[SIGGRAPH 2021] Dynamic Closest Color Warping to Sort and Compare PalettesSuzi Kim
A color palette is one of the simplest and most intuitive descriptors that can be extracted from images or videos. This paper proposes a method to assess the similarity between color palettes by sorting colors. While previous palette similarity measures compare only colors without considering the overall palette combination, we sort palettes to minimize the geometric distance between colors and align them to share a common color tendency. We propose dynamic closest color warping (DCCW) to calculate the minimum distance sum between colors and the graph connecting the colors in the other palette. We evaluate the proposed palette sorting and DCCW with several datasets and demonstrate that DCCW outperforms previous methods in terms of accuracy and computing time. We validate the effectiveness of the proposed sorting technique by conducting a perceptual study, which indicates a clear preference for the results of our approach. We also demonstrate useful applications enabled by DCCW, including palette interpolation, palette navigation, and image recoloring.
StyleCLIP: Text-Driven Manipulation of StyleGAN Imagery ivaderivader
The paper presents three methods for text-driven manipulation of StyleGAN imagery using CLIP:
1. Direct optimization of the latent w vector to match a text prompt
2. Training a mapping function to map text to changes in the latent space
3. Finding global directions in the latent space corresponding to attributes by measuring distances between text embeddings
The methods allow editing StyleGAN images based on natural language instructions and demonstrate CLIP's ability to provide fine-grained controls, but rely on pretrained StyleGAN and CLIP models and may struggle with unseen text or image domains.
This document summarizes a presentation about tidy data and how to organize data in a clean, consistent format. It defines what tidy data is, why it is important especially for GIS applications, and tools that can help tidy messy data, including R, Python, Stata, Excel, XML and JSON. It provides advice for both data producers and data users, encouraging producers to provide tidy download options and users to look for tools that simplify working with data.
N Queen Problem using Branch And Bound - GeeksforGeeks.pdfakashreddy966699
The document discusses the N queens puzzle and its solution using the branch and bound algorithm. The N queens puzzle aims to place N chess queens on an N×N chessboard so that no two queens threaten each other. The branch and bound solution avoids exploring paths that cannot lead to a valid solution. Pseudocode and implementations in C++ and Java are provided to demonstrate solving the N queens puzzle using branch and bound.
Bigtable is Google's distributed database system that stores large amounts of structured data across commodity servers. It uses a column-oriented data model with rows identified by keys and columns grouped into column families. Data is stored in immutable files called SSTables across servers, and a master coordinates tablet assignments and recovery when servers fail. Queries can be served efficiently through caching of frequently accessed data blocks and rows.
Design and develop with performance in mind
Establish a tuning environment
Index wisely
Reduce parsing
Take advantage of Cost Based Optimizer
Avoid accidental table scans
Optimize necessary table scans
Optimize joins
Use array processing
Consider PL/SQL for “tricky” SQL
The document discusses B-trees, which are a type of search tree used to organize data files. B-trees allow each node to have many children, with the number limited only by block size. This improves efficiency over 2-3 trees by keeping the search tree short. The key operations of B-trees are retrieval, insertion, and deletion of records. Variations like B*-trees and B+-trees aim to reduce the number of nodes in the tree and improve traversal efficiency.
Network forensics involves collecting and analyzing network data and traffic to determine how attacks occur. It is important to establish standard forensic procedures and know normal network traffic patterns to detect variations. Tools like packet analyzers, Sysinternals, and honeypots can help monitor traffic and identify intrusions. The Honeynet Project aims to increase security awareness by observing new attacker techniques.
Cygwin and OpenSSL Installation Guide provides instructions for installing Cygwin and OpenSSL on Windows. It explains what Cygwin and OpenSSL are, how to download and install Cygwin, including selecting necessary packages like gcc and make. It then explains what OpenSSL is and its implemented algorithms and standards. Finally, it outlines the steps to download the OpenSSL source code, compile and install it on Cygwin.
How to operate on tree data structures using multiple parallel threads of execution. Parallel algorithms allows for achieving higher performance on multi-core machines, but getting the correct result from parallel execution can be tricky. This set of slides illustrates a few primary algorithms that operate on tree data structures in parallel.
[SIGGRAPH 2021] Dynamic Closest Color Warping to Sort and Compare PalettesSuzi Kim
A color palette is one of the simplest and most intuitive descriptors that can be extracted from images or videos. This paper proposes a method to assess the similarity between color palettes by sorting colors. While previous palette similarity measures compare only colors without considering the overall palette combination, we sort palettes to minimize the geometric distance between colors and align them to share a common color tendency. We propose dynamic closest color warping (DCCW) to calculate the minimum distance sum between colors and the graph connecting the colors in the other palette. We evaluate the proposed palette sorting and DCCW with several datasets and demonstrate that DCCW outperforms previous methods in terms of accuracy and computing time. We validate the effectiveness of the proposed sorting technique by conducting a perceptual study, which indicates a clear preference for the results of our approach. We also demonstrate useful applications enabled by DCCW, including palette interpolation, palette navigation, and image recoloring.
StyleCLIP: Text-Driven Manipulation of StyleGAN Imagery ivaderivader
The paper presents three methods for text-driven manipulation of StyleGAN imagery using CLIP:
1. Direct optimization of the latent w vector to match a text prompt
2. Training a mapping function to map text to changes in the latent space
3. Finding global directions in the latent space corresponding to attributes by measuring distances between text embeddings
The methods allow editing StyleGAN images based on natural language instructions and demonstrate CLIP's ability to provide fine-grained controls, but rely on pretrained StyleGAN and CLIP models and may struggle with unseen text or image domains.
This document summarizes a presentation about tidy data and how to organize data in a clean, consistent format. It defines what tidy data is, why it is important especially for GIS applications, and tools that can help tidy messy data, including R, Python, Stata, Excel, XML and JSON. It provides advice for both data producers and data users, encouraging producers to provide tidy download options and users to look for tools that simplify working with data.
N Queen Problem using Branch And Bound - GeeksforGeeks.pdfakashreddy966699
The document discusses the N queens puzzle and its solution using the branch and bound algorithm. The N queens puzzle aims to place N chess queens on an N×N chessboard so that no two queens threaten each other. The branch and bound solution avoids exploring paths that cannot lead to a valid solution. Pseudocode and implementations in C++ and Java are provided to demonstrate solving the N queens puzzle using branch and bound.
Bigtable is Google's distributed database system that stores large amounts of structured data across commodity servers. It uses a column-oriented data model with rows identified by keys and columns grouped into column families. Data is stored in immutable files called SSTables across servers, and a master coordinates tablet assignments and recovery when servers fail. Queries can be served efficiently through caching of frequently accessed data blocks and rows.
Design and develop with performance in mind
Establish a tuning environment
Index wisely
Reduce parsing
Take advantage of Cost Based Optimizer
Avoid accidental table scans
Optimize necessary table scans
Optimize joins
Use array processing
Consider PL/SQL for “tricky” SQL
The document discusses B-trees, which are a type of search tree used to organize data files. B-trees allow each node to have many children, with the number limited only by block size. This improves efficiency over 2-3 trees by keeping the search tree short. The key operations of B-trees are retrieval, insertion, and deletion of records. Variations like B*-trees and B+-trees aim to reduce the number of nodes in the tree and improve traversal efficiency.
Network forensics involves collecting and analyzing network data and traffic to determine how attacks occur. It is important to establish standard forensic procedures and know normal network traffic patterns to detect variations. Tools like packet analyzers, Sysinternals, and honeypots can help monitor traffic and identify intrusions. The Honeynet Project aims to increase security awareness by observing new attacker techniques.
The document describes the TPR*-tree, an optimized index structure for predictive queries on moving objects in spatiotemporal databases. The TPR*-tree improves upon the Time Parameterized R-tree (TPR-tree) by addressing three deficiencies: 1) choosing a better path for insertions, 2) selecting entries that minimize node size for reinsertions, and 3) actively tightening node boundaries during deletions. Experiments showed the TPR*-tree outperformed the TPR-tree in answering predictive queries with fewer disk I/O operations.
B-trees are multiway search trees used to store large datasets on disk. They reduce the height of the tree compared to binary trees, lowering the number of disk accesses needed for operations like search. A B-tree of order m has internal nodes with up to m children, keeps the leaves at the same level, and remains balanced during insertions and deletions which may involve splitting and merging nodes as well as promoting keys. B-trees are efficient for disk-based data structures due to their ability to group adjacent records into each node transfer.
Hiload: проблемы и решения. Что нужно знать, начиная проект?
Ваш стартап "взлетел"? Посещаемость сайта растет? Вы уверены, что под напором клиентов сервер не "ляжет"? Грамотное проектирование архитектуры информационной системы позволит избежать чрезмерных затрат на масштабирование и не потерять клиентов.
This document provides an overview of floorplanning in chip design. Floorplanning involves block placement, pin assignment, design partitioning, and other tasks. It aims to optimize chip area, wirelength, timing, and routability. Representations like sequence pairs and algorithms like simulated annealing are used. Floorplanning is important for estimating metrics early in design and improving subsequent steps like routing. It can eliminate guesswork and risks from hierarchical flows.
This document discusses floorplanning, which is an important first step in physical design. There are two main approaches to floorplanning: simulated annealing and analytical formulation. Popular representations of geometric relationships used in floorplanning are normalized Polish expression, B*-tree, and sequence pair. The goal of floorplanning is to optimize metrics like area and wire length. Slicing floorplans can be represented by binary trees, while non-slicing floorplans use constraint graphs.
Доклад с PUG#4 https://www.facebook.com/events/350783888446030/
Рассмотрим:
- Что такое Highload, термины, инструменты.
- Где тормозит PHP, родовые травмы языка, как с ними жить.
- Скорость работы vs скорость разработки.
- Архитектура, что стоит делать и когда.
1. Лекция 5:
B-деревья (B-trees)
Курносов Михаил Георгиевич
к.т.н. доцент Кафедры вычислительных систем
Сибирский государственный университет
телекоммуникаций и информатики
http://www.mkurnosov.net
2. Организация дисковой памяти
2
Жёсткий диск (hard disk drive, HDD) –
это совокупность пластин (platters), которые хранят данные
в концентрических окружностях – дорожках (tracks)
Данные считываются/записываются головками (heads)
Пластины и головки приводятся в движение двигателями
Сектор (Sector) – часть дорожки (минимально адресуемая
единица жесткого диска)
Кластер (Cluster) – это совокупность секторов дорожки
Цилиндр (Cylinder) – множество дорожек, размещенных
на одном и том же месте нескольких пластин
3. Организация дисковой памяти
3
Время доступа к сектору (seek time) зависит от скорости
вращения пластин
Количество вращений в минуту
(Revolutions per minute, RPM)
Время доступа
(Rotational latency)
5400 rpm 0.011 сек.
7200 rpm 0.008 сек.
15 000 rpm 0.004 сек.
Время доступа к оперативной памяти (≈ 10 нс) в 105 раз меньше
времени доступа к диску
4. Твердотельные накопители (SSD)
4
Твердотельный накопитель
(Solid state drive, flash drive, SSD) –
это немеханическое запоминающее
устройство на основе микросхем памяти
Время поиска блока на SSD (seek time) ≈ 0 сек
5. Организация дисковой памяти
5
Для сокращения времени работы с диском данные читают
и записывают блоками – буферизованный ввод/вывод
В алгоритмах для внешней памяти необходимо учитывать
количество обращений к диску
6. Структуры данных для внешней памяти
6
Имеется бинарное дерево поиска (binary search tree),
в котором каждый узел содержит:
ключ (key) – строка из 32 символов (char[32], 32 байта)
значение (value) – целое число (int, 4 байта)
указатели left и right (по 8 байт)
Имеется сервер с 16 GiB оперативной памяти
Сколько узлов дерева поместится в оперативную память?
7. Структуры данных для внешней памяти
7
Имеется бинарное дерево поиска (binary search tree),
в котором каждый узел содержит:
ключ (key) – строка из 32 символов (char[32], 32 байта)
значение (value) – целое число (int, 4 байта)
указатели left и right (по 8 байт)
Имеется сервер с 16 GiB оперативной памяти
Сколько узлов дерева поместится в оперативную память?
Узел дерева занимает 32 + 4 + 8 + 8 = 52 байта
Пусть нам доступны все 16 GiB (оценка сверху):
16 * 2^30 / 52 ≈ 330 382 099 узлов
8. Структуры данных для внешней памяти
8
Как хранить словарь из 1 000 000 000 записей?
Количество пользователей Facebook (июль 2013):
1 200 000 000
Количество пользователей Google Gmail (июнь 2012):
425 000 000
Количсество пользователей ВКонтакте (февраль 2013):
43 000 000
Решение: использовать внешнюю память –
HDD/SSD-диски, сетевые хранилища
9. B-дерево (B-tree)
9
B-дерево (B-tree) – это сбалансированное дерево поиска,
узлы которого хранятся во внешней памяти (например,
на диске HDD/SSD)
В любой момент времени в оперативной памяти
находится лишь часть B-дерева (размер дерева может
значительно превышать объем оперативной памяти)
B-деревья используются в файловых системах и системах
управления базами данных (СУБД)
Авторы Rudolf Bayer и Edward M. McCreight
Boeing Research Labs, USA, 1971
Буква “В” в названии B-деревьев: Boeing, Bayer, …
Bayer R., McCreight E. Organization and Maintenance of Large Ordered Indices //
Math. and Information Sciences Report (Boeing Research Labs). – 1970, No. 20.
Bayer R. Binary B-Trees for Virtual Memory // Workshop on Data Description, Access
and Control, 1971.
10. B-дерево (B-tree)
10
Высота B-дерева не превышает O(logn), где n – количество
узлов в дереве
Узлы B-дерева могут иметь много дочерних узлов –
до тысяч (сильно ветвящиеся деревья)
Каждый узел B-дерева может содержать больше 1 ключа
Если внутренний узел содержит k ключей, то у него k + 1
дочерних узлов
Один ключ
Два ключаДва ключа
12. B-дерево (B-tree)
12
B-дерево (B-tree) – это корневое дерево, обладающее
следующими свойствами:
1) Каждый узел содержит поля:
− количество n ключей, хранящихся в узле
− ключи key1, key2, …, keyn, упорядоченные по
не убыванию key1 ≤ key2 ≤ … ≤ keyn
− флаг leaf, равный true, если узел является листом
− внутренний узел содержит n + 1 указателей c1, c2, …, cn+1
на дочерние узлы (листья не имеют дочерних узлов)
13. B-дерево (B-tree)
13
B-дерево (B-tree) – это корневое дерево, обладающее
следующими свойствами:
2) Ключи разделяют диапазоны ключей, хранящихся
в поддеревьях:
если ki – произвольный ключ в поддереве ci, то
k1 ≤ key1 ≤ k2 ≤ key2 ≤ … ≤ keyn ≤ kn+1
3) Все листья расположены на одинаковой глубине,
равной высоте h дерева
14. B-дерево (B-tree)
14
B-дерево (B-tree) – это корневое дерево, обладающее
следующими свойствами:
4) Имеются нижняя и верхняя границы
количества ключей, хранящихся в узле –
минимальная степень t (minimum degree) B-дерева
− корневой узел содержит от 1 до 2t – 1 ключей
− каждый внутренний узел содержит минимум t – 1
ключей и минимум t дочерних узлов
− каждый узел содержит максимум 2t – 1 ключей и
максимум 2t дочерних узлов (за исключением листьев)
− узел заполнен (full), если он содержит 2t – 1 ключей
15. …
B-дерево (B-tree)
15
root
…t – 1 t – 1
t – 1
…
…t – 1 t – 1
t – 1
…
t – 1
…
…t – 1 t – 1
t – 1
…
…t – 1 t – 1
t – 1
…
t – 1
1Уровень: # узлов 0: 1
1: 2
2: 2t
3: 2t2
17. Высота B-дерева
17
Утверждение. Высота B-дерева с n ≥ 1 ключами
и минимальной степенью t ≥ 2 в худшем случае
не превышает logt((n + 1) / 2)
Доказательство. Обозначим высоту B-дерева через h.
Рассмотрим максимально высокое B-дерево:
в корне такого дерева хранится 1 ключ, а в остальных
узлах по t – 1 ключу (минимально возможное количество)
На уровне 0 размещен один узел (корень) с 1 ключом
На уровне 1: 2 узла (у каждого по t – 1 ключу)
На уровне 2: 2t узлов
На уровне 3: 2t2 узлов
…
На уровне h: 2th-1 узлов
18. Высота B-дерева
18
Утверждение. Высота B-дерева с n ≥ 1 ключами
и минимальной степенью t ≥ 2 в худшем случае
не превышает logt((n + 1) / 2)
Доказательство.
Тогда, общее количество ключей есть
𝑛 = 1 + 𝑡 − 1 2 + 2𝑡 + 2𝑡2
+ 2𝑡3
+ ⋯ + 2𝑡ℎ−1
=
= 1 + 2 𝑡 − 1 1 + 𝑡 + 𝑡2 + ⋯ + 𝑡ℎ−1
Сумма h первых членов геометрической прогрессии
𝑆ℎ =
𝑏1(𝑞ℎ − 1)
𝑞 − 1
19. Высота B-дерева
19
Утверждение. Высота B-дерева с n ≥ 1 ключами
и минимальной степенью t ≥ 2 в худшем случае
не превышает logt((n + 1) / 2)
Доказательство.
Следовательно,
𝑛 = 1 + 2 𝑡 − 1
𝑡ℎ
− 1
𝑡 − 1
= 2𝑡ℎ
− 1
𝑛 + 1
2
= 𝑡ℎ
𝒉 = 𝐥𝐨𝐠 𝒕
𝒏 + 𝟏
𝟐
Утверждение доказано.
20. Операции с B-деревьями
20
Во всех операциях предполагаем следующее:
o корень B-дерева всегда находится в оперативной
памяти
o для чтения и записи данных на диск используются
процедуры DiskRead и DiskWrite
Б-дерево минимизирует количество обращений к внешней
памяти (к DiskRead, DiskWrite)
21. Поиск элемента (Lookup)
21
1) Поиск начинаем с корня дерева. Для заданного ключа k
среди ключей текущего узла
key1 ≤ key2 ≤ … ≤ keyn
отыскиваем первый ключ keyi, такой что k ≤ keyi
2) Если k = keyi, то прекращаем поиск (узел найден)
3) Иначе, загружаем с диска (DiskRead) дочерний узел ci
и рекурсивного обследуем его ключи
4) Если достигли листа (leaf = true), завершаем работу
(ключ не найден)
22. Поиск элемента (Lookup)
22
function BTreeLookup(node, key)
i = 1
while i < n AND key > node.key[i] do
i = i + 1
end while
if i <= n AND key = node.key[i] then
return (node, i)
if node.leaf != TRUE then
child = DiskRead(node.c[i])
return BTreeLookup(child, key)
end if
return NULL
end function
23. Поиск элемента (Lookup)
23
function BTreeLookup(node, key)
i = 1
while i < n AND key > node.key[i] do
i = i + 1
end while
if i <= n AND key = node.key[i] then
return (node, i)
if node.leaf != TRUE then
child = DiskRead(node.c[i])
return BTreeLookup(child, key)
end if
return NULL
end function
O(t)
Количество чтений с диска: 𝑇𝑅𝑒𝑎𝑑 = 𝑂 ℎ = 𝑂(log 𝑡 𝑛)
Вычислительная сложность: 𝑇 = 𝑂 𝑡ℎ = 𝑂(𝑡 log 𝑡 𝑛)
24. Поиск элемента (Lookup)
24
function BTreeLookup(node, key)
i = 1
while i < n AND key > node.key[i] do
i = i + 1
end while
if i <= n AND key = node.key[i] then
return (node, i)
if node.leaf != TRUE then
child = DiskRead(node.c[i])
return BTreeLookup(child, key)
end if
return NULL
end function
O(t)
Количество чтений с диска: 𝑇𝑅𝑒𝑎𝑑 = 𝑂 ℎ = 𝑂(log 𝑡 𝑛)
Вычислительная сложность: 𝑇 = 𝑂 𝑡ℎ = 𝑂(𝑡 log 𝑡 𝑛)
Как ускорить поиск ключа в узле?
25. Поиск элемента (Lookup)
25
function BTreeLookup(node, key)
i = 1
while i < n AND key > node.key[i] do
i = i + 1
end while
if i <= n AND key = node.key[i] then
return (node, i)
if node.leaf != TRUE then
child = DiskRead(node.c[i])
return BTreeLookup(child, key)
end if
return NULL
end function
O(t)
Количество чтений с диска: 𝑇𝑅𝑒𝑎𝑑 = 𝑂 ℎ = 𝑂(log 𝑡 𝑛)
Вычислительная сложность: 𝑇 = 𝑂 𝑡ℎ = 𝑂(𝑡 log 𝑡 𝑛)
Как ускорить поиск ключа в узле?
Двоичный поиск (Binary search) за время O(log2t)
T = O(log2t ∙ logtn)
26. Создание пустого B-дерева (Create)
26
function BTreeCreate()
node = DiskAllocateNode()
node.leaf = TRUE
node.n = 0
DiskWrite(node)
end function
Количество дисковых операций: 𝑇 𝐷𝑖𝑠𝑘 = 𝑂 1
Вычислительная сложность: 𝑇 = 𝑂 1
1) Выделить на диске место для корневого узла
2) Заполнить поля корневого узла
27. Добавление ключа (Insert)
27
1) Для заданного ключа key находим лист для вставки
нового элемента
2) Если лист не заполнен (ключей меньше или равно 2t – 1),
то вставляем ключ в узел (сохраняя упорядоченность
ключей)
2 4
31 5
B-дерево
Вставка ключа 6
28. Добавление ключа (Insert)
28
3) Если лист заполнен (содержит 2t – 1 ключей), то
разбиваем его (split) на 2 листа по t – 1 ключей –
среди ключей листа key1 ≤ key2 ≤ … ≤ keyn и ключа key
отыскиваем медиану (median key) – средний ключ
разделитель
4) Ключ медиана вставляется в родительский узел.
Если родительский узел заполнен, то он разбивается и
процедура повторяется по описанной выше схеме.
Подъем вверх по дереву может продолжаться до корня
30. Добавление ключа (Insert)
30
При проходе от корня дерева к искомому листу
разбиваем (split) все заполненные узлы, через которые
проходим (включая лист).
Это гарантирует, что если понадобится разбить узел,
то его родительский узел не будет заполнен
31. Разбиение узла (Split)
31
function BTreeSplitNode(node, parent, i)
z = DiskAllocateNode()
z.leaf = node.leaf
z.n = t – 1
/* Половина ключей перемещаются в новый узел */
for j = 1 to t – 1 do
z.key[j] = node.key[t + j]
end for
if node.leaf = FALSE then
for j = 1 to t do
z.c[j] = node.c[t + j]
end for
end if
32. Разбиение узла (Split)
/* В node остается меньшая половина ключей */
node.n = t – 1
/* Вставляем ключ в родительский узел */
for j = parent.n + 1 downto i + 1 do
parent.c[j + 1] = parent.c[j]
end for
parent.c[i + 1] = z
for j = parent.n downto i do
parent.key[j + 1] = parent.key[j]
end for
parent.key[i] = node.key[t]
parent.n = parent.n + 1
DiskWrite(node)
DiskWrite(z)
DiskWrite(parent)
end function
32
TSplitNode = O(t)
TDisk = O(1)
33. Добавление ключа (Insert)
33
function BTreeInsert(root, key)
if root.n = 2t – 1 then
newroot = DiskAllocateNode()
newroot.leaf = FALSE
newroot.n = 0
newroot.c[1] = root
BTreeSplitNode(root, newroot, 1)
return BTreeInsertNonfull(newroot, key)
end if
return BTreeInsertNonfull(root, key)
end function
34. Добавление ключа (Insert)
function BTreeInsertNonfull(node, key)
i = node.n
if node.leaf = TRUE then
while i > 1 AND key < node.key[i] do
node.key[i + 1] = node.key[i]
i = i - 1
end while
node.key[i + 1] = key
node.n = node.n + 1
DiskWrite(node)
else
while i > 1 AND key < node.key[i] do
i = i - 1
end while
i = i + 1
DiskRead(node.c[i])
34
35. Добавление ключа (Insert)
35
if node.c[i].n = 2t – 1 then
BTreeSplitNode(node.c[i], node, i)
if key > node.key[i] then
i = i + 1
end if
end if
node = BTreeInsertNonfull(node.c[i], key)
end if
return node
end function
Вычислительная сложность вставки ключа в B-дерево
в худшем случае (разбиваем узлы на каждом уровне):
𝑇 = 𝑂 𝑡ℎ = 𝑂(𝑡 log 𝑡 𝑛)
Количество дисковых операций:
𝑇 𝐷𝑖𝑠𝑘 = 𝑂 ℎ = 𝑂(log 𝑡 𝑛)
36. Удаление ключа (Delete)
36
Находим узел, содержащий искомый ключ key
Если ключ key находится в листе, то удаляем ключ из него
Если количество ключей стало меньше t – 1, выполняем
восстановление свойств B-дерева
…
Изучить самостоятельно [CLRS, С. 530]
37. Виды B-деревьев
37
B+-дерево (B+-tree) – это B-дерево, в котором только листья
содержат информацию, а внутренние узлы хранят только
ключи
Примнение: храннеие
B*-дерево (B*-tree) – это B-дерево, в котором каждый узел
(за исключением корня) должен содержать не менее 2/3
ключей, а не 1/2 как в B-дереве
38. Применение B-деревьев
38
B+-деревья:
o индексация метаданных в файловых системах
NTFS, ReiserFS, NSS, XFS, JFS
o индексы таблиц в СУБД IBM DB2, Informix, Microsoft
SQL Server, Oracle 8, Sybase ASE, SQLite
39. Реализация 2-3-4 B-tree
39
/* Minimum degree of B-tree */
#define T 2 /* 2-3-4 B-tree */
struct btree {
int leaf;
int nkeys;
int *key;
int *value;
struct btree **child;
};
43. Реализация B-tree
void btree_split_node(struct btree *node,
struct btree *parent, int index)
{
struct btree *z;
int i;
z = btree_create();
z->leaf = node->leaf;
z->nkeys = T - 1;
for (i = 0; i < T - 1; i++) {
z->key[i] = node->key[T + i];
z->value[i] = node->value[T + i];
}
if (!node->leaf) {
for (i = 0; i < T; i++)
z->child[i] = node->child[i + T];
}
node->nkeys = T - 1;
43
44. Реализация B-tree
/* Insert median key into parent node */
for (i = parent->nkeys; i >= 0 && i <= index + 1; i--)
parent->child[i + 1] = parent->child[i];
parent->child[index + 1] = z;
for (i = parent->nkeys - 1; i >= 0 && i <= index; i--) {
parent->key[i + 1] = parent->key[i];
parent->value[i + 1] = parent->value[i];
}
parent->key[index] = node->key[T - 1];
parent->value[index] = node->value[T - 1];
parent->nkeys++;
/* Write to disk: node, z, parent */
}
44
45. Реализация B-tree
struct btree *btree_insert_nonfull(
struct btree *node, int key, int value)
{
int i;
i = node->nkeys;
if (node->leaf) {
for (i = node->nkeys - 1; i > 0 &&
key < node->key[i]; i--)
{
node->key[i + 1] = node->key[i];
}
node->key[i + 1] = key;
node->nkeys++;
} else {
45
46. Реализация B-tree
for (i = node->nkeys - 1; i > 0 &&
key < node->key[i]; )
{
i--;
}
i++;
if (node->child[i]->nkeys == 2 * T - 1) {
btree_split_node(node->child[i], node, i);
if (key > node->key[i])
i++;
}
node = btree_insert_nonfull(node->child[i],
key, value);
}
return node;
}
46
47. Реализация B-tree
int main()
{
struct btree *tree;
tree = btree_insert(NULL, 3, 0);
tree = btree_insert(tree, 12, 0);
tree = btree_insert(tree, 9, 0);
tree = btree_insert(tree, 18, 0);
return 0;
}
47
48. Внешняя сортировка слиянием
48
Внешняя сортировка (External sorting) – это класс алгоритмов
сортировки, которые оперируют данными размещенными на внешней
памяти
Как отсортировать 300 GiB данных на жестком диске
имея 2 GiB оперативной памяти?
49. Внешняя сортировка слиянием
49
Внешняя сортировка (External sorting) – это класс алгоритмов
сортировки, которые оперируют данными размещенными на внешней
памяти
Как отсортировать 300 GiB данных на жестком диске
имея 2 GiB оперативной памяти?
1. Загружаем блок размером 2 GiB в оперативную память
2. Сортируем блок (MergeSort, QuickSort, CountingSort, …) и сохраняем
на нешнюю память (диск)
3. Повторяем шаги 1 и 2, пока на получим 300 / 2 = 150 отсортированных
блоков на внешней памяти
4. Создаем в оперативной памяти 151 буфер по 13 KiB (2 GiB / 151 ≈ 13 KiB)
5. Загружаем в 150 буферов по 13 KiB из отсортированных блоков, 151-й
буфер – это выходной блок
6. В выходной блок сливаем (merge) данные из 150 буферов и записываем
его на внешнюю память
7. Повторяем шаги 5 и 6 пока не сольем все 150 блоков
50. Внешняя сортировка слиянием
50
Внешняя сортировка (External sorting) – это класс алгоритмов
сортировки, которые оперируют данными размещенными на внешней
памяти
Как отсортировать 300 GiB данных на жестком диске
имея 2 GiB оперативной памяти?
1. Загружаем блок размером 2 GiB в оперативную память
2. Сортируем блок (MergeSort, QuickSort, CountingSort, …) и сохраняем
на нешнюю память (диск)
3. Повторяем шаги 1 и 2, пока на получим 300 / 2 = 150 отсортированных
блоков на внешней памяти
4. Создаем в оперативной памяти 151 буфер по 13 KiB (2 GiB / 151 ≈ 13 KiB)
5. Загружаем в 150 буферов по 13 KiB из отсортированных блоков, 151-й
буфер – это выходной блок
6. В выходной блок сливаем (merge) данные из 150 буферов и записываем
его на внешнюю память
7. Повторяем шаги 5 и 6 пока не сольем все 150 блоков
k-way merge sort
k = 300 GiB / 2 GiB = 150
150-way merge sort
51. Задания
51
Рассмотреть применение B-деревьев в файловых
системах – что содержит поле “ключ” (key)
и поле “значение” (value)
Привести пример значения t, используемого в файловой
системе Btrfs
Изучить применение B-деревьев в системах управления
базами данных (MySQL, PostgreSQL, Microsoft SQL Server,
IBM DB2 и др.): какие задачи они решают, что хранится
в поле “ключ” (key) и поле “значение” (value)