Skip to content
GitLab
Explore
Sign in
Primary navigation
Search or go to…
Project
C
Curio
Manage
Activity
Members
Labels
Plan
Issues
Issue boards
Milestones
Wiki
Code
Merge requests
Repository
Branches
Commits
Tags
Repository graph
Compare revisions
Snippets
Build
Pipelines
Jobs
Pipeline schedules
Artifacts
Deploy
Releases
Package registry
Container Registry
Model registry
Operate
Environments
Terraform modules
Monitor
Incidents
Analyze
Value stream analytics
Contributor analytics
CI/CD analytics
Repository analytics
Model experiments
Help
Help
Support
GitLab documentation
Compare GitLab plans
Community forum
Contribute to GitLab
Provide feedback
Keyboard shortcuts
?
Snippets
Groups
Projects
Show more breadcrumbs
Jim Wallace
Curio
Merge requests
!5
Allminilm
Code
Review changes
Check out branch
Download
Patches
Plain diff
Merged
Allminilm
AllMiniLM
into
main
Overview
0
Commits
7
Pipelines
1
Changes
1
Merged
Henry Tian
requested to merge
AllMiniLM
into
main
1 year ago
Overview
0
Commits
7
Pipelines
1
Changes
1
Expand
0
0
Merge request reports
Viewing commit
91a131bb
Prev
Next
Show latest version
1 file
+
55
−
0
Inline
Compare changes
Side-by-side
Inline
Show whitespace changes
Show one file at a time
91a131bb
Upload New File
· 91a131bb
Henry Tian
authored
1 year ago
Sources/SwiftNLP/2. Embeddings/MiniLMAllEmbeddings.swift
0 → 100644
+
55
−
0
Options
import
Foundation
import
CoreML
@available
(
macOS
12.0
,
iOS
15.0
,
*
)
public
class
MiniLMEmbeddings
{
public
let
model
:
all_MiniLM_L6_v2
public
let
tokenizer
:
BertTokenizer
public
let
inputDimention
:
Int
=
512
public
let
outputDimention
:
Int
=
384
public
init
()
{
let
modelConfig
=
MLModelConfiguration
()
modelConfig
.
computeUnits
=
.
all
do
{
self
.
model
=
try
all_MiniLM_L6_v2
(
configuration
:
modelConfig
)
}
catch
{
fatalError
(
"Failed to load the Core ML model. Error:
\(
error
.
localizedDescription
)
"
)
}
self
.
tokenizer
=
BertTokenizer
()
}
// MARK: - Dense Embeddings
public
func
encode
(
sentence
:
String
)
async
->
[
Float
]?
{
// Encode input text as bert tokens
let
inputTokens
=
tokenizer
.
buildModelTokens
(
sentence
:
sentence
)
let
(
inputIds
,
attentionMask
)
=
tokenizer
.
buildModelInputs
(
from
:
inputTokens
)
// Send tokens through the MLModel
let
embeddings
=
generateEmbeddings
(
inputIds
:
inputIds
,
attentionMask
:
attentionMask
)
return
embeddings
}
public
func
generateEmbeddings
(
inputIds
:
MLMultiArray
,
attentionMask
:
MLMultiArray
)
->
[
Float
]?
{
let
inputFeatures
=
all_MiniLM_L6_v2Input
(
input_ids
:
inputIds
,
attention_mask
:
attentionMask
)
let
output
=
try
?
model
.
prediction
(
input
:
inputFeatures
)
guard
let
embeddings
=
output
?
.
embeddings
else
{
return
nil
}
var
embeddingsArray
=
[
Float
]()
for
index
in
0
..<
embeddings
.
count
{
let
value
=
embeddings
[
index
]
.
floatValue
embeddingsArray
.
append
(
Float
(
value
))
}
return
embeddingsArray
}
}
Loading