-
Notifications
You must be signed in to change notification settings - Fork 676
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[huggingface] Adds Huggingface ModelZoo #1984
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
136 changes: 136 additions & 0 deletions
136
extensions/tokenizers/src/main/java/ai/djl/huggingface/zoo/HfModelZoo.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,136 @@ | ||
/* | ||
* Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance | ||
* with the License. A copy of the License is located at | ||
* | ||
* http://aws.amazon.com/apache2.0/ | ||
* | ||
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES | ||
* OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions | ||
* and limitations under the License. | ||
*/ | ||
package ai.djl.huggingface.zoo; | ||
|
||
import ai.djl.Application; | ||
import ai.djl.Application.NLP; | ||
import ai.djl.engine.Engine; | ||
import ai.djl.repository.Repository; | ||
import ai.djl.repository.Version; | ||
import ai.djl.repository.VersionRange; | ||
import ai.djl.repository.zoo.ModelZoo; | ||
import ai.djl.util.JsonUtils; | ||
import ai.djl.util.Utils; | ||
|
||
import com.google.gson.reflect.TypeToken; | ||
|
||
import org.slf4j.Logger; | ||
import org.slf4j.LoggerFactory; | ||
|
||
import java.io.IOException; | ||
import java.io.Reader; | ||
import java.io.Writer; | ||
import java.lang.reflect.Type; | ||
import java.net.URL; | ||
import java.nio.file.Files; | ||
import java.nio.file.Path; | ||
import java.time.Duration; | ||
import java.util.Collections; | ||
import java.util.Map; | ||
import java.util.Set; | ||
import java.util.zip.GZIPInputStream; | ||
|
||
/** HfModelZoo is a repository that contains HuggingFace models. */ | ||
public class HfModelZoo extends ModelZoo { | ||
|
||
private static final Logger logger = LoggerFactory.getLogger(HfModelZoo.class); | ||
|
||
private static final String REPO = "https://mlrepo.djl.ai/"; | ||
private static final Repository REPOSITORY = Repository.newInstance("Huggingface", REPO); | ||
private static final String GROUP_ID = "ai.djl.huggingface.pytorch"; | ||
|
||
private static final long ONE_DAY = Duration.ofDays(1).toMillis(); | ||
|
||
HfModelZoo() { | ||
Version version = new Version(Engine.class.getPackage().getSpecificationVersion()); | ||
addModels(NLP.FILL_MASK, version); | ||
addModels(NLP.QUESTION_ANSWER, version); | ||
addModels(NLP.TEXT_CLASSIFICATION, version); | ||
addModels(NLP.TEXT_EMBEDDING, version); | ||
addModels(NLP.TOKEN_CLASSIFICATION, version); | ||
} | ||
|
||
/** {@inheritDoc} */ | ||
@Override | ||
public String getGroupId() { | ||
return GROUP_ID; | ||
} | ||
|
||
/** {@inheritDoc} */ | ||
@Override | ||
public Set<String> getSupportedEngines() { | ||
return Collections.singleton("PyTorch"); | ||
} | ||
|
||
private void addModels(Application app, Version version) { | ||
Map<String, Map<String, Object>> map = listModels(app); | ||
for (Map.Entry<String, Map<String, Object>> entry : map.entrySet()) { | ||
Map<String, Object> model = entry.getValue(); | ||
if ("failed".equals(model.get("result"))) { | ||
continue; | ||
} | ||
String requires = (String) model.get("requires"); | ||
if (requires != null) { | ||
// the model requires specific DJL version | ||
VersionRange range = VersionRange.parse(requires); | ||
if (!range.contains(version)) { | ||
continue; | ||
} | ||
} | ||
String artifactId = entry.getKey(); | ||
addModel(REPOSITORY.model(app, GROUP_ID, artifactId, "0.0.1")); | ||
} | ||
} | ||
|
||
private Map<String, Map<String, Object>> listModels(Application app) { | ||
try { | ||
String path = "model/" + app.getPath() + "/ai/djl/huggingface/pytorch/"; | ||
Path dir = Utils.getCacheDir().resolve("cache/repo/" + path); | ||
if (Files.notExists(dir)) { | ||
Files.createDirectories(dir); | ||
} else if (!Files.isDirectory(dir)) { | ||
logger.warn("Failed initialize cache directory: " + dir); | ||
return Collections.emptyMap(); | ||
} | ||
Type type = new TypeToken<Map<String, Map<String, Object>>>() {}.getType(); | ||
|
||
Path file = dir.resolve("models.json"); | ||
if (Files.exists(file)) { | ||
long lastModified = Files.getLastModifiedTime(file).toMillis(); | ||
if (Boolean.getBoolean("offline") | ||
|| System.currentTimeMillis() - lastModified < ONE_DAY) { | ||
try (Reader reader = Files.newBufferedReader(file)) { | ||
return JsonUtils.GSON.fromJson(reader, type); | ||
} | ||
} | ||
} | ||
|
||
String url = REPO + path + "models.json.gz"; | ||
Path tmp = Files.createTempFile(dir, "models", ".tmp"); | ||
try (GZIPInputStream gis = new GZIPInputStream(new URL(url).openStream())) { | ||
String json = Utils.toString(gis); | ||
try (Writer writer = Files.newBufferedWriter(tmp)) { | ||
writer.write(json); | ||
} | ||
Utils.moveQuietly(tmp, file); | ||
return JsonUtils.GSON.fromJson(json, type); | ||
} finally { | ||
Utils.deleteQuietly(tmp); | ||
} | ||
} catch (IOException e) { | ||
logger.warn("Failed load index of models: " + app, e); | ||
} | ||
|
||
return Collections.emptyMap(); | ||
} | ||
} |
29 changes: 29 additions & 0 deletions
29
extensions/tokenizers/src/main/java/ai/djl/huggingface/zoo/HfZooProvider.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
/* | ||
* Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance | ||
* with the License. A copy of the License is located at | ||
* | ||
* http://aws.amazon.com/apache2.0/ | ||
* | ||
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES | ||
* OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions | ||
* and limitations under the License. | ||
*/ | ||
package ai.djl.huggingface.zoo; | ||
|
||
import ai.djl.repository.zoo.ModelZoo; | ||
import ai.djl.repository.zoo.ZooProvider; | ||
|
||
/** | ||
* An Huggingface model zoo provider implements the {@link ai.djl.repository.zoo.ZooProvider} | ||
* interface. | ||
*/ | ||
public class HfZooProvider implements ZooProvider { | ||
|
||
/** {@inheritDoc} */ | ||
@Override | ||
public ModelZoo getModelZoo() { | ||
return new HfModelZoo(); | ||
} | ||
} |
14 changes: 14 additions & 0 deletions
14
extensions/tokenizers/src/main/java/ai/djl/huggingface/zoo/package-info.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
/* | ||
* Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance | ||
* with the License. A copy of the License is located at | ||
* | ||
* http://aws.amazon.com/apache2.0/ | ||
* | ||
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES | ||
* OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions | ||
* and limitations under the License. | ||
*/ | ||
/** Contains the built-in {@link ai.djl.huggingface.zoo.HfModelZoo}. */ | ||
package ai.djl.huggingface.zoo; |
Empty file.
1 change: 1 addition & 0 deletions
1
extensions/tokenizers/src/main/resources/META-INF/services/ai.djl.repository.zoo.ZooProvider
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
ai.djl.huggingface.zoo.HfZooProvider |
92 changes: 92 additions & 0 deletions
92
extensions/tokenizers/src/test/java/ai/djl/huggingface/zoo/ModelZooTest.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,92 @@ | ||
/* | ||
* Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance | ||
* with the License. A copy of the License is located at | ||
* | ||
* http://aws.amazon.com/apache2.0/ | ||
* | ||
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES | ||
* OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions | ||
* and limitations under the License. | ||
*/ | ||
package ai.djl.huggingface.zoo; | ||
|
||
import ai.djl.Application.NLP; | ||
import ai.djl.ModelException; | ||
import ai.djl.inference.Predictor; | ||
import ai.djl.modality.nlp.qa.QAInput; | ||
import ai.djl.repository.zoo.Criteria; | ||
import ai.djl.repository.zoo.ZooModel; | ||
import ai.djl.testing.TestRequirements; | ||
import ai.djl.translate.TranslateException; | ||
import ai.djl.util.JsonUtils; | ||
import ai.djl.util.Utils; | ||
|
||
import org.testng.Assert; | ||
import org.testng.annotations.Test; | ||
|
||
import java.io.IOException; | ||
import java.io.Writer; | ||
import java.nio.file.Files; | ||
import java.nio.file.Path; | ||
import java.util.Map; | ||
import java.util.concurrent.ConcurrentHashMap; | ||
|
||
public class ModelZooTest { | ||
|
||
@Test | ||
public void testModelZoo() throws ModelException, IOException, TranslateException { | ||
TestRequirements.nightly(); | ||
|
||
String question = "When did BBC Japan start broadcasting?"; | ||
String paragraph = | ||
"BBC Japan was a general entertainment Channel. " | ||
+ "Which operated between December 2004 and April 2006. " | ||
+ "It ceased operations after its Japanese distributor folded."; | ||
|
||
String url = "djl://ai.djl.huggingface.pytorch/deepset/minilm-uncased-squad2"; | ||
Criteria<QAInput, String> criteria = | ||
Criteria.builder().setTypes(QAInput.class, String.class).optModelUrls(url).build(); | ||
|
||
try (ZooModel<QAInput, String> model = criteria.loadModel(); | ||
Predictor<QAInput, String> predictor = model.newPredictor()) { | ||
QAInput input = new QAInput(question, paragraph); | ||
String res = predictor.predict(input); | ||
Assert.assertEquals(res, "december 2004"); | ||
} | ||
} | ||
|
||
@Test | ||
public void testFutureVersion() throws IOException { | ||
Map<String, Map<String, Object>> map = new ConcurrentHashMap<>(); | ||
Map<String, Object> model = new ConcurrentHashMap<>(); | ||
model.put("result", "failed"); | ||
map.put("model1", model); | ||
|
||
model = new ConcurrentHashMap<>(); | ||
model.put("requires", "10.100.0+"); | ||
map.put("model2", model); | ||
|
||
model = new ConcurrentHashMap<>(); | ||
model.put("requires", "0.19.0+"); | ||
map.put("model3", model); | ||
map.put("model4", new ConcurrentHashMap<>()); | ||
|
||
String path = "model/" + NLP.QUESTION_ANSWER.getPath() + "/ai/djl/huggingface/pytorch/"; | ||
Path dir = Utils.getCacheDir().resolve("cache/repo/" + path); | ||
Files.createDirectories(dir); | ||
Path file = dir.resolve("models.json"); | ||
try (Writer writer = Files.newBufferedWriter(file)) { | ||
writer.write(JsonUtils.GSON_PRETTY.toJson(map)); | ||
} | ||
HfModelZoo zoo = new HfModelZoo(); | ||
|
||
Assert.assertNull(zoo.getModelLoader("model1")); | ||
Assert.assertNull(zoo.getModelLoader("model2")); | ||
Assert.assertNull(zoo.getModelLoader("model3")); | ||
Assert.assertNotNull(zoo.getModelLoader("model4")); | ||
|
||
Utils.deleteQuietly(file); | ||
} | ||
} |
13 changes: 13 additions & 0 deletions
13
extensions/tokenizers/src/test/java/ai/djl/huggingface/zoo/package-info.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
/* | ||
* Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance | ||
* with the License. A copy of the License is located at | ||
* | ||
* http://aws.amazon.com/apache2.0/ | ||
* | ||
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES | ||
* OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions | ||
* and limitations under the License. | ||
*/ | ||
package ai.djl.huggingface.zoo; |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think we may want a models.json for every DJL release version. Otherwise, we may be suggested new models that are not supported for older versions of DJL
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Currently
models.json
is per application, assume the same application will use the same Translator. So we don't really need each file per version. The risk would be some model may require enhancement in current Translator. What we can do is add arequires="0.20.0+"
field, so we can filter out those future models that is not compatible with old Translator